Skip to content

Instantly share code, notes, and snippets.

@desbo
Last active February 4, 2020 17:13
Show Gist options
  • Save desbo/5c7dc1f3e1230bd75636 to your computer and use it in GitHub Desktop.
Save desbo/5c7dc1f3e1230bd75636 to your computer and use it in GitHub Desktop.
javascript scan function
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;
}
@kedicesur
Copy link

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]

@varvir
Copy link

varvir commented Feb 14, 2019

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?

@vzaccaria
Copy link

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