Algorithm 12 - [JS] A Chain adding function

luneah·2021년 12월 5일
0

Algorithm CodeKata

목록 보기
12/13
post-thumbnail

A Chain adding function

We want to create a function that will add numbers together when called in succession.

add(1)(2);
// returns 3

We also want to be able to continue to add numbers to our chain.

add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

and so on.

A single call should return the number passed in.

add(1); // 1

We should be able to store the returned values and reuse them.

var addTwo = add(2);
addTwo; // 2
addTwo + 5; // 7
addTwo(3); // 5
addTwo(3)(5); // 10

We can assume any number being passed in will be valid whole number.

📌 Needs ) 연속적으로 호출될 때 숫자를 더하는 함수를 만들어야 함, 체인에 계속해서 숫자를 추가할 수 있어야 함, 반환된 값을 저장하고 재사용할 수 있어야 함

📁 Sol )

function add(n){
  let fn = function (x) {
    return add (n + x);
  };
  fn.valueOf = function () {
    return n;
  };
  return fn;
}

💬 valueOf() 메소드는 호출된 객체의 값을 단순 반환해준다.

profile
하늘이의 개발 일기

0개의 댓글