组织信息层级转换
说明:把扁平的数据根据层级展示成树结构
原数据示例:
[
{
id: 1,
name: '部门A',
parentId: 0
},
{
id: 2,
name: '部门B',
parentId: 0
},
{
id: 3,
name: '部门C',
parentId: 1
},
{
id: 4,
name: '部门D',
parentId: 1
},
{
id: 5,
name: '部门E',
parentId: 2
},
{
id: 6,
name: '部门F',
parentId: 3
},
{
id: 7,
name: '部门G',
parentId: 2
},
{
id: 8,
name: '部门H',
parentId: 4
}
];
转换后数据示例:
[
{
id: 1,
name: '部门A',
parentId: 0,
children: [
{
id: 3,
name: '部门C',
parentId: 1,
children: [{ id: 6, name: '部门F', parentId: 3, children: [] }]
},
{
id: 4,
name: '部门D',
parentId: 1,
children: [{ id: 8, name: '部门H', parentId: 4, children: [] }]
}
]
},
{
id: 2,
name: '部门B',
parentId: 0,
children: [
{ id: 5, name: '部门E', parentId: 2, children: [] },
{ id: 7, name: '部门G', parentId: 2, children: [] }
]
}
];
思路:通过map映射关系完成收据的整合
const convert = list => {
// 生成一个根据数据中每项id的数组,同时都赋值children,也更改原数组数据
let obj = list.reduce((map, node) => {
map[node.id] = node;
node.children = [];
return map;
}, {});
// 遍历数组数据把对应的数据放在对应放到对应父级的children中,并过滤出不含有父元素的数据
return list.filter(item => {
obj[item.parentId] && obj[item.parentId].children.push(item);
return !item.parentId;
});
};
函数柯里化
说明:sum(1)(2,3)(4,5,6)函数连续调用累加参数
示例:sum(1)(2,3)(4,5,6) // 21
const sum = function() {
const a = [...arguments].reduce((total, item) => total + item);
const tem = function() {
const b = [...arguments].reduce((total, item) => total + item);
return sum(a + b);
};
// 重新toString方法,把本次调用函数的的总和值返回
tem.toString = () => a;
return tem;
};
防抖与节流
防抖
概念:当用户在防抖时间内不停点击只会执行最后一次;
场景:用户输入查询功能,输入的过程不进行请求,等到用户停止输入后查询返回结果;
代码示例:
const debounce = (time, fn)=>{
let timer = null;
return ()=>{
clearTimeout(timer);
timer = setTimeout(() => {
fn();
}, time);
};
}
const handle = function(){
console.log(1111111);
}
document.getElementById('button1').onclick = debounce(3000, handle);
节流
概念:当用户在节流时间范围内只会执行用户第一次发起的请求;
场景:点击提交按钮时候,无论用户连续点击几次在时间范围内都会执行第一次;
代码示例:
const throttle = (time, fn)=>{
let timer;
return ()=>{
if(timer) return;
timer = setTimeout(() => {
fn();
timer = null;
}, time);
}
}
const handle = function(){
console.log(1111111);
}
document.getElementById('button1').onclick = throttle(3000, handle);