首頁 >web前端 >js教程 >Leetcode #允許一個函數調用

Leetcode #允許一個函數調用

王林
王林原創
2024-08-24 11:14:06347瀏覽

Leetcode #Allow One Function Call

給定一個函數 fn,傳回一個與原始函數相同的新函數,只不過它確保 fn 最多被呼叫一次。

第一次呼叫傳回的函數時,它應該會傳回與 fn 相同的結果。
隨後每次調用它時,它都應該返回未定義。

範例1:

輸入:

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

輸出:


**Explanation:**


const OnceFn = Once(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 OnceFn = Once(fn);
一次Fn(5,7,4); // 140
一次Fn(2,3,6); // 未定義,fn 未被呼叫
一次Fn(4,6,8); // 未定義,fn 未被呼叫



**Constraints:**

`calls` is a valid JSON array



1 1 2



*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