function add(...args) { //这是需要处理的函数,任意
return args.reduce((pre, cur) => {
return pre + cur;
});
}
const memorize = (fn) => { //处理函数
let map = new Map();
return function (...args) {
let keys = Array.from(map.keys());
console.log(keys);
let is = false;
for (let item of keys) {
is = args.every((val, index) =>{
return val === item[index]
});
if (is) {
console.log('使用缓存')
return map.get(item)
}
}
console.log('重新计算')
let r = fn(...args);
map.set(args, r);
return r;
}
}
const f = memorize(add); //调用
console.log(f(1, 2));
console.log(f(3, 4));
console.log(f(3, 4));
console.log(f(1, 2));
console.log(f(1, 2, 3));
console.log(f(1, 2, 4));
console.log(f(5, 6));
console.log(f(1, 2, 3));
//实现一个函数只能通过new调用,通过普通方式调用时抛出错误,并且每次返回的对象里的id属性要递增,不能使用全局变量
const dog = (function (){
let id = 0;
return function(){
if(!new.target){
throw new Error('new only');
}
this.id = ++ id;
}
})();
console.log(new dog());
console.log(new dog());
console.log(new dog());
let a = 123123234.123;
let b = "123,123,234.123";
function change(str){
let arr = str + '';
arr = arr.split('.');
let re = arr[0].split('').reverse();
let stack = [];
let count = 0;
for(let i=0;i<re.length;i++){
stack.push(re[i]);
count++;
if(count == 3 && i<re.length-1){
stack.push(',');
count = 0;
}
}
return stack.reverse().join('') + '.' + arr[1];
}
console.log(change(a))
function f(arr){
if(arr.length<1){
return arr;
}
let mid = arr[Math.floor(arr.length/2)];
let left = [],righ = [];
arr.forEach(item => (item<mid?left:right).push(item));
return [...f(left),mid,...f(right)];
}
let rotate = (matrix) =>{
for(let i = 0; i < matrix.length; i++){
for (let j = i; j < matrix[i].length; j++){
[matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]]
}
}
matrix.forEach(row=> row.reverse())
};
[
[1,2,3],
[4,5,6],
[7,8,9]
],
[
[1,4,7],
[2,5,8],
[3,6,9]
]
//原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
console