[Home] > Snippets  > Languages  > JavaScript  > Fn  >  Delay the evaluation of a function

Delay the evaluation of a function

JavaScript

// returns a new version of `fn` that returns values as lazy evaluable
const thunkfy =
(fn) =>
(...args) =>
() =>
fn(...args)

Examples

const heavyComputation = (x) => doStuff(x)
const unnecessarySlow = manyThings.map(heavyComputation).find((result) => result.criteria)
const probablyFaster = manyThings.map(thunkfy(heavyComputation)).find((thunk) => thunk().criteria)