Javascript closure returning string instead of function - javascript

I am trying to write a simple compose function that takes a series of functions, and composes them like so:
compose(func1, func2, func3)(n) === func1(func2(func3(n)))
I do so by recursing through a rest parameter,
var compose = function(...args) {
return (n) => {
if (args.length) {
return args[0](compose(args.slice(1)));
} else {
return n;
}
};
};
I then attempt to compose a new function made up of a series of other functions,
var plusOneAndTwo = compose((n) => n + 1, (n) => n + 2);
plusOneAndTwo(1);
Instead of returning 4, I get back the body of the inner, anonymous function inside of compose as a string,
"(n) => {
if (args.length) {
return args[0](compose(args.slice(1)));
} else {
return n;
}
}1"
Note the "1" at the end of the string! I have no idea why this is happening, and in particular I'm perplexed by how a 1 is getting appended to the end of that.
Any clarification is appreciated, thanks!

The problem occurs in the recursive call to compose.
In particular, you are not passing the parameter n to it (as also suggested by others above). Furthermore, you need to expand the rest parameter in the call.
You should use something like:
return args[0](compose(...args.slice(1))(n))
In your case, you are simply returning:
return args[0](compose(args.slice(1)));
In your example you call compose((n) => n + 1, (n) => n + 2);. Compose then returns a function taking n as a parameter. In this function, args.length becomes 1 (i.e. true-is), args[0] becomes (n) => n + 1 and args.slice(1) becomes [(n) => n + 2].
Next, you call this returned function with the parameter n = 1. As args.length is 1, the if() statement will go into the if() case. In this if case, it will call args[0] with the argument compose(args.slice(1)).
In this recursive call, compose(args.slice(1)) is evaluated to a function, taking n as a parameter and the same function body.
This function is then given as the parameter n to args[0] (in the outer call). Recall that args[0] in this scenario is the function (n) => n + 1.
Thus the call as a whole is equivalent to:
// returned from the recursive call to compose(args.slice(1))
var n = (n) => {
if (args.length) {
return args[0](compose(args.slice(1)));
} else {
return n;
}
}
// applied to arg[0] == (n) => n + 1
return n + 1
This means that the code will attempt to add a function with the number 1.
In JavaScript adding a function and a number results in both objects coerced into a string. Casting a number into a string is trivial, casting a function into a string returns the function source code. These strings are then added to give the return value you saw: The function body as a string with the 1 at the end.

You just have to call the composed function:
return args[0](compose(...args.slice(1))(n));
Or without recursion it'll be:
const compose = (...fns) => start => fns.reduceRight((acc, fn) => fn(acc), start);

You could take a different approach by returning a new function or returning the last function for calling with arguments.
const
compose = (...fns) => fns.length
? v => compose(...fns.slice(0, -1))(fns.pop()(v))
: v => v,
fn1 = n => n * 5,
fn2 = n => n + 2,
fn3 = n => n * 7;
console.log(fn1(fn2(fn3(1))));
console.log(compose(fn1, fn2, fn3)(1));

Related

How Array.reduce put functions as parameters in function composition?

Can somebody explain to me how Array.reduce can put functions as arguments in function composition like this:
const composeB = (f, g) => x => f(g(x))
const add = a => b => a + b
const add5 = add(5)
const double = a => a * 2
const add5ThenDouble = [double, add5].reduce(composeB)
console.log(add5ThenDouble(6)); // 22
So, according to my knowledge (which is not enough) of reduce function is that Array.reduce iterate through an array like this - it takes each of array values and puts them through callback function with another argument (lets call it accumulator). The next array value will undergo the same callback function, but with (eventually) changed accumulator value.
What confuses me in code example above is:
1) Array is list of functions [double, add5].
2) In first iteration, composeB will receive arguments: f=accumulator (empty value), g=double(function). ComposeB should return emptyvalue(double(6)) (or maybe not??)
I know that I am missing something, but can someone explain me what?
The documentation for reduce says that the first argument is
A function to execute on each element in the array (except for the first, if no initialValue is supplied).
So in this case, you have not supplied an initialValue and so compose is only called once (with arguments double and add5).
var inc = (x) => ++x, // increment +1
x2 = (x) => x*2, // multiply by 2
sq = (x) => x*x; // square
var compose = (f,g) => (_) => g(f(_));
var f1 = [ sq, inc, inc ].reduce(compose, (_) => _);
f1(10); // 102
var f2 = [ inc, sq, inc ].reduce(compose, (_) => _);
f2(10); // 122
See the code above, notice:
identity function (_) => _ as default value (second argument) for reduce
compose will NOT return a number, it will return a FUNCTION that is a composition of all the functions that were passed in before... So - only when you CALL the (say) f1, only then the functions will be executed.
we are putting all the functions from list [a,b,c,d,e] into a chain of e,d,c,b,a (reverse order!) and then execute as e(d(c(b(a(10))))) getting the order we actually wanted.
(f,g) => (_) => g(f(_)) <-- function arguments are actually reversed when calling them. Longer version: function compose (f, g) { return function (z) { return g(f(z)); }; }
p.s.: i use var because i can ;)

Currying function with unknown arguments in JavaScript

In a recent interview, I was asked to write a function that adds numbers and accepts parameters like this:
add(1)(2)(3) // result is 6
add(1,2)(3,4)(5) // result is 15
The number of parameters is not fixed, and the arguments can be either passed in sets or individually.
How can I implement this add function?
Given your examples, the number of parameters is fixed in some ways.
As #ASDFGerte pointed out, your examples seem to return the result after three invocations. In this case a simple implementation without introducing terms like variadic and currying could be
function add(...args1){
return function(...args2){
return function(...args3){
return args1.concat(args2).concat(args3).reduce((a,b)=>a+b)}}}
console.log(add(1)(2)(3))
console.log(add(1,2)(3,4)(5))
Every invocation accepts a variable number of parameters.
However it would be nice to generalize the construction of this nested functions structure and you can accomplish that with currying.
But if you want to allow an arbitrary number of invocations, when you should stop returning a new function and return the result? There is no way to know, and this is a simple, unaccurate and partial explanation to give you the idea of why they said you cannot accomplish what they asked you.
So the ultimate question is: is it possible that you misunderstood the question? Or maybe it was just a trick to test you
Edit
Another option would be to actually invoke the function when no arguments are passed in, change the call to add(1)(2)(3)()
Here an example recursive implementation
function sum (...args) {
let s = args.reduce((a,b)=>a+b)
return function (...x) {
return x.length == 0 ? s : sum(s, ...x)
};
}
console.log(sum(1,2)(2,3,4)(2)())
At every invocation computes the sum of current parameters and then return a new function that:
if is invoked without parameters just return the current sum
if other numbers are passed in, invokes recursively sum passing the actual sum and the new numbers
I'm a bit late to the party, but something like this would work (a bit hacky though in my opinion):
const add = (a, ...restA) => {
const fn = (b, ...restB) => {
return add([a, ...restA].reduce((x, y) => x + y) + [b, ...restB].reduce((x, y) => x + y))
};
fn.valueOf = () => {
return [a, ...restA].reduce((x, y) => x + y)
};
return fn;
}
This function returns a function with a value of the sum. The tests below are outputing the coerced values instead of the actual functions.
console.log(+add(1,2)(3,4)(5)); // 15
console.log(+add(1)) // 1
console.log(+add(1)(2)) // 3
console.log(+add(1)(2)(3)) // 6
console.log(+add(1)(2)(3)(4)) // 10
Since it's a currying function, it will always return another function so you can do something like this:
const addTwo = add(2);
console.log(+addTwo(5)); // 7
using reduce and spread it can be done as below
function calc(...args1){
return function (...args2){
return function (...args3){
let merge = [...args1, ...args2, ...args3]
return merge.reduce((x ,y)=> x + y) ;
}
}
}
let sum = calc(10)(1)(4);
console.log("sum",sum);
They probably wanted to know how comfortable you were with "javascript internals", such as how and when methods like Function#toString and Function#valueOf, Function#[Symbol.toPrimitive] are called under the hood.
const add = (...numbers) => {
const cadd = (...args) => add(...args, ...numbers);
cadd[Symbol.toPrimitive] = () => numbers.reduce((a, b) => a + b);
return cadd;
}
console.log(
`add(1,2)(3,4)(5) =>`, add(1,2)(3,4)(5),
); // result is 15
console.log(
`add(1,2) =>`, add(1,2),
); // result is 3
console.log(
`add(1,2)(5)(1,2)(5)(1,2)(5)(1,2)(5) =>`, add(1,2)(5)(1,2)(5)(1,2)(5)(1,2)(5),
); // result is 32

