内容:使用闭包完成如下要求


内容:使用闭包完成如下要求


参考GPT和自己的思路:以下是实现该功能的代码:
function makeHistory(maxActions) {
const actions = [];
let index = -1;
return function(action) {
if (action === "undo") {
if (index >= 0) {
const lastAction = actions[index];
index--;
return `${lastAction} undone`;
} else {
return "nothing to do";
}
} else {
if (actions.length >= maxActions) {
actions.shift();
}
actions.push(action);
index = actions.length - 1;
return `${action} done`;
}
};
}
首先,我们定义一个 makeHistory 函数,该函数返回一个闭包函数。闭包函数内部维护了一个数组 actions,记录所有执行过的操作,以及一个变量 index,表示当前可以执行的操作的索引。
在闭包函数内部,我们首先判断传入的操作是否为 "undo"。如果是 "undo",则需要检查是否还有操作可以撤销。如果 index 大于等于 0,则说明还有可以撤销的操作,将最近的一个操作取出来,index 减 1,然后返回撤销的信息。否则,说明没有可以撤销的操作了,直接返回提示信息。
如果传入的操作不是 "undo",则需要将该操作加入到 actions 数组中。如果 actions 数组长度已经达到了 maxActions,则需要将最早的一个操作从数组中删除,保证数组长度不会超过 maxActions。然后将当前操作添加到数组中,更新 index 的值,最后返回操作完成的信息。
使用示例:
// 示例1
const myActions = makeHistory(2);
console.log(myActions("jump")); // 'jump done'
console.log(myActions("undo")); // 'jump undone'
console.log(myActions("walk")); // 'walk done'
console.log(myActions("code")); // 'code done'
console.log(myActions("pose")); // 'pose done'
console.log(myActions("undo")); // 'pose undone'
console.log(myActions("undo")); // 'code undone'
console.log(myActions("undo")); // 'nothing to do'
// 示例2
const myActions = makeHistory(1);
console.log(myActions("jump")); // 'jump done'
console.log(myActions("undo")); // 'jump undone'
console.log(myActions("undo")); // 'nothing to do'