手写代码

57 阅读2分钟

call

Function.prototype.myCall = function (context, ...args) {
    context = context || globalThis
    context.fn = this
    const result = context.fn(...args)
    delete context.fn
    return result
}

apply

Function.prototype.myApply = function (context, args) {
    context = context || globalThis;
    context.fn = this;
    const result = context.fn(...(args || []));
    delete context.fn;
    return result;
};

bind

Function.prototype.myBind = function (context, ...args) {
    const fn = this;
    return function (...args2) {
        return fn.apply(context, [...args, ...args2]);
    };
};

函数柯里化

function curry(fn) {
    return function curried(...args) {
        // 检查是否收集到足够的参数
        if (args.length >= fn.length) {
            return fn(...args); // 调用原函数
        } else {
            return function (...args2) {
                return curried(...args, ...args2); // 继续收集参数
            };
        }
    };
}

快速排序

function quickSort(arr) {
    // 如果数组长度小于或等于 1,直接返回数组
    if (arr.length <= 1) {
        return arr;
    }

    // 选择基准值(这里选择数组的最后一个元素)
    const pivot = arr[arr.length - 1];
    const left = [];
    const right = [];

    // 遍历数组,分割成左右两个子数组
    for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] < pivot) {
            left.push(arr[i]); // 小于基准值的元素放入左边数组
        } else {
            right.push(arr[i]); // 大于或等于基准值的元素放入右边数组
        }
    }

    // 递归排序左右子数组,并将结果合并
    return [...quickSort(left), pivot, ...quickSort(right)];
}

浅拷贝

function shallowCopy(obj) {
    if (typeof obj !== 'object' || typeof obj !== null) {
        return obj
    }
    return Object.assign({}, obj)
}

深拷贝

function deepCopy(obj) {
    let deepCloneObj = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
        for (let key in obj) {
            console.log(key)
            if (obj.hasOwnProperty(key)) {
                deepCloneObj[key] = deepCopy(obj[key])
            }
        }
    }
    return deepCloneObj
}

解析url参数

function parseUrl(url) {
    const result = {}
    const params = url.split("?")[1]
    const paramsArr = params.split("&")
    paramsArr.forEach(item => {
        const key = item.split("=")[0]

        const value = item.split("=")[1]
        result[key] = value
    });
    console.log(result)
}

递归

//递归 性能差
function factorial1(n) {
    if (n === 1) return 1
    return n * factorial(n - 1)
}

// 尾递归 性能更好
function factorial(n, total) {
    if (n === 1) return total
    return factorial(n - 1, n * total)
}

防抖、节流

// 防抖:在 时间N 内执行一次,如果在时间N内又被触发,则重新计时
function myDebounce(fn, wait) {
    let timer;
    return function () {
        const context = this
        const args = arguments;
        if (timer) {
            clearTimeout(timer)
            timer = null
        }

        timer = setTimeout(() => {
            fn.apply(context, args)
        }, wait)
    }
}

// 节流:在时间N内执行一次,即使重复触发事件
function myThrottle(fn, delay) {
    let curTime = Date.now();
    return function () {
        const context = this;
        const args = arguments;
        nowTime = Date.now()
        if (nowTime - curTime >= delay) {
            curTime = Date.now();
            return fn.apply(context, args)
        }
    }
}

将JS对象转化为树形结构

 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 2.1', parentId: 4 }
        ];
        function buildTree(items, parentId = null) {
            let tree = [];
            for (let i in items) {
                console.log('i--->', i)
                if (items[i].parentId == parentId) {
                    const children = buildTree(items, items[i].id);
                    if (children.length) {
                        items[i].children = children;
                    }
                    tree.push(items[i]);
                }
            }
            return tree;
        }
        // 使用上面的函数构建树  
        const tree = buildTree(items);
        console.log(tree);
        // [
        //     {
        //         id: 1,
        //         name: 'Item 1',
        //         parentId: null,
        //         children: [
        //             { id: 2, name: 'Item 1.1', parentId: 1 },
        //             { id: 3, name: 'Item 1.2', parentId: 1 }
        //         ]
        //     },
        //     {
        //         id: 4,
        //         name: 'Item 2',
        //         parentId: null,
        //         children: [
        //             { id: 5, name: 'Item 2.1', parentId: 4 }
        //         ]
        //     },
        // ]