Skip to content

Instantly share code, notes, and snippets.

@honzabrecka
Created August 2, 2017 11:13
Show Gist options
  • Save honzabrecka/238a9cd8ac88b4b4713e073494f1ef33 to your computer and use it in GitHub Desktop.
Save honzabrecka/238a9cd8ac88b4b4713e073494f1ef33 to your computer and use it in GitHub Desktop.
function reduce(f, init, col) {
let result = init
for (i = 0; i < col.length; i++)
result = f(result, col[i], i, col)
return result
}
function recursiveReduce(f, init, col) {
function $(i, result) {
return i === col.length
? result
: $(i + 1, f(result, col[i], i, col))
}
return $(0, init)
}
function range(from, to) {
const col = []
for (i = from; i < to; i++)
col.push(i)
return col
}
const sum = (a, b) => a + b
// použití
reduce(sum, 0, [1, 2, 3])
recursiveReduce(sum, 0, [1, 2, 3])
// bacha na stack při rekurzi!
reduce(sum, 0, range(0, 1000000))
recursiveReduce(sum, 0, range(0, 1000000))// StackOverflow error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment