Last active
February 4, 2020 17:13
-
-
Save desbo/5c7dc1f3e1230bd75636 to your computer and use it in GitHub Desktop.
javascript scan function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scan(xs, f, acc) { | |
var result = []; | |
for (var i = 0; i < xs.length; i++) { | |
acc = result[result.push(f(acc, xs[i])) - 1]; | |
} | |
return result; | |
} |
A more functional, Haskellesque version of
scanl
would be;var scanl = (xs, f, ac) => xs.map((a => e => a = f(a,e))(ac)); scanl([1,2,3,4], (a,e) => a + e, 0); // -> [1, 3, 6, 10]
Thanks! @kedicesur
I've found some scanl
like this!
How can I make scanl
by foldr
or foldl
?
The initial value of the accumulator should be the first element of the prefix scan; here's something similar to the Haskell GHC.List
scan (using lodash):
let scanl = (xs, f, ac) =>
_.concat(ac, xs.length == 0 ? [] : scanl(_.tail(xs), f, f(ac, _.first(xs))));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A more functional, Haskellesque version of
scanl
would be;