# 函数转换
# 复合函数
请你编写一个函数,它接收一个函数数组 [f1, f2, f3,…, fn] ,并返回一个新的函数 fn ,它是函数数组的 复合函数 。
[f(x), g(x), h(x)] 的 复合函数 为 fn(x) = f(g(h(x))) 。
一个空函数列表的 复合函数 是 恒等函数 f(x) = x 。
你可以假设数组中的每个函数接受一个整型参数作为输入,并返回一个整型作为输出。
# 示例 1:
输入:functions = [x => x + 1, x => x * x, x => 2 * x], x = 4
输出:65
解释:
从右向左计算......
Starting with x = 4.
2 * (4) = 8
(8) * (8) = 64
(64) + 1 = 65
# 示例 2:
输出:functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1
输入:1000
解释:
从右向左计算......
10 * (1) = 10
10 * (10) = 100
10 * (100) = 1000
# 示例 3:
输入:functions = [], x = 42
输出:42
解释:
空函数列表的复合函数就是恒等函数
# 题解
# 方法一
使用for循环正常写法
const compose = (funcArr) => {
return (x) => {
let init = x;
for (let i = funcArr.length - 1; i >= 0; i--) {
init = funcArr[i](init);
}
return init;
};
};
const fun = compose([(x) => x + 1, (x) => x * x, (x) => 2 * x]);
const fun1 = compose([(x) => 10 * x, (x) => 10 * x, (x) => 10 * x]);
const fun2 = compose([]);
console.log("结果", fun(4));
console.log("结果", fun1(1));
console.log("结果", fun2(42));
# 方法 2:使用 Array.reduceRight() 的函数组合
在第一种方法中,我们使用迭代的方式从右到左应用函数。不过,我们可以利用 Array.reduceRight() 方法来实现相同的结果。reduceRight() 方法将一个函数应用于累加器和数组中的每个元素(从右到左),以将它们还原为单个值。在这种情况下,我们的累加器将是输入值 x,函数将是数组中函数的组合。
使用 reduceRight() 简化了代码,并提供了更函数式编程风格的解决方案。关键是理解 Array.reduceRight() 方法的工作原理以及如何将其应用于此问题。
var compose = function (functions) {
return x => functions.reduceRight((acc, f) => f(acc), x);
};
# 返回传递的参数的长度
请你编写一个函数 argumentsLength,返回传递给该函数的参数数量。
# 示例 1:
输入:args = [5]
输出:1
解释:
argumentsLength(5); // 1
只传递了一个值给函数,因此它应返回 1。
# 示例 2:
输入:args = [{}, null, "3"]
输出:3
解释:
argumentsLength({}, null, "3"); // 3
传递了三个值给函数,因此它应返回 3。
# 题解
# 方法 1: 使用参数对象
为了解决这个问题,我们可以利用 JavaScript 提供的参数对象,它是一个类似数组的对象,包含传递给函数的所有参数。我们可以简单地检索参数对象的长度并返回它。 更具体地说,JavaScript 中的参数是作为类似数组的对象传递的。因此,你可以在参数上使用与数组相同类型的许多函数,包括使用 arguments.length。
注意 1: 参数对象在函数内部自动可用,并保存传递给函数的参数。 注意 2: 使用 arguments.length 直接访问长度,而不创建中间数组( args)可能在某些情况下有益。
var argumentsLength = function (...args) {
return arguments.length;
};
# 方法 2: 使用剩余参数
我们可以使用剩余参数语法(...args)将所有参数收集到一个名为 args 的数组中。args.length 表达式用于访问 args 数组的长度属性,该属性表示传递给函数的参数数量。
var argumentsLength = function (...args) {
return args.length
};
# 只允许一次函数调用
给定一个函数 fn ,它返回一个新的函数,返回的函数与原始函数完全相同,只不过它确保 fn 最多被调用一次。
第一次调用返回的函数时,它应该返回与 fn 相同的结果。
第一次后的每次调用,它应该返回 undefined 。
# 示例 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 没有被调用
# 题解
# 方法一 利用剩余参数传入参数
const onceFun = (fun) => {
let num = 0;
return (...args) => {
if (num > 0) return;
num++;
return fun(...args);
};
};
const fn = onceFun((a, b, c) => a + b + c);
console.log("结果", fn(1, 2, 3));
console.log("结果", fn(1, 2, 3));
console.log("结果", fn(1, 2, 3));
注意
- 如果从函数中不返回任何值,它将隐式返回undefined
# 方法二 利用apply传入参数
var once = function (fn) {
let hasBeenCalled = false;
return function (...args) {
if (!hasBeenCalled) {
hasBeenCalled = true;
return fn.apply(this, args);
}
}
};
注意
# apply和call函数方法
- 函数原型上的
apply和call方法都可以更改this指向,实现继承 - 相同点:两个方法的第一个参数都是传入this指向,第二个参数都为传入函数的数据
- 不同点:第二个参数,
apply传入数组,在apply中被解析为单个数据传入,call方法从第一个参数开始都是参数
//数组最大项
let maxNum;
let arr = [1, 2, 3];
let arr2 = [7, 8, 9];
arr2.push.apply(arr, arr2);
console.log("数组", arr);//[1,2,3,7,8,9]
console.log("apply", Math.max.apply(null, arr));// 9
console.log("call", Math.max.call(null, ...arr));//9
# 利用apply实现继承
function creatName(name) {
this.name = name;
}
function creatAge(name, age) {
creatName.apply(this, [name]);
this.age = age;
}
function createSex(name, age, sex) {
creatAge.apply(this, [name, age]);
this.sex = sex;
}
console.log("结果", new creatAge("李四", 18));//{name:'张三',age:18}
console.log("结果", new createSex("张三", 18, "男"));//{name:'张三',age:18,sex:'男'}
# 利用call实现继承
function creatName(name) {
this.name = name;
}
function creatAge(name, age) {
creatName.call(this, name);
this.age = age;
}
function createSex(name, age, sex) {
creatAge.call(this, name, age);
this.sex = sex;
}
console.log("结果", new creatAge("李四", 18));//{name:'张三',age:18}
console.log("结果", new createSex("张三", 18, "男"));//{name:'张三',age:18,sex:'男'}
# 记忆函数
请你编写一个函数,它接收另一个函数作为输入,并返回该函数的 记忆化 后的结果。
记忆函数 是一个对于相同的输入永远不会被调用两次的函数。相反,它将返回一个缓存值。
你可以假设有 3 个可能的输入函数:sum 、fib 和 factorial 。
- sum 接收两个整型参数 a 和 b ,并返回 a + b 。
- fib 接收一个整型参数 n ,如果 n <= 1 则返回 1,否则返回 fib (n - 1) + fib (n - 2)。
- factorial 接收一个整型参数 n ,如果 n <= 1 则返回 1 ,否则返回 factorial(n - 1) * n 。
# 示例 1:
输入:
fnName = "sum"
actions = ["call","call","getCallCount","call","getCallCount"]
values = [[2,2],[2,2],[],[1,2],[]]
输出:[4,4,1,3,2]
解释:
const sum = (a, b) => a + b;
const memoizedSum = memoize(sum);
memoizedSum (2, 2);// "call" - 返回 4。sum() 被调用,因为之前没有使用参数 (2, 2) 调用过。
memoizedSum (2, 2);// "call" - 返回 4。没有调用 sum(),因为前面有相同的输入。
// "getCallCount" - 总调用数: 1
memoizedSum(1、2);// "call" - 返回 3。sum() 被调用,因为之前没有使用参数 (1, 2) 调用过。
// "getCallCount" - 总调用数: 2
# 示例 2:
输入:
fnName = "factorial"
actions = ["call","call","call","getCallCount","call","getCallCount"]
values = [[2],[3],[2],[],[3],[]]
输出:[2,6,2,2,6,2]
解释:
const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));
const memoFactorial = memoize(factorial);
memoFactorial(2); // "call" - 返回 2。
memoFactorial(3); // "call" - 返回 6。
memoFactorial(2); // "call" - 返回 2。 没有调用 factorial(),因为前面有相同的输入。
// "getCallCount" - 总调用数:2
memoFactorial(3); // "call" - 返回 6。 没有调用 factorial(),因为前面有相同的输入。
// "getCallCount" - 总调用数:2
# 示例 3:
输入:
fnName = "fib"
actions = ["call","getCallCount"]
values = [[5],[]]
输出:[8,1]
解释:
fib(5) = 8 // "call"
// "getCallCount" - 总调用数:1
# 题解
# 方法一 将key转化为字符串
function memoize(fun) {
this.map = {};
this.current = 0;
this.memoizeFun = function (...args) {
const key = JSON.stringify(args);
if (key in this.map) return this.map[key];
this.current++;
const result = fun(...args);
this.map[key] = result;
return result;
};
}
const fun1 = new memoize((a, b) => a + b);
console.log("调用次数", fun1.current); //0
console.log("结果", fun1.memoizeFun(2, 2)); //4
console.log("调用次数", fun1.current); //1
console.log("结果", fun1.memoizeFun(2, 2)); //4
console.log("调用次数", fun1.current); //1
console.log("结果", fun1.memoizeFun(2, 3)); //5
console.log("调用次数", fun1.current); //2
# 利用逻辑空值运算符运算符 ??
const memoize = (fn, cache = {}) => (...args) => cache[args.join()] ?? (cache[args.join()] = fn(...args));
const fn = memoize((a, b) => a + b);
console.log("结果", fn(2, 2)); //4
console.log("结果", fn(2, 2)); //4
console.log("结果", fn(2, 3)); //5
console.log([2, 1, 5].join()); //2,1,5
注意
数组的join方法用于将数组的每一项都转换为字符串,该方法接受一个参数 用于指定分隔的符号