Keeping state in curried function - javascript

Is there a way to keep some sort of internal state while writing a curried function?
For example, let's say I want to write a curried function that takes into account the number of times the function was called previously.
I.e. addProgressively(3)(4)(5) = 1*3 + 2*4 + 3*5 = 26.
My approach is to add some counter that increments every time a new curried function is returned but I can't find a good way to keep track of that argument within the addProgressively function.

You could use another variable as closure for the factor.
function addProgressively(x) {
var factor = 1,
sum = factor * x;
function f(y) {
factor++;
sum += factor * y;
return f;
};
f.toString = function () { return sum; };
return f;
}
console.log(addProgressively(3)(4)(5));

Related

How does this higher order function work in JavaScript?

This code is confusing me.
Where does the inner function get the value for x.
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier
}
}
let doubleMe = createMultiplier(2);
This is called currying, what happens is that in the function createMultiplier you get a function and then when you execute that function you pass the parameter x
If you want to execute the function inside the function immediately, you can use this code createMultiplier(2)(5)
If you use console logs you can understand better what happens, I made an example bellow, so you can see first you only get a function and then you can pass the parameter x
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier
}
}
const doubleMe = createMultiplier(2);
console.log(doubleMe)
const result = doubleMe(5)
console.log(result)
The inner function will get the value x. When you invoke: doubleMe(16), for example.
When you call createMultiplier(2) you are setting the multiplier value.
It might be helpful to try and visual what happens when you call createMultiplier(2).
This will create a function that would look like this:
function doubleMe(x) {
return x * 2; // 2 is the multiplier that we supplied to 'createMultiplier'
}
let answer = doubleMe(4);
// answer = 8;
another example:
let tripleMe = createMultiplier(3);
// is the same as writing this
function tripleMe(x) {
return x * 3;
}
let answer = tripleMe(3);
// answer = 9;

What are the parameters in arow function in JS?

please help the newbie figure it out.
There is such a code:
function makeDouble (x) {
return x * 2;
}
var doMath = (x, func) => func(x + 5);
var num = 5;
The task is:
*Using only makeDouble, doMath, and num, make the value of num equal to 20.
num = _____________________________________________________*
I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?
You can translate the arrow function as:
function doMath(x, func) { return func(x+5); }
So you pass a value (x) and a function (func) to the doMath function. func can be any function, for example makeDouble... You can call it like:
doMath(1, makeDouble)
And the result will be (1+5)*2 = 12.
I think you can figure out the rest based on this.
Both parameters in doMath() are being used. The first is argument x will be applied as an argument in the function call of the second argument func and the value returned from that function call will be returned by doMath() itself.
The answer is
num = doMath(num, makeDouble)
There are also 2 parameters in the body of the function.
Let's look a little bit closer
func(x+5)
func is a second parameter of the function and x that we pass to it is a first parameter
Here, func is a callback function. In javascript, you can pass a function as a parameter just like you pass any other variable, for e.g, an integer, object or an array. So here in doMatch you're passing a number and a callback function. When doMatch executes, it calls func with the parameter 10 (5+5). Func, now, will be executed and will return 2*10 (20)
function makeDouble (x) {
return x * 2;
}
var doMath = (x, func) => func(x + 5);
var num = 5;
console.log(doMath(num, makeDouble))
function makeDouble (x) {
return x * 2;
}
const doMath = (x, func) => func(x + 5);
const num = 5;
let result = doMath(num, makeDouble);
console.log(result);// 20
doMath(x, func) is an arrow function which takes two parameters. The first para meters is your numeric value, and the second is a function which in this case is makeDouble(x). Inside the arrow function, the makeDouble(x) function is called with the numeric parameter + 5 like makeDouble( num + 5). In this case, num is added five inside the constructor, so this time makeDouble returns the product of 10 * 2. Also, I would suggest to revise the use of var. Currently the use of let and const is preferred over var.
Arrow functions can take other functions as parameters, which is great to work with recursion and functional programming.
Thank very much you all!
My problem was that I did not notice that the makeDouble() function in the parameters of the arrow function did not return the value, but the content of the function itself. And then in the body of the arrow function, it can be to call the makeDouble() function as a parameter.

Call function inside of another function

Using the factory pattern, i wrote snippets of code that use firebase cloud functions :
//Notice that when instantiated it does calculations and returns a value
function sumAndMultiply(int number) {
function sum(i) {
return i + 1;
}
function multiply(i) {
return i * 3;
}
const x = sum(number);
const y = multiply(x);
return y;
}
everting working fine, but, what i can make if i need to unit test multiply() or sum() function?
describe('Unit testing', () => {
it('test sum function', () => {
//How i can call sum function without call sumAndMultiply?
let result = sum(3);
expect(result == 4);
});
it('test multiply function', () => {
//How i can call multiply function without call sumAndMultiply?
let result = multiply(3);
expect(result == 9);
});
});
As I'm talking about unit testing, one idea is to avoid editing the code used for production, but changes that make the code more readable or better are accepted
The problem with your approach is that your code is tightly coupled with the implementation of sum and multiply functions. This makes testing way harder, and testing the units of sum and multiply would take a lot of effort.
One way of solving this code smell is to use Dependency Injection. This way, you would provide both the sum and multiply functions, but the interface of sumAndMultiplyfunctions would need to change. This way, your code would become:
//Notice that when instantiated it does calculations and returns a value
function sumAndMultiply(number, sum, multiply) {
const x = sum(number);
const y = multiply(x);
return y;
}
function sum(i) {
return i + 1;
}
function multiply(i) {
return i * 3;
}
That way, you INJECT these functions. Good thing is that now we can unit test both our sum and multiply functions as you've sugested. Even better, we can now mock our sum and multiply functions on sumAndMultiply.

Javascript high order functions - How do pass a variable from to function to it's parent function

I'm trying to solve this algorithm. I think I'm very close.
I need the seven function to pass the a variable to the timesFive function. OR is there a way I can pass the * 5 operation from timesFive to seven in order to get the desired result?
I'm not allowed to have variables outside of these two function scopes.
I can add another argument to timesFive as long as b remains the first argument.
function seven(action) {
var a = 7;
return action;
}
function timesFive(b) {
console.log(a); // How can I access "a"?
return a * 5;
}
console.log(seven(timesFive())); // Desired result: 35
timeFive should return a function and seven should expect a function as a parameter. Then seven can simply call the function that timesFive() returns (so basically returning the * 5 operation as you mentioned in your question):
function seven(action) {
var a = 7;
return action(a);
}
function timesFive() {
return (a) => a * 5;
}
console.log(seven(timesFive())); // Desired result: 35
BTW
You'll often see these kind of exercises written in a way that mimics the functional notation from math, like:
const seven = (action) => action(7);
const timesFive = () => (a) => a * 5;
console.log(seven(timesFive())); // Desired result: 35

write a twice function that multiplies one number four times by itself in the format below

I want to write a function called twice that takes a function f and a value x as its parameters and returns f(f(x)). For example,
twice(function (x) { return x * x; }, 3)
should return 81. How do I do it?
Call the anonymous function twice which is passed as an argument. On the second call use the returned value of first execution as the argument.
function twice(funct, a) {
return funct(funct(a));
}
console.log(
twice(function(x) {
return x * x;
}, 3)
);
What is stopping you? You already has the answer with you. It is working pretty fine.
function twice(f, x) {
return f(f(x));
}
var result = twice(function(n){return n*n;}, 3);
console.log(result);

Categories

Resources