登录
首页 >  文章 >  前端

Leetcode #允许一个函数调用

来源:dev.to

时间:2024-11-19 14:40:51 309浏览 收藏

小伙伴们有没有觉得学习文章很有意思?有意思就对了!今天就给大家带来《Leetcode #允许一个函数调用》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

Leetcode #允许一个函数调用

给定一个函数 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 <= 通话长度 <= 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 #允许一个函数调用》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>