Roscoe Roscoe - 1 month ago 10
Javascript Question

How to return a function that needs 2 parameters with 1

I believe I have solved this problem but having an issue only passing 1 parameter to my final function to return result. Here is the question

For instance, consider the function getDouble. When run twice on value 3, yields 12 as shown below.

getDouble(3) => 6
getDouble(6) => 12


Let us name the new function createIterator and we should be able to obtain the same result using createIterator as shown below:

var doubleIterator = createIterator(getDouble, 2); // This means, it runs *getDouble* twice
doubleIterator(3) => 12


For the sake of simplicity, all function inputs to createIterator would be functions returning a small number and number of iterations would always be integers.

Here is my answer:

function getDouble(num){
newNum = num * 2
return newNum
}


var createIterator = function (func, n) {
var results = [];
var result;
result = func;
results.push(func);

for(var i = 0;i < n - 1; i++){
results.push(results[i] * 2);
}

return results;

};

// var doubleIterator = createIterator(getDouble(3),2).slice(-1).pop();


Here is the function that I am trying to make to have only 1 call. Everything is working properly above but I must be able to submit this entire response only passing one parameter this this function:

function doubleIterator(d){
// var n;
// createIterator.call(this,n)
return createIterator(getDouble(d),n).slice(-1).pop();
}


console.log(doubleIterator);

Answer

You could use this definition of createIterator:

function createIterator(func, n) {
    return function (arg) {
        for (var i = 0; i < n; i++) arg = func(arg);
        return arg;
    };
}

function getDouble(num){
    return num * 2;
}

var doubleIterator = createIterator(getDouble, 2);

console.log(doubleIterator(3)); // => 12

You could also write the same with reduce and bind:

function createIterator(func, n) {
    return [].reduce.bind([...Array(n)], arg => func(arg));
}

function getDouble(num){
    return num * 2;
}

var doubleIterator = createIterator(getDouble, 2);

console.log(doubleIterator(3)); // => 12