Return required for Ternary Operator

why do we need to add 'return' to the ternary operator on line 4?
when I evaluate a standalone ternary operator such as 'five' === 'five' ? 1 : 0 I get a return value of 1. So my understanding is that a value was returned with that expression. So the 'return' on line 4 seems unnecessary although it is definitely needed for the code to run.
var countOccurrence = function(array, value) {
var n =array.length - 1;
if(n===0) {
return array[0] === value ? 1 : 0;
} else {
if(array[n] === value) {
return 1 + countOccurrence(array.slice(0,n), value)
} else {
return countOccurrence(array.slice(0,n), value)
}
}
};
Unlike input on the devtools console, JavaScript functions do not return the result value of the last statement to be evaluated. You need an explicit return keyword to terminate the function and return a result to the caller. If the function body evaluation ends without a return, the value undefined is returned implicitly.
Like the previous answers have stated, you need to explicitly return a result, otherwise the result of a function will be undefined. This can be done by using the return keyword, but since javascript ES6, the return keyword is no longer neccessary when using an arrow function expression.
The following function:
const fn = function(x, y) {
return x+y;
}
could be written in ES6 in the following way (without the need for the return keyword):
const fn = (x, y) => x+y;
With this in mind (and some functional programming principles), we could rewrite your function countOccurrence in the following way:
const countOccurrence = array => value => array.filter(y => y == value).length;
const array = [2,3,2,4,2];
const valueToCheck = 2;
console.log(countOccurrence(array)(valueToCheck)); // => 3

JavaScript Add function called as many times as you wanted

The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that?
function add () {
}
add(1)(2)(3)(); //6
add(5)(6)(7)(8)(9)() //35
I think this is exactly what you need:
function add(value) {
return (val) => val !== undefined ? add(value + val) : value;
}
console.log(add(2)(2)()); //4
console.log(add(2)(2)(5)(5)()); //14
console.log(add(1)(1)(1)(1)(1)()); //5
console.log(add(1)(1)(0)(1)(1)()); //4
How it works
For every call it declares a function inside, in result it creates a closure(persistent scope) in every call. Function created in that way has access to its parameter + previous call parameter due to existing closure.
So if I call add(2)(3)():
add(2) - returns function with visible 2 value
add(2)(3) - calls second function with input 2 + 3 and return third function with visible value equal 5
add(2)(3)() - ends computation due to empty param and returns the value
To finish the computation pipe the last call needs to be without a value.
The basic idea is to create a closure with a variable sum that we can update, and return the sum if the value is undefined, or the the inner function:
const add = (n) => {
let sum;
const inner = (n) => n === undefined ? sum : (sum = (sum || 0) + n, inner);
return inner(n);
};
console.log(add(1)(2)(3)()); //6
console.log(add(5)(6)(7)(8)(9)()); //35
I would just use a Spread syntax like this:
function add(...values) {
return values.reduce((sum, value) => sum + value, 0)
}
console.log(add(1, 4, 34, 45, 3, 4, 5))

create compose function in functional programming approach

I am trying to understand how compose works by recreating compose. As part of that I've created a simple calculator to take a value and based on that value return interest.
https://medium.com/javascript-scene/reduce-composing-software-fe22f0c39a1d#.rxqm3dqje
Essentially ultimate goal is to create a function that can do below.
https://github.com/ngrx/example-app/blob/master/src/app/reducers/index.ts#L150
Nice to have: been able to pass multiple deposit values, and and may be calculate compound interest over time.
It would be good have some comments so I understand what is going on from Functional programming approach.
(()=>{
// Generic compose function to handle anything
const compose = (...fns) => (x) => {
return fns.reduceRight((acc,fn)=>{
return fn(acc);
}, x)
};
const getInterest = (value) => {
if (value < 1000) {
return 1 / 100
}
if (value < 10000) {
return 2 / 100
}
return 3 / 100;
};
const getDeposit = (value) => {
return value;
};
const calculator = compose(getDeposit, getInterest)
console.log(calculator(1000)) // Should return value of 1000 * interest rate. I currently get 0.03
})();
The issue is that you never multiply the two values: value and interest.
You should therefore pass another function into the composition, which will multiply the two previous results.
This means that this function will need to get 2 arguments, while the other two only take one. In general a function could need any number of arguments. So the composer should be able to pass enough arguments to each function. Furthermore, functions may also return more than one value -- in the form of an array. These values should be made available as arguments for the next function in the chain, while keeping any previous returned values available as well.
Another thing is that although you have implemented compose to execute the functions from right to left, the sequence of function you pass seem to suggest you expect them to execute from left to right, first getDeposit, and then getInterest, even though in your case it works both ways. Still, I would suggest to switch their positions.
So here is how you can make all that work:
(()=>{
// Generic compose function to handle anything
const compose = (...fns) => (...args) => {
return fns.reduceRight((acc,fn)=>{
// Call the function with all values we have gathered so far
let ret = fn.apply(null, acc);
// If function returns a non-array, turn it into an array with one value
if (!Array.isArray(ret)) ret = [ret];
// Queue the returned value(s) back into the accumulator, so they can
// serve as arguments for the next function call
acc.unshift(...ret);
return acc;
}, args)[0]; // only return the last inserted value
};
const getInterest = (value) => {
return value < 1000 ? 0.01
: value < 10000 ? 0.02
: 0.03;
};
const multiply = (a, b) => a * b;
const getDeposit = (value) => value;
// Be aware the the rightmost function is executed first:
const calculator = compose(multiply, getInterest, getDeposit);
console.log(calculator(1000)) // Returns 20, which is 0.02 * 1000
})();
Alternative: pass along an object
The above implementation is not a pure compose implementation, since it passes not only the previous function result on to the next, but all previous functions results. This is not disturbing, and opens doors for more complex functions, but if you wanted to stick more to the original compose idea, you have a problem to solve:
As you want to have a function in the chain that only returns the rate, the next function in the chain will then only get the rate -- nothing else. With just that one piece of information it is of course not possible to calculate the result, which also needs the value as input.
You could "solve" this, by letting getInterest return an object, that not only has the rate in it, but also the value that was passed to it. You could also implement this with an array.
Here it is with an object implementation:
(()=>{
// Straightforward implementation:
const compose = (...fns) => (...args) => {
return fns.reduceRight((acc,fn)=>{
return fn(acc);
}, args);
};
// Return an object with two properties: value & interest
const getInterest = (value) => ({
value,
interest: value < 1000 ? 0.01
: value < 10000 ? 0.02
: 0.03
});
// Expect an object as argument, with two properties:
const getInterestAmount = ({value, interest}) => value * interest;
const getDeposit = (value) => value;
// Be aware the the rightmost function is executed first:
const calculator = compose(getInterestAmount, getInterest, getDeposit);
console.log(calculator(1000)) // Returns 20, which is 0.02 * 1000
})();
With this approach you can pass along objects that have many more properties, and so anything becomes possible.
I actually liked your simple compose function (it just only works for unary functions), and I think you can also make it work for now by making these changes:
rename getInterest to ...Rate, since it returns a multiplier for a value.
add a new getInterest function that takes a "rate getter" and a "value" in curried form: getRate => x => getRate(x) * x
swap the order of your calculator arguments in compose
I think compose usually works from right to left (f => g => x
=> f(g(x))), and pipe works from left to right (f => g => x => g(f(x)))
(()=>{
// Generic compose function to handle anything
const compose = (...fns) => (x) => {
return fns.reduceRight((acc,fn)=>{
return fn(acc);
}, x)
};
const defaultRate = (value) => {
if (value < 1000) {
return 1 / 100
}
if (value < 10000) {
return 2 / 100
}
return 3 / 100;
};
const getInterest = getRate => x => getRate(x) * x;
const getDeposit = x => 1000;
const calculator = compose(getInterest(defaultRate), getDeposit);
console.log(calculator());
})();

Categories

Resources