├── README.md └── jsPipe.js /README.md: -------------------------------------------------------------------------------- 1 | Implementing pipes in Javascript using pseudo operator overloading. 2 | ====== 3 | Most of the credit goes to Dr. Axel Rauschmayer that introduced me to the concept of pseudo operator overloading in Javascript in his [great article](http://www.2ality.com/2011/12/fake-operator-overloading.html?m=1) about the subject. 4 | 5 | The code it self is pretty simple (containing just 28 lines of Javascript for the actual pipe implementation). 6 | 7 | I have used the fact that when doing operations on Objects, the method valueOf of the Object is being triggered. 8 | Using a bit of trickery, (and overwriting primitive prototypes) I was able to go as far as to make the following work and produce the expected result: 9 | ```javascript 10 | var result; 11 | p([1,6,4,9,3]) 12 | | sort 13 | | removeLessThenThree 14 | | doubleAll 15 | | print // prints [8, 12, 18] 16 | | function (value) { result = value; } 17 | |pe 18 | ``` 19 | 20 | This little trick is obviously not suitable for real usage, but it is a great example of Javascript's hidden flexibility. 21 | 22 | -------------------------------------------------------------------------------- /jsPipe.js: -------------------------------------------------------------------------------- 1 | var p = (function (exports) { 2 | 3 | var pipedValue, 4 | pipes = [], 5 | addToPipe = false, 6 | runPipe = function () { 7 | var val = pipedValue, idx; 8 | for (idx in pipes) { 9 | val = pipes[idx](val); 10 | } 11 | pipes = []; 12 | addToPipe = false; 13 | 14 | return; 15 | }; 16 | 17 | Function.prototype.valueOf = function () { 18 | return addToPipe ? pipes.push(this) : this; 19 | }; 20 | 21 | exports.pe = {valueOf: runPipe}; 22 | 23 | return function (newPipedValue) { 24 | addToPipe = true; 25 | pipedValue = newPipedValue; 26 | }; 27 | 28 | }(window)); 29 | 30 | 31 | function sort(array) { 32 | return Array.prototype.sort.apply(array); 33 | } 34 | 35 | function removeLessThenThree(array) { 36 | return Array.prototype.filter.apply(array, [ 37 | function (n) { return n > 3; } 38 | ]); 39 | } 40 | 41 | function doubleAll(array) { 42 | return array.map(function(n) { return n*2; } ); 43 | } 44 | 45 | function print(value) { 46 | console.log(value); 47 | } 48 | 49 | var result; 50 | p([1,6,4,9,3]) 51 | | sort 52 | | removeLessThenThree 53 | | doubleAll 54 | | print 55 | | function (value) { result = value; } 56 | |pe 57 | 58 | 59 | --------------------------------------------------------------------------------