>  기사  >  웹 프론트엔드  >  Leetcode #하나의 함수 호출 허용

Leetcode #하나의 함수 호출 허용

王林
王林원래의
2024-08-24 11:14:06295검색

Leetcode #Allow One Function Call

fn 함수가 주어지면 fn이 최대 한 번 호출된다는 점을 제외하고 원래 함수와 동일한 새 함수를 반환합니다.

반환된 함수를 처음 호출하면 fn과 동일한 결과를 반환해야 합니다.
이후에 호출될 때마다 정의되지 않은 값을 반환해야 합니다.

예 1:

입력:

fn = (a,b,c) => (a + b + c), 호출 = [[1,2,3],[2,3,6]]

출력:


**Explanation:**


const 한 번Fn = 한 번(fn);
한 번Fn(1, 2, 3); // 6
한 번Fn(2, 3, 6); // 정의되지 않음, fn이 호출되지 않음


**Example 2:**

**Input:**

 ```fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]```


**Output:**

 ```[{"calls":1,"value":140}]```


**Explanation:**


const 한 번Fn = 한 번(fn);
한 번Fn(5, 7, 4); // 140
한 번Fn(2, 3, 6); // 정의되지 않음, fn이 호출되지 않음
한 번Fn(4, 6, 8); // 정의되지 않음, fn이 호출되지 않음



**Constraints:**

`calls` is a valid JSON array



1 <= 통화.길이 <= 10
1 <= 통화[i].length <= 100
2 <= JSON.stringify(calls).length <= 1000



*Solution*

In this case, we are required to create a higher-order function(a function that returns another function) [Read more about high-order functions here](https://www.freecodecamp.org/news/higher-order-functions-explained/#:~:text=JavaScript%20offers%20a%20powerful%20feature,even%20return%20functions%20as%20results.)

We should make sure that the original function `fn` is only called once regardless of how many times the second function is called.

If the function fn has been not called, we should call the function `fn` with the provided arguments `args`. Else, we should return `undefined`


_Code solution_



``` sh
/**
 * @param {Function} fn
 * @return {Function}
 */
var once = function (fn) {
    // if function === called return undefined, 
    // else call fn with provide arguments
    let executed = false;
    let result;

    return function (...args) {
        if (!executed) {
            executed = true;
            result = fn(...args);
            return result;
        } else {
            return undefined;
        }
    }
};

/**
 * 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
 */






          

            
        

위 내용은 Leetcode #하나의 함수 호출 허용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.