Last active
August 29, 2015 14:06
-
-
Save molily/152f29a8f0a2e7d0aa44 to your computer and use it in GitHub Desktop.
Custom memoizer
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
util = | |
# This is faster than working with `arguments` | |
# \u001E is a ASCII Record Separator | |
stringify2: (a, b) -> | |
"#{a}\u001E#{b}" | |
stringify3: (a, b, c) -> | |
"#{a}\u001E#{b}\u001E#{c}" | |
stringify4: (a, b, c, d) -> | |
"#{a}\u001E#{b}\u001E#{c}\u001E#{d}" | |
stringify5: (a, b, c, d, e) -> | |
"#{a}\u001E#{b}\u001E#{c}\u001E#{d}\u001E#{e}" | |
stringify6: (a, b, c, d, e, f) -> | |
"#{a}\u001E#{b}\u001E#{c}\u001E#{d}\u001E#{e}\u001E#{f}" | |
# Memoize a function using an argument stringifier. | |
# Only works with arguments that can be easily converted to strings, | |
# i.e. primitives and objects to a certain degree. | |
# Only works with functions that have up to 6 arguments. | |
# If these constraints are not met, use _.memoize. | |
# Expects a function, returns a function. | |
memoize: (func) -> | |
# This is faster than working with `arguments` | |
# https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments | |
stringify = switch func.length | |
when 0 then util.stringify6 | |
when 1 then _.identity | |
when 2 then util.stringify2 | |
when 3 then util.stringify3 | |
when 4 then util.stringify4 | |
when 5 then util.stringify5 | |
when 6 then util.stringify6 | |
else throw new Error('util.memoize: Too many arguments') | |
memoized = (a, b, c, d, e, f) -> | |
cache = memoized.cache | |
key = stringify a, b, c, d, e, f | |
if key of cache | |
cache[key] | |
else | |
cache[key] = func.call this, a, b, c, d, e, f | |
memoized.cache = {} | |
memoized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment