Home > OS >  Correct function currying
Correct function currying

Time:09-10

I have such a function

function addNum() {
  let sum = 0
  sum  = 1

  function getNum() {
    return sum
  }

  addNum.getInnerNum = getNum

  return function() {
    return addNum
  }
}

addNum().getInnerNum() // 1
addNum()()().getInnerNum() // 3
addNum()()()()().getInnerNum() // 5

I need it to be called N times and calculate number of calls. So final result should be something like that

addNum().getInnerNum() // 1
addNum()()().getInnerNum() // 3
addNum()()()()().getInnerNum() // 5

Right now my code doesn't work and I have an error:

Uncaught TypeError: addNum(...).getInnerNum is not a function)

The function doesn't calculate its calls.

CodePudding user response:

Close the counter in addNum and return an inner function that increments the counter and returns itself:

function addNum() {
    let n = 1

    function inner() {
        n  = 1
        return inner
    }

    inner.getNum = () => n

    return inner

}


console.log(addNum()()()()()()()().getNum())

CodePudding user response:

The let has been initialized inside the function, so every time it will receive the value 1;

you can initialize the let outside the function and use the function to update the value

let sum = 0;

function addNum(valueToAdd) {
  sum  = valueToAdd

  function getNum() {
    return sum;
  }

  return {getNum};
}


console.log(addNum(1).getNum()) // 1
console.log(addNum(3).getNum()) // 3
console.log(addNum(5).getNum()) // 5

Another way is passing a number to the function with how many times this function should run, idk if it fits what you want

function addNum(valueToAdd) {
  let sum = 0;
  sum  = valueToAdd

  function getNum() {
    return sum;
  }

  return {getNum};
}


console.log(addNum(1).getNum()) // 1
console.log(addNum(3).getNum()) // 4
console.log(addNum(5).getNum()) // 9

With this idea of use props you can play and use any variable to control the iteration as variable to change, number of times to parse, value to add, etc.

  • Related