Skip to content

Instantly share code, notes, and snippets.

@spalger
Created February 8, 2016 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spalger/b253fd8aaf04d41822d2 to your computer and use it in GitHub Desktop.
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)`.
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
}
}())
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