Skip to content

Instantly share code, notes, and snippets.

@sdepold
Created October 20, 2010 12:44
Show Gist options
  • Save sdepold/636341 to your computer and use it in GitHub Desktop.
Save sdepold/636341 to your computer and use it in GitHub Desktop.
function convertToArray(iterable) {
return Array.prototype.slice.call(arguments);
}
Function.prototype.curry = function(){
if (!arguments.length) return this;
var __method = this, args = convertToArray(arguments);
return function() {
return __method.apply(this, args.concat(convertToArray(arguments)));
}
}
var mixinCache = (function() {
var cache = {}
// signature: function(identifier, func, param1, param2, param3, ...)
var executor = function() {
// why is arguments[0] an array???
var func = arguments[0][0], identifier = func.toString(), params = []
for(var i = 1; i < arguments.length; i++) params.push(arguments[i][0])
var paramsIdentifier = params.join(", ")
if(cache.hasOwnProperty(identifier) && cache[identifier].hasOwnProperty(paramsIdentifier)) {
console.log("cached baby!")
return cache[identifier][paramsIdentifier]
} else {
console.log("not cached yet!")
cache[identifier] = cache[identifier] || {}
return cache[identifier][paramsIdentifier] = func.call(null, params)
}
}
return executor
})()
var sin = function(arg) { return Math.sin(arg) }
// when doing curry twice, the second argument is an array :-/
// e.g. mixinCache.curry('sin').curry(sin)(3) => arg0 = 'sin', arg1 = [func sin, 3]
var cachedSin = mixinCache.curry(sin)
var isPrime = function(num) {
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
var cachedIsPrime = mixinCache.curry(isPrime)
console.log(cachedSin(2))
console.log(cachedSin(2))
console.log(cachedIsPrime(524287))
console.log(cachedIsPrime(524287))
console.log(cachedIsPrime(524287))
console.log(cachedIsPrime(524287))
console.log(cachedIsPrime(524287))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment