Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Last active February 12, 2024 00:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unscriptable/d5a4c520c7e6d5e8dae08a3ae2c4cd12 to your computer and use it in GitHub Desktop.
Save unscriptable/d5a4c520c7e6d5e8dae08a3ae2c4cd12 to your computer and use it in GitHub Desktop.
// Classic array unfold that works with functions that produce
// reasonably-sized output arrays.
export const unfoldWith =
f => x =>
_unfold(f, [], x)
// Recursive unfold function. Will overflow stack for very, very large unfolds.
// f should return null, if done, or return [ curr, next ] values, if not.
const _unfold =
(f, acc, value) => {
const result = f(value)
if (!result) return acc
const [ curr, next ] = result
return _unfold(f, acc.concat(curr), next)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment