Consider the following example for calculating the 20% tip of an array of checks.
map function accepts a closure that in the example returns a 20% tip.
Rather than using an inline
tip function it makes sense to pass a reference to a defined function, so we can reuse the
Probably you don’t always want to tip 20%. Sometimes you want to tip a little more, other times you may want to tip a little less. Therefore you want to pass in the percentage to
tip as an argument rather than tipping 20% all the time.
Adding the percentage as argument is of course simple. But now we can no longer pass the tip function into map since it needs an extra argument that map ain’t going to provide. Rather than using an inline function that calls
tip with 20%, let’s explore another possibility.
Partial functions is a functional programming concept. A partial function takes a function and fewer arguments than normal. It returns a function that takes the remaining arguments. When called the returned function call the original function with both sets of arguments.
We need a function
arguments is not an actual array but an object that supports array lookups. It lacks most array functions (like
map), but we can call the functions from the array prototype using
arguments as their context.]
partial must return a function that takes the remaining arguments and, as invoked, calls the original function with the combined argument arrays. Since
partial can only access arguments in form of an array we cannot call the original function (i.e. using parentheses or
call) but must
apply it instead. This way the array of arguments we pass to
apply is mapped to arguments of the original function.
partial the general tip function can be passed into map as a 20%-tip function like this.
partial function only works for pure functions and not for a function that gets needs some state of the object it is in. This is due to the function being applied without a context.
tip function obviously wouldn’t have worked out if the
percentage argument was last.