ホームページ  >  記事  >  ウェブフロントエンド  >  Leetcode #1 つの関数呼び出しを許可する

Leetcode #1 つの関数呼び出しを許可する

王林
王林オリジナル
2024-08-24 11:14:06292ブラウズ

Leetcode #Allow One Function Call

関数 fn が指定された場合、fn が最大 1 回呼び出されることを保証する点を除いて、元の関数と同一の新しい関数を返します。

返された関数が初めて呼び出されたとき、fn と同じ結果が返される必要があります。
それ以降呼び出されるたびに、unknown が返されるはずです。

例 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 <= 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 #1 つの関数呼び出しを許可するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。