UnitJS/src/UnitJS/Fun/Curry.js

138 lines
1.8 KiB
JavaScript

return {
curry: curry,
flip: flip,
plus: plus,
minus: minus,
substractTo: substractTo,
times: times,
dividedBy: dividedBy,
divide: divide,
gt: gt,
ge: ge,
eq: eq,
neq: neq,
teq: teq,
tneq: tneq,
lt: lt,
le: le,
and: and,
or: or
};
function curry(f, n, t) {
n = n == undefined ? f.length : n;
t = t == undefined ? [] : t;
if(n < 1) {
return f.apply(null, t);
} else {
return function(x) {
var args = Array.prototype.slice.call(arguments);
return curry(f, n - args.length, t.concat(args));
};
}
}
function flip(f) {
return function(a) {
return function(b) {
return f(b)(a);
}
}
}
function plus(a) {
return function(b) {
return a+b;
}
}
function minus(a) {
return function(b) {
return b-a; // reversed to match the expected infix feel : «minus(4)» should substract 4 to whatever's passed to it, not the other way round — which is implemented by substractTo
}
}
function substractTo(a) {
return function(b) {
return a-b;
}
}
function times(a) {
return function(b) {
return a*b;
}
}
function dividedBy(a) {
return function(b) {
return b/a; // same natural order as for minus — the other way round equivalent is divide
}
}
function divide(a) {
return function(b) {
return a/b;
}
}
function gt(a) {
return function(b) {
return b > a;
};
}
function ge(a) {
return function(b) {
return b >= a;
};
}
function eq(a) {
return function(b) {
return b == a;
};
}
function neq(a) {
return function(b) {
return b != a;
};
}
function teq(a) {
return function(b) {
return b === a;
};
}
function tneq(a) {
return function(b) {
return b !== a;
};
}
function lt(a) {
return function(b) {
return b < a;
};
}
function le(a) {
return function(b) {
return b <= a;
};
}
function and(a) {
return function(b) {
return a && b;
};
}
function or(a) {
return function(b) {
return a || b;
};
}