Skip to content

Instantly share code, notes, and snippets.

@albertywu
Last active March 28, 2017 18:59
Show Gist options
  • Select an option

  • Save albertywu/3de5195ca35b96606750aaa0dc7d96b3 to your computer and use it in GitHub Desktop.

Select an option

Save albertywu/3de5195ca35b96606750aaa0dc7d96b3 to your computer and use it in GitHub Desktop.
derived collection methods
// given: Array.prototype.forEach, derive:
// 1. reduce
// 2. concat
// 3. map
// 4. filter
// 5. flatten
// 6. flatMap
const reduce = (xs, f, z) => {
var acc = z
xs.forEach(x => acc = f(acc, x))
return acc
}
const concat = (xs, ys) => {
const append = (xs, y) => {
xs.push(y)
return xs
}
return reduce(ys, append, xs)
}
const map = (xs, f) => xs.reduce((a, b) => a.concat(f(b)), [])
const filter = (xs, p) => xs.reduce((a, b) => p(b) ? a.concat(b) : a, [])
const flatten = (xs) => xs.reduce((a, b) => a.concat(b), [])
const flatMap = (xs, f) => xs.reduce((a, b) => flatten(a.concat(f(b))), [])
Object.defineProperty(Array.prototype, 'my', {
get() {
return {
reduce: (f, z) => reduce(this, f, z),
concat: (xs) => concat(this, xs),
map: (f) => map(this, f),
filter: (f) => filter(this, f),
flatten: () => flatten(this),
flatMap: (f) => flatMap(this, f)
}
}
})
/* -- examples below -- */
console.log(
[1, 2, 3].my.reduce((a, b) => a + b, 0)
)
console.log(
[1, 2, 3].my.concat([4, 5])
)
console.log(
[1, 2, 3].my.map(x => x + 1)
)
console.log(
[1, 2, 3, 4, 5, 6, 7].my.filter(x => x % 2 === 0)
)
console.log(
[[1, 2, 3], [4, 5], [6]].my.flatten()
)
console.log(
[1, 2, 3].my.flatMap(x => [x, x])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment