列表

详情


2666. 只允许一次函数调用

给定一个函数 fn ,它返回一个新的函数,返回的函数与原始函数完全相同,只不过它确保 fn 最多被调用一次。

 

示例 1:

输入:fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
输出:[{"calls":1,"value":6}]
解释:
const onceFn = once(fn);
onceFn(1, 2, 3); // 6
onceFn(2, 3, 6); // undefined, fn 没有被调用

示例 2:

输入:fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
输出:[{"calls":1,"value":140}]
解释:
const onceFn = once(fn);
onceFn(5, 7, 4); // 140
onceFn(2, 3, 6); // undefined, fn 没有被调用
onceFn(4, 6, 8); // undefined, fn 没有被调用

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * @param {Function} fn * @return {Function} */ var once = function(fn) { return function(...args){ } }; /** * 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 */

typescript 解法, 执行用时: 60 ms, 内存消耗: 42.4 MB, 提交时间: 2023-05-14 17:04:02

function once<T extends (...args: any[]) => any>(
  fn: T
): (...args: Parameters<T>) => ReturnType<T> | undefined {
  let used = false;
  return (...args) => used ? undefined : (used = true, fn(...args));
}

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

javascript 解法, 执行用时: 76 ms, 内存消耗: 40.9 MB, 提交时间: 2023-05-14 17:03:41

/**
 * @param {Function} fn
 * @return {Function}
 */
var once = function (fn) {
    let num = 0;
    return function (...args) {
        if (num > 0) return undefined;
        num++;
        return fn(...args)
    }
};

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

上一题