문제

Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.

The first time the returned function is called, it should return the same result as fn.
Every subsequent time it is called, it should return undefined.

 

예제

처음 호출 시 fn에 argument 값들이 올바르게 들어가고 값을 반환한다.

하지만 두번째 호출부터는 fn 함수를 호출하지 않고 undefined를 반환한다.

마찬가지로 처음 호출 시 fn 함수에 주어진 argument 값들이 올바르게 들어간 뒤 값을 반환하지만,

이후에는 fn 함수를 호출하지 않고 undefined를 반환한다.

 

 


코드

/**
 * @param {Function} fn
 * @return {Function}
 */
var once = function(fn) {
    let isUsed = false;
    return function(...args){
        if (!isUsed) {
            isUsed = true;
            return fn(...args);
        }
    }
};

/**
 * let fn = (a,b,c) => (a + b + c)
 * let onceFn = once(fn)
 *
 * onceFn(1,2,3); // 6
 * onceFn(2,3,6); // returns undefined without calling fn
 */

 

isUsed라는 변수를 기본값 false로 초기화한 뒤, 함수가 실행되면 true로 변환한다.

함수는 isUsed가 false일 때, 즉 처음 호출 시에만 fn 함수를 실행시키고, 이후부터는 isUsed가 true이기 때문에 if 문이 실행되지 않고 undefined를 반환한다.

+ Recent posts