数组算法排序实现

重写 Array.filter()

复制代码
javascript复制代码Array.prototype.myFilter = function(callback, thisArg) {
    const result = [];
    for (let i = 0; i < this.length; i++) {
        if (callback.call(thisArg, this[i], i, this)) {
            result.push(this[i]);
        }
    }
    return result;
};
​
// 测试
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.myFilter(num => num > 2);
console.log(filteredArr); // [3, 4, 5]

算法1:合并两个已排序的数组

复制代码
javascript复制代码function mergeSortedArrays(arr1, arr2) {
    let i = 0, j = 0;
    const result = [];
​
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) {
            result.push(arr1[i]);
            i++;
        } else {
            result.push(arr2[j]);
            j++;
        }
    }
​
    // 处理剩余元素
    return result.concat(arr1.slice(i)).concat(arr2.slice(j));
}
​
// 测试
const arr1 = [1, 3, 5, 7];
const arr2 = [2, 4, 6, 8];
console.log(mergeSortedArrays(arr1, arr2)); // [1, 2, 3, 4, 5, 6, 7, 8]

算法2:数值序列化(每隔三位一个逗号)

复制代码
javascript复制代码function numberWithCommas(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
​
// 测试
const num = 1234567890;
console.log(numberWithCommas(num)); // 1,234,567,890

算法3:格式化 query 字符串

复制代码
javascript复制代码function parseQueryString(queryString) {
    const queryObj = {};
    const pairs = queryString.replace(/^\?/, '').split('&');
​
    for (const pair of pairs) {
        const [key, value] = pair.split('=');
        if (queryObj[key]) {
            if (Array.isArray(queryObj[key])) {
                queryObj[key].push(decodeURIComponent(value));
            } else {
                queryObj[key] = [queryObj[key], decodeURIComponent(value)];
            }
        } else {
            queryObj[key] = decodeURIComponent(value);
        }
    }
​
    return queryObj;
}
​
// 测试
const queryString = '?a=1&a=2&b=3';
console.log(parseQueryString(queryString)); // { a: ['1', '2'], b: '3' }
相关推荐
董员外1 分钟前
RAG 系统进化论(二):Naive RAG,检索增强生成的最小闭环
前端·人工智能·后端
脾气有点小暴5 分钟前
ECharts 伪 3D 柱状图完整注释 + 实现原理说明
前端·3d·信息可视化·vue·echarts
掘金一周19 分钟前
看看大家每月的成本有多少 | 沸点周刊 7.30
前端·人工智能·后端
ji_shuke28 分钟前
从零深入:基于 Playwright + Pytest + Allure 的企业级 Web 端到端自动化测试框架实战
前端·自动化测试·docker·jenkins·pytest·allure·playwright
陆枫Larry1 小时前
用 CSS Mask + background-color 给图标「换色」
前端
幼儿园技术家2 小时前
原来不用发版也可以做到版本更新
前端·js or ts
亦暖筑序2 小时前
AgentScope-Java 入门:完善 Vue 前端、发布 GitHub,并规划下一步
java·前端·vue.js
北斗落凡尘2 小时前
Vue面试题
前端
程序员黑豆2 小时前
鸿蒙应用开发之父子组件传参:@Param、@Event、@Once 装饰器详解与实战
前端·harmonyos
ClouGence2 小时前
一个人录好的测试用例,团队怎么一起用?
前端·测试