If one thing this is clear from this discussion, it is that different
programmers have different preferences (perhaps even changeable
depending on use case). So, no single standard API will suit everyone
and the language support for different patterns could be improved.

Meanwhile, it seems one can get both via proxies (wrapping selected
target methods to return this or argument). I had some trouble finding a direct proxy implementation in released engines, so I'm using Tom's harmony-reflect shim in node). See code below, which outputs:

   $ node --harmony proxy-chain.js
   undefined { xs: [ 5 ] }
   { xs: [ 5, 6 ] }
   { xs: [ 5, 6, 7, 8 ] }
   9 { xs: [ 5, 6, 7, 8, 9 ] }

The original collection's add method returns undefined (line 1), the this-chained proxy's add returns this (lines 2,3), the value-chained proxy's add returns the added value (line 4).

Claus


// install npm install harmony-reflect
// run: node --harmony proxy-chain.js

var Reflect = require('harmony-reflect'); // also shims direct proxies

// enable chainable this-return for methods in target
function chain_this(target,methods) {
 return Proxy(target
             ,{get:function(target,name,receiver){
                     return methods.indexOf(name)!==-1
                            ? function(){
                                target[name].apply(target,arguments);
                                return receiver
                              }
                            : target[name]
                   }
              });
}

// enable chainable value-return for unary! methods in target
function chain_value(target,methods) {
 return Proxy(target
             ,{get:function(target,name,receiver){
                     return methods.indexOf(name)!==-1
                            ? function(arg){
                                target[name](arg);
                                return arg
                              }
                            : target[name]
                   }
              });
}


function X() { this.xs = []; }
X.prototype.add = function(x){ this.xs.push(x) }; // returns void

var x = new X();

console.log( x.add(5) , x );


var xt = chain_this(x,['add']);

console.log( xt.add(6) );

console.log( xt.add(7).add(8) );


var xv = chain_value(x,['add']);

console.log( xv.add(9) , xv );

_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to