Skip to content

Instantly share code, notes, and snippets.

@foxbunny
Created November 27, 2018 19:57
Show Gist options
  • Save foxbunny/f7779e3af141d1b538a944abf6a65ce8 to your computer and use it in GitHub Desktop.
Save foxbunny/f7779e3af141d1b538a944abf6a65ce8 to your computer and use it in GitHub Desktop.
function reduce(transform, append, arr, init) {
const l = arr.length
let i = 0
let accum = init
if (typeof accum === 'undefined') {
accum = arr[0]
i = 1
}
for (; i < l; i++) {
accum = append(accum, transform(arr[i]))
}
return accum
}
function map(fn, arr) {
return reduce(fn, (newArr, x) => {
newArr.push(x)
return newArr
}, arr)
}
function filter(fn, arr) {
return reduce(id, (newArr, x) => {
if (fn(x)) {
newArr.push(x)
}
return newArr
})
}
function id(x) {
return x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment