Reputation:
I have an array with random numbers. I want to add the sum of these numbers by using calling the inner function using the outer function. Basically, using closures.
let arr = [93, 95, 88, 0, 55, 91];
let addMany = function(arr){
let addTwo = function (numbers) {
console.log('array', arr)
console.log('numbers', numbers)
return numbers.reduce((acc,cur) => acc+cur,0)
}
return addTwo(arr);
}
let sum = new addMany(arr);
console.log('final sum', sum)
let res = sum.addTwo();
console.log(res);
I also think I am passing array 'arr' bit too many times. I could be wrong.
I have already tried it using IIFE and modular approach. That one worked fine. I am trying to achieve the same this way.
Upvotes: 1
Views: 67
Reputation: 386680
You could take a instanciable function and a prototype for adding the values.
function Numbers(array) {
this.numbers = array;
}
Numbers.prototype.add = function () {
return this.numbers.reduce((a, b) => a + b, 0);
};
var array = [93, 95, 88, 0, 55, 91],
numbers = new Numbers(array),
result = numbers.add();
console.log(result);
An other possibillity is to use a fluent interface, where you return an object with some functions, where you can chain the functions.
function take(array) {
var object = {
add: () => array.reduce((a, b) => a + b, 0),
update: cb => take(array.map(cb)),
valueOf: () => array
};
return object;
}
var array = [93, 95, 88, 0, 55, 91],
numbers = take(array),
result = numbers.add();
console.log(result);
console.log(numbers.valueOf());
console.log(numbers.update(x => 2 * x).valueOf());
Upvotes: 1
Reputation: 138427
With return addTwo(arr)
you are already returning the result directly. I assume you rather want to return addTwo
itself, and use arr
inside addTwo
:
let addMany = function(arr){
let addTwo = function () {
console.log('array', arr)
return arr.reduce((acc,cur) => acc+cur,0)
};
return addTwo;
}
The you'd call it as:
const closured = addMany(1, 2, 3);
console.log(closured()); // call addTwo
In your example you are calling it as (new addMany(...)).addTwo()
... to achieve that behaviour, remove the return
as constructors do not return anything, amd assign addTwo
as a method to this
(which is the returned object):
let addMany = function(arr){
this.addTwo = function () {
console.log('array', arr);
return arr.reduce((acc,cur) => acc+cur,0)
};
}
Upvotes: 1