function asArray(quasiArray, start) {
var result = [];
for (var i = (start || 0); i < quasiArray.length; i++)
result.push(quasiArray[i]);
return result;
}
function partial(func) {
var fixedArgs = asArray(arguments, 1);
return function(){
return func.apply(null, fixedArgs.concat(asArray(arguments)));
};
}
function compose(func1, func2) {
return function() {
return func1(func2.apply(null, arguments));
};
}
var isUndefined = partial(op["==="], undefined);
var isDefined = compose(op["!"], isUndefined);
show(isDefined(Math.PI));
show(isDefined(Math.PIE));
Why can't the function compose simply return:
func1(func2);
and give the proper output. I thought the partial function which is stored in the variable isUndefined already returns func.apply(null, [fixed, arguments])
var op = {
"+": function(a, b){return a + b;},
"==": function(a, b){return a == b;},
"===": function(a, b){return a === b;},
"!": function(a){return !a;}
/* and so on */
};
Both
partial
andcompose
are higher-order functions.isUndefined
will return a function that, when invoked, will invoke the originally passed function with the original arguments plus any new arguments passed at invocation.To answer your question, you'd be calling
apply
on the function returned frompartial
which will in turn, callapply
on the function originally passed topartial
.You want
compose
to return a function that when called, will return the result of calling the first function passed the second function as an argument (with the second function passed the arguments passed to thecompose
invocation). Ifcompose
returnedfunc1(func2)
, then you'd assign the result of the invocation to the variableisDefined
.EDIT:
Now that we have
op
, let's try to decompose this:this is equivalent to
isUndefined
is assigned a function that, when called, will call the function passed as the first argument topartial
, passing inundefined
as the first argument to that function call, followed by the arguments passed to the functionisUndefined
i.e.isDefined
composesisUndefined
with another function that negates the result ofisUndefined
.is equivalent to
which is equivalent to (renamed variables for clarity)
If we look at what we have so far and substituting for readability, boils down to a function that takes an argument and compares it to undefined, negates the result and returns a boolean
So lets simply dissect it. Assuming we have this compose function:
What will happen when you use it like this?
The second function would be call immediately outputting
2
, and straight afterwards the first function will be called outputting1
.a
will beundefined
, because the first function does not return anything.What you want combine to do, is to return a new function, that combines the two other functions and that you can call at will.
Doing the above all on the original compose, will return a new function, that, when you call it with
a()
will output2
and then1
.