Created
February 8, 2016 08:31
-
-
Save spalger/b253fd8aaf04d41822d2 to your computer and use it in GitHub Desktop.
A version of _.partial that caches functions so that `partial(fn, 1, 2, 3) === partial(fn, 1, 2, 3)`.
This file contains 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
var partial = (function () { | |
'use strict'; | |
const caches = new WeakMap() | |
return function partial(fn, ...args) { | |
let toApply = fn | |
while (args.length) { | |
if (!caches.has(toApply)) caches.set(toApply, []) | |
const cache = caches.get(toApply) | |
const arg = args.shift() | |
let cached = cache.find(cache => cache[0] === arg) | |
if (!cached) { | |
const applied = toApply | |
cached = [arg, (...args) => applied(arg, ...args)] | |
cache.push(cached) | |
} | |
toApply = cached[1] | |
} | |
return toApply | |
} | |
}()) |
This file contains 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
var log = (...args) => console.log(...args) | |
log(1, 2, 3) | |
var part1 = partial(log, 1, 2, 3) | |
part1() | |
var part11 = partial(log, 1, 2, 3) | |
console.assert(part1 === part11, 'part 1 and part 11 should be the same function') | |
var part2 = partial(part1, 4) | |
part2() | |
console.assert(part1 !== part2, 'part 1 and part 2 should NOT be the same function') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment