数组合并去重
function dealArr(arr1: any[], arr2: any[]): any[] {
return Array.from(new Set([...arr1.flat(), ...arr2.flat()]));
}
const arr1 = ["a", 1, 2, 3, ["b", "c", 5, 6]];
const arr2 = [1, 2, 4, "d", ["e", "f", "5", 6, 7]];
console.log("dealArr(arr1, arr2 ); :>> ", dealArr(arr1, arr2));
一维数组转树状数组
const items = [
{ id: 1, name: "Item 1", parentId: null },
{ id: 2, name: "Item 1.1", parentId: 1 },
{ id: 3, name: "Item 1.2", parentId: 1 },
{ id: 4, name: "Item 2", parentId: null },
{ id: 5, name: "Item 1.1.1", parentId: 2 },
];
function arrayToTree(items) {
// 初始化结果数组和映射对象
const tree = [];
const map = {};
// 遍历 items 数组,为每个 item 创建一个 children 数组(如果尚未存在)
// 并将 item 添加到其 parentId 对应的 children 数组中(如果 parentId 存在)
// 如果没有 parentId,则认为是根节点,添加到结果数组中
items.forEach((item) => {
map[item.id] = { ...item, children: [] };
if (item.parentId) {
map[item.parentId].children = map[item.parentId].children || [];
map[item.parentId].children.push(map[item.id]);
} else {
tree.push(map[item.id]);
}
});
return tree;
}
// 使用示例与之前相同
const tree = arrayToTree(items);
console.log(JSON.stringify(tree, null, 2));
防抖/节流
function debounce(fn: Function, delay: number) {
let timer: any = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
};
}
function throttle(fn: Function, delay: number) {
let timer: any = null;
return function () {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
};
}
深拷贝
function deepClone<T extends Array<T> | any>(obj: T): T {
if (typeof obj !== "object" || obj === null) return obj;
const result: T = obj instanceof Array ? ([] as T) : ({} as T);
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
快速排序
function quickSort(arr: number[], startIndex = 0): number[] {
if (arr.length <= 1) return arr;
const right: number[] = [],
left: number[] = [],
startNum = arr.splice(startIndex, 1)[0];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < startNum) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), startNum, ...quickSort(right)];
}
链式调用(实现加减乘除计算器)
class Calculator {
constructor() {
this.value = 0;
}
add(num) {
this.value += num;
return this; // 返回自身,以实现链式调用
}
subtract(num) {
this.value -= num;
return this;
}
multiply(num) {
this.value *= num;
return this;
}
divide(num) {
this.value /= num;
return this;
}
getValue() {
return this.value;
}
}
const calculator = new Calculator();
const result = calculator
.add(5)
.subtract(2)
.multiply(3)
.divide(4)
.getValue();
console.log(result); // 输出 2.25
实现一个类似map的方法
// fn是callback函数,thisValue是参数
Array.prototype.mymap = function ( fn , thisValue ){
let temp = []
// this就是调用map()方法的数组
let arr = this
// 循环数组项
for(let i = 0; i < arr.length; i++){
// 对每一项使用传入的fn()方法
let result = fn.call(thisValue ,arr[i] , i, arr)
// 将每次fn()方法返回的值存储到新数组中,如果fn()没有返回值,result为undefined
temp.push(result)
}
// 返回一个新数组
return temp
}
let aa = [1,4,2,33]
let bb = aa.mymap(function (item,key,arr){
return item*2
})
console.log(bb) // 输出 [ 2, 8, 4, 66 ]
动态规划(斐波那契)
小偷计划偷窃沿街的房屋,两间相邻的房屋不能在同一晚上闯入。给定一个代表每个房屋存放金额的非负整数数组,计算不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
// 可以用递归,反过来也可以用数组,那么最后简化如下
function rob(nums: number[]): number {
const len = nums.length;
const dp = [];
let i = 0;
let j = nums[0];
for(let k=2;k<=len;k++){
const flag = Math.max(i+nums[k-1],j);
i = j;
j = flag;
}
return j;
};
实现柯里化
目的是让一个函数处理的问题尽可能单一
function foo(m, n, x, y) {
return m + n + x + y;
}
foo(m + n + x + y)
// 柯里化过程
function bar(m) {
return function(n) {
return function (x) {
return function (y) {
return m + n + x + y;
}
}
}
}
// 调用
bar(10)(20)(30)(40)