Javascript Array chain(f)

Description

Javascript Array chain(f)


Array.prototype.chain = function(f) {
 return this.reduce(function(acc, it) {
  return acc.concat(f(it));
 }, []);/*from www  .  ja  v  a  2  s .  c  o  m*/
};

var arr = Array.of('cat,dog', 'fish, bird').chain(function(it) {
  return it.split(',');
});
console.log(arr); // [ 'cat', 'dog', 'fish', ' bird' ]


// contrast to map
var arr2 = Array.of('cat,dog', 'fish, bird').map(function(it) {
 return it.split(',');
});

console.log(arr2); // [ [ 'cat', 'dog' ], [ 'fish', ' bird' ] ]



PreviousNext

Related