If I have an array someArray
that I first want to do some operations on and then pass that result to a function arrfun
that takes an array as an argument. Like the following
let arr = someArray.filter(foo).map(bar)
let result = arrfun(arr)
In the above scenario I would like to avoid having to assign an intermediary variable to be passed to arrfun
. I would like to have something like this.
Object.prototype.pipe = function(f) {return f(this)}
let result = someArray.filter(foo).map(bar).pipe(arrfun)
- In lieu of a
.pipe()
how would you solve this? - Would it be sensible to introduce that function to
Object
? - Is
pipe
the best name for such a function?chain
?pass
?
New example
const pc = options => options
.join(' ')
.match(/--[\w.]* [\w.]*/g)
.map(s => s.slice(2).split(' '))
.map(([key, value]) => ({key, value}))
.map(nestObject)
.reduce((acc, val) => Object.assign(acc, val), {})
const nestObject = ({key, value}) => key
.split('.')
.reverse()
.reduce((inner, key) => ({[key]: inner}), value)
In the above example a problem is that .match
returns null
if no match is found. Using .pipe
you could solve it ny changing that line to
.pipe(s => s.match(/--[\w.]* [\w.]*/g) || [])
How would you solve this one without pipe
?