Skip to content

Instantly share code, notes, and snippets.

@joaofnds
Last active March 5, 2021 16:40
Show Gist options
  • Save joaofnds/2a9fd139e05666ec31baf0ad334f670a to your computer and use it in GitHub Desktop.
Save joaofnds/2a9fd139e05666ec31baf0ad334f670a to your computer and use it in GitHub Desktop.
reduce, map and filter one-liners. Just because.
const reduce = reducer => memo => ([first, ...rest]) =>
first ? reduce(reducer)(reducer(first)(memo))(rest) : memo
const map = f => arr =>
reduce(mapReducer(f))([])(arr)
const filter = f => arr =>
reduce(filterReducer(f))([])(arr)
const mapReducer = f => element => memo =>
memo.concat(f(element))
const filterReducer = f => element => memo =>
f(element) && memo.concat(element) || memo
const addReducer = a => b => a + b
const add1Reducer = addReducer(1)
const isEven = a => a % 2 == 0
const items = [1,2,3,4,5]
console.log(reduce(addReducer)(0)(items)) //=> 15
console.log(map(add1Reducer)(items)) //=> [2,3,4,5,6]
console.log(filter(isEven)(items)) //=> [2,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment