前言:锻炼自己的思想,规范自己的编程思路。
问题1:返回传递的参数的长度
请你编写一个函数 argumentsLength,返回传递给该函数的参数数量。
示例:(放代码里面)
输入:argsArr = [{}, null, "3"]
输出:3
解释:
argumentsLength({}, null, "3"); // 3
传递了三个值给函数,因此它应返回 3。
思路:
在 JavaScript 中,返回一个参数访问 args.length 属性来获取传递给该函数的参数数量。
基于上述思考,代码如下:
/**
* @return {number}
*/
var argumentsLength = function(...args) {
return args.length
};
执行结果如下图:
结论:这个函数非常简单,只需一行代码就能实现。它可以用来检查传递给函数的参数数量是否符合预期,或者在某些情况下根据参数数量执行不同的操作。
问题2:Execute Cancellable Function With Delay
Given a function fn, an array or arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.
After a delay of t, fn should be called with args passed as parameters unless cancelFn was called first. In that case, fn should never be called.
示例:(放代码里面)
Input: fn = (x) => x * 5, args = [2], t = 20, cancelTime = 50
Output: [{"time": 20, "returned": 10}]
Explanation:
const cancel = cancellable(fn, [2], 20); // fn(2) called at t=20ms
setTimeout(cancel, 50);
the cancelTime (50ms) is after the delay time (20ms), so fn(2) should be called at t=20ms. The value returned from fn is 10.
思路:
在这个函数中,我们首先使用 setTimeout 函数创建一个定时器,用来在给定的延迟时间 t 后调用指定的函数 fn。我们使用 apply 方法将 args 数组中的元素作为参数传递给 fn 函数。
接着,我们返回一个名为 cancelFn 的取消函数。当调用这个函数时,它会使用 clearTimeout 函数清除之前创建的定时器,从而阻止 fn 函数被调用。
基于上述思考,代码如下:
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function delay(fn, args, t) {
let timer = setTimeout(() => {
fn.apply(null, args);
}, t);
return function cancelFn() {
clearTimeout(timer);
};
}
执行结果如下图: