公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:52010
  • 待审:67
  • 小程序:12
  • 文章:1106242
  • 会员:784

给定一个函数 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 一个函数 调用
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 52010

    网站

  • 12

    小程序

  • 1106242

    文章

  • 784

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定