1.函数科里化
写一个函数 实现:
sum(1,2,3)(4)(); // 10
sum(1)(2)(3)(); // 6
sum(1)(2)(3,4, 5)(); // 15
function currySum(...args) {
let sum = args.reduce((pre, cur) => {
return pre + cur;
}, 0);
const getSum = function(...args2) {
if(args2.length > 0) {
sum += args2.reduce((pre, cur) => {
return pre + cur;
}, 0);
return getSum;
} else {
return sum;
}
}
return getSum;
}
2. 根据pId把对象数组转为树形结构
const arr = [
{ id: 1, name: "a", parentId: null },
{ id: 2, name: "b", parentId: 1 },
{ id: 3, name: "c", parentId: 2 },
{ id: 4, name: "d", parentId: 2 },
{ id: 5, name: "e", parentId: null },
{ id: 6, name: "f", parentId: 4 },
{ id: 7, name: "g", parentId: 5 },
{ id: 8, name: "h", parentId: 1 },
]
// 输出:
[
{
"id": 1,
"name": "a",
"parentId": null,
"children": [
{
"id": 2,
"name": "b",
"parentId": 1,
"children": [
{
"id": 3,
"name": "c",
"parentId": 2,
"children": []
},
{
"id": 4,
"name": "d",
"parentId": 2,
"children": [
{
"id": 6,
"name": "f",
"parentId": 4,
"children": []
}
]
}
]
},
{
"id": 8,
"name": "h",
"parentId": 1,
"children": []
}
]
},
{
"id": 5,
"name": "e",
"parentId": null,
"children": [
{
"id": 7,
"name": "g",
"parentId": 5,
"children": []
}
]
}
]
使用递归:
function convertTreeArray(target) {
const convertFn = (target, pId, result) => {
target.forEach(item => {
if(item.parentId === pId) {
result.push(item)
}
})
result.forEach(p => {
p.children = [];
convertFn(target, p.id, p.children);
})
return result;
};
return convertFn(target, null, []);
}
3. 数组扁平化
const arr = [[1,2], [3, 4], [5, [6, [7]]]];
// 输出 [1,2,3,4,5,6,7]
function flattenArray(target) {
return target.reduce((pre, cur) => {
return Array.isArray(cur)
? [...pre, ...flattenArray(cur)]
: pre.concat(cur);
}, []);
}
或使用
数组的flat()方法 在不知道数组是多少维度的情况下做到扁平化,只要将 Infinity 的参数传入
function flattenArray(arr) {
return arr.flat(Infinity);
}
4. 数组去重
const arr = [1,2,3,1,2,3, 4, 5,4, 6,6,4,1];
// [1,2,3,4,5,6]
使用Set
function uniqueItemArr(arr) {
return [...new Set(arr)]
}
使用reduce
function uniqueArr(arr) {
return arr.reduce((pre, cur) => {
return pre.includes(cur) ? pre : pre.concat(cur);
}, [])
}
使用filter
function disticArr(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index)
}
5. 手写防抖和节流
防抖debounce
function debounceFn(fn, delay = 1000) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.call(this, ...args)
}, delay)
};
}
function fn(name) {
console.log("我是该被防抖的方法, 三秒后打印!", name);
}
debounceFn(fn, 3000)();
// 这样返回一个函数调用 可以把参数传进fn里, 如:
// const name = "张三";
// debounceFn(fn, 3000)(name)
节流 throttle
function throttle(fn, delay) {
let lastTimeTemp = 0;
return function(...args) {
const currentTime = Date.now();
// 第一次 当前的时间戳 - 0 一定是大于delay的,所以刚开始fn就会执行,后面只有隔了delay后fn才会执行
if(currentTime - lastTimeTemp >= delay) {
fn.call(this, ...args)
lastTimeTemp = currentTime;
}
}
}