Chain onto native Javascript functions

Viewed 508

tl;dr:

How can I chain onto Javascript's map() with my own function? Like -

stuff.map(i => i.key).avg()

where avg() is my own function to compute the average of the array returned by map?


In moving away from objects and toward functional programming with pure functions, I've lost the handy

return this;

that allows me to chain.

If I have

let stuff = [
  {id: 1, name: 'tuan', country: 'VN', age: 23},
  {id: 2, name: 'nhung', country: 'US', age: 25},
  ...

//my own filter to pass as a param to native filter()
var filt = x => j => j.country === x;

//my own reducer for an array that computes an average
let avg = (arr) => (arr.reduce((acc, i) => acc + i) / arr.length);

then

stuff.filter(filt('VN')).map(i => i.age)

would return something like

[23, 34, 45]

but

stuff.filter(filt('VN')).map(i => i.age).avg()

gives an error like

filter().map().avg() is not a function 

How can we write functions that chain onto the native ones?

5 Answers
Related