Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active December 12, 2015 08:58
Show Gist options
  • Save AutoSponge/4747439 to your computer and use it in GitHub Desktop.
Save AutoSponge/4747439 to your computer and use it in GitHub Desktop.
(function (global, undef) {
/**
* memoizes functions with a single, primitive argument
* @param f {Function}
* @returns {Function}
*/
function memoize(f) {
var cache = (f.memoize = f.memoize || {});
return function (arg) {
return (arg in cache) ? cache[arg] : cache[arg] = f.call(this, arg);
};
}
/**
* create a function to compose n functions
* @param n {Integer}
* @returns {Function}
*/
var c = memoize(function (n) {
if (n < 1) {
return new Function;
}
var i;
var params = "";
var vars = "\treturn function () {\n";
var body = "\t\treturn _0;\n";
for (i = 0; i < n; i += 1) {
params += i ? (", fn" + i) : "fn" + i;
}
vars += "\t\tvar _" + --i + " = fn" + i + ".apply(this, arguments);\n";
while (i--) {
vars += "\t\tvar _" + i + " = fn" + i + ".call(this, _" + (i + 1) + ");\n"
}
body += "\t};";
return Function(params, vars + body);
});
/**
* Composes 1-n functions
* @param {Function}
* @returns {Function}
*/
global.compose = function () {
return c(arguments.length).apply(this, arguments);
};
}(this));
function slice(obj) {
return Array.prototype.slice.call(obj, 0);
}
function makeArray(obj) {
if (obj === null || obj === undefined) {
return [];
}
if (obj instanceof Array) {
return obj;
}
if (obj instanceof Object && "length" in obj && "0" in obj) {
return slice(obj);
}
return [obj];
}
var fixedArr = [1,2,3];
function fixed() {
return fixedArr;
}
function makeUnary(arg) {
if (arguments.length > 1) {
return arguments;
}
return arg;
}
//compose slice and makeArray passing fixed as a parameter
console.assert(JSON.stringify(compose(slice, makeArray)(fixed())) === "[1,2,3]");
console.assert(compose(slice, makeArray)(fixed()) !== fixed());
//compose slice, makeArray, and fixed
console.assert(JSON.stringify(compose(slice, makeArray, fixed)()) === "[1,2,3]");
console.assert(compose(slice, makeArray, fixed)() !== fixed());
//compose slice, makeArray, and makeUnary so any signature will produce a list
var list = compose(slice, makeArray, makeUnary);
console.assert(JSON.stringify(list(1)) === "[1]");
console.assert(JSON.stringify(list(1,2)) === "[1,2]");
console.assert(JSON.stringify(list([1,2])) === "[1,2]");
console.assert(JSON.stringify(list({0:1,1:2,length:2})) === "[1,2]");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment