Skip to content

Instantly share code, notes, and snippets.

@janwirth
Created April 24, 2016 11:16
Show Gist options
  • Save janwirth/7db0773643f68f02256d7db7b1be8848 to your computer and use it in GitHub Desktop.
Save janwirth/7db0773643f68f02256d7db7b1be8848 to your computer and use it in GitHub Desktop.
# a function that takes a function and returns a function
reduce = (operation) ->
# the returned function accepts a list
(list) ->
# and applies the operation passed to the outer function recursively to the list
if list.length > 2
return operation list[0], reduce(operation)(list.slice(1, list.length))
# until it is empty
else
return operation list[0], list[1]
# basic mathematical operations that take two arguments
add = (a, b) -> a + b
multiply = (a, b) -> a * b
# combine these operations with reduce to create specialised reduce functions
sum = reduce add
factorial = reduce multiply
console.log()
console.log sum [3 .. 6] # 3 + 4 + 5 + 6
console.log()
console.log factorial [2 .. 4] # 2 * 3 * 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment