目录
一、JavaScript算法设计的现代范式
1.1 JavaScript算法的演进革命
1.2 JavaScript算法的独特优势
二、数组与对象算法
2.1 现代数组操作方法
2.2 迭代器与生成器算法
三、排序与搜索算法
3.1 现代排序技术
3.2 高效搜索算法
四、性能优化与内存管理
4.1 算法性能优化技巧
4.2 数据缓存与记忆化
五、实用算法与设计模式
5.1 函数式编程实用算法
5.2 实用数据处理算法

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。
一、JavaScript算法设计的现代范式
1.1 JavaScript算法的演进革命
JavaScript算法设计经历了三次重大变革:
- ES5时代:函数式编程萌芽(map、filter、reduce)
- ES6时代:箭头函数、解构、Promise、模块化
- ES2020+时代:可选链、空值合并、BigInt、动态导入

1.2 JavaScript算法的独特优势
// 1. 函数式编程的天然优势 const numbers = [1, 2, 3, 4, 5];
// 链式调用与组合 const result = numbers .filter(n => n % 2 === 0) // [2, 4] .map(n => n * 2) // [4, 8] .reduce((sum, n) => sum + n, 0); // 12
// 2. 高阶函数与柯里化 const multiply = a => b => a * b; const double = multiply(2); const triple = multiply(3);
console.log(double(5)); // 10 console.log(triple(5)); // 15
// 3. 异步编程的优雅处理 async function processData(urls) { const promises = urls.map(url => fetch(url).then(r => r.json())); const results = await Promise.allSettled(promises); return results .filter(r => r.status === 'fulfilled') .map(r => r.value); }

二、数组与对象算法
2.1 现代数组操作方法
// 1. ES6+新增数组方法 const array = [1, 2, 3, 4, 5];
// find/findIndex – 查找元素 const firstEven = array.find(n => n % 2 === 0); // 2 const firstEvenIndex = array.findIndex(n => n % 2 === 0); // 1
// some/every – 条件检查 const hasEven = array.some(n => n % 2 === 0); // true const allPositive = array.every(n => n > 0); // true
// flat/flatMap – 数组展平 const nested = [1, [2, [3, [4]]]]; const flattened = nested.flat(Infinity); // [1, 2, 3, 4]
const words = ["hello world", "good morning"]; const letters = words.flatMap(word => word.split(' ')); // ["hello", "world", "good", "morning"]
// 2. Array.from 与扩展运算符 // 类数组转数组 const nodeList = document.querySelectorAll('div'); const divArray = Array.from(nodeList);
// 创建范围数组 const range = (start, end) => Array.from({ length: end – start + 1 }, (_, i) => start + i);
console.log(range(1, 5)); // [1, 2, 3, 4, 5]
// 3. 使用Set和Map优化算法 // 数组去重 const duplicates = [1, 2, 2, 3, 4, 4, 5]; const unique = […new Set(duplicates)]; // [1, 2, 3, 4, 5]
// 频率统计 function frequency(arr) { return arr.reduce((map, item) => { map.set(item, (map.get(item) || 0) + 1); return map; }, new Map()); }
// 4. 对象操作的高级技巧 // 对象合并与克隆 const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 };
// 浅合并 const merged = { …obj1, …obj2 }; // { a: 1, b: 3, c: 4 }
// 深克隆(简单版) const deepClone = obj => JSON.parse(JSON.stringify(obj));
// 动态属性名(计算属性) const dynamicKey = 'score'; const student = { name: 'Alice', [dynamicKey]: 95, [`${dynamicKey}Level`]: 'A' };
// 可选链与空值合并 const user = { profile: { address: { city: 'New York' } } };
const city = user?.profile?.address?.city ?? 'Unknown'; const score = user?.scores?.[0] ?? 0;
2.2 迭代器与生成器算法
// 1. 自定义迭代器 class Range { constructor(start, end, step = 1) { this.start = start; this.end = end; this.step = step; } [Symbol.iterator]() { let current = this.start; const end = this.end; const step = this.step; return { next() { if (current <= end) { const value = current; current += step; return { value, done: false }; } return { done: true }; } }; } }
// 使用 for (const num of new Range(1, 5)) { console.log(num); // 1, 2, 3, 4, 5 }
// 2. 生成器函数 function* fibonacci(limit) { let [prev, curr] = [0, 1]; while (curr <= limit) { yield curr; [prev, curr] = [curr, prev + curr]; } }
// 惰性求值 const fibSequence = fibonacci(100); console.log([…fibSequence]); // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
// 3. 异步生成器 async function* asyncGenerator(urls) { for (const url of urls) { const response = await fetch(url); yield response.json(); } }
// 使用for await…of (async () => { const urls = ['/api/data1', '/api/data2']; for await (const data of asyncGenerator(urls)) { console.log(data); } })();

三、排序与搜索算法
3.1 现代排序技术
// 1. 内置排序的灵活使用 const items = [ { name: 'Apple', price: 3.5, rating: 4.2 }, { name: 'Banana', price: 2.0, rating: 4.5 }, { name: 'Cherry', price: 5.0, rating: 4.0 } ];
// 多字段排序 items.sort((a, b) => { // 先按价格升序,再按评分降序 if (a.price !== b.price) { return a.price – b.price; } return b.rating – a.rating; });
// 2. 稳定排序的实现 function stableSort(array, compare) { return array .map((item, index) => ({ item, index })) .sort((a, b) => { const result = compare(a.item, b.item); return result === 0 ? a.index – b.index : result; }) .map(({ item }) => item); }
// 3. 使用Intl.Collator进行本地化排序 const germanWords = ['ä', 'z', 'a']; germanWords.sort(new Intl.Collator('de').compare); // ['a', 'ä', 'z']
// 4. 快速排序(函数式版本) const quickSort = arr => { if (arr.length <= 1) return arr; const pivot = arr[0]; const left = arr.slice(1).filter(x => x <= pivot); const right = arr.slice(1).filter(x => x > pivot); return […quickSort(left), pivot, …quickSort(right)]; };
3.2 高效搜索算法
// 1. 二分查找(支持复杂比较) function binarySearch(arr, target, compareFn = (a, b) => a – b) { let left = 0; let right = arr.length – 1; while (left <= right) { const mid = Math.floor((left + right) / 2); const cmp = compareFn(arr[mid], target); if (cmp === 0) return mid; if (cmp < 0) left = mid + 1; else right = mid – 1; } return -1; }
// 2. 使用Map实现O(1)查找 class FastLookup { constructor(items, keyFn = item => item.id) { this.map = new Map(); this.keyFn = keyFn; items.forEach(item => { this.map.set(keyFn(item), item); }); } get(key) { return this.map.get(key); } has(key) { return this.map.has(key); } }
// 3. 模糊搜索(Levenshtein距离) function levenshteinDistance(a, b) { const matrix = Array(b.length + 1) .fill() .map(() => Array(a.length + 1).fill(0)); for (let i = 0; i <= a.length; i++) matrix[0][i] = i; for (let j = 0; j <= b.length; j++) matrix[j][0] = j; for (let j = 1; j <= b.length; j++) { for (let i = 1; i <= a.length; i++) { const cost = a[i – 1] === b[j – 1] ? 0 : 1; matrix[j][i] = Math.min( matrix[j][i – 1] + 1, // 删除 matrix[j – 1][i] + 1, // 插入 matrix[j – 1][i – 1] + cost // 替换 ); } } return matrix[b.length][a.length]; }
// 4. 使用Trie树进行前缀搜索 class TrieNode { constructor() { this.children = new Map(); this.isEndOfWord = false; } }
class Trie { constructor() { this.root = new TrieNode(); } insert(word) { let node = this.root; for (const char of word) { if (!node.children.has(char)) { node.children.set(char, new TrieNode()); } node = node.children.get(char); } node.isEndOfWord = true; } search(prefix) { let node = this.root; // 找到前缀的最后一个节点 for (const char of prefix) { if (!node.children.has(char)) { return []; } node = node.children.get(char); } // 收集所有以该前缀开头的单词 return this._collectWords(node, prefix); } _collectWords(node, prefix) { const words = []; if (node.isEndOfWord) { words.push(prefix); } for (const [char, childNode] of node.children) { words.push(…this._collectWords(childNode, prefix + char)); } return words; } }

四、性能优化与内存管理
4.1 算法性能优化技巧
// 1. 使用Web Workers进行CPU密集型计算 // main.js const worker = new Worker('worker.js');
worker.postMessage({ data: largeArray }); worker.onmessage = event => { console.log('Result:', event.data); };
// worker.js self.onmessage = event => { const result = heavyComputation(event.data.data); self.postMessage(result); };
// 2. 使用requestIdleCallback进行调度 function processInBackground(tasks) { function processTask(deadline) { while (tasks.length > 0 && deadline.timeRemaining() > 0) { const task = tasks.shift(); executeTask(task); } if (tasks.length > 0) { requestIdleCallback(processTask); } } requestIdleCallback(processTask); }
// 3. 使用WeakMap和WeakSet优化内存 // WeakMap的键是弱引用,不影响垃圾回收 const weakCache = new WeakMap();
function expensiveComputation(obj) { if (weakCache.has(obj)) { return weakCache.get(obj); } const result = /* 复杂计算 */; weakCache.set(obj, result); return result; }
// 4. 防抖与节流优化 function debounce(fn, delay) { let timer; return function(…args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; }
function throttle(fn, limit) { let inThrottle; return function(…args) { if (!inThrottle) { fn.apply(this, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; }
// 5. 使用位运算优化 // 判断奇偶 const isEven = n => (n & 1) === 0;
// 交换两个数(不使用临时变量) let a = 5, b = 10; a ^= b; b ^= a; a ^= b;
// 判断2的幂 const isPowerOfTwo = n => n > 0 && (n & (n – 1)) === 0;
4.2 数据缓存与记忆化
// 1. 记忆化函数(Memoization) function memoize(fn) { const cache = new Map(); return function(…args) { const key = JSON.stringify(args); if (cache.has(key)) { return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); return result; }; }
// 使用 const factorial = memoize(n => { if (n <= 1) return 1; return n * factorial(n – 1); });
// 2. LRU缓存实现 class LRUCache { constructor(capacity) { this.capacity = capacity; this.cache = new Map(); } get(key) { if (!this.cache.has(key)) return -1; // 移动到最新位置 const value = this.cache.get(key); this.cache.delete(key); this.cache.set(key, value); return value; } put(key, value) { if (this.cache.has(key)) { this.cache.delete(key); } else if (this.cache.size >= this.capacity) { // 删除最旧的项 const oldestKey = this.cache.keys().next().value; this.cache.delete(oldestKey); } this.cache.set(key, value); } }
// 3. 使用Proxy实现智能缓存 function createCachedApi(apiFunction) { const cache = new Map(); return new Proxy(apiFunction, { apply(target, thisArg, args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log('Cache hit:', key); return Promise.resolve(cache.get(key)); } return target.apply(thisArg, args).then(result => { cache.set(key, result); return result; }); } }); }

五、实用算法与设计模式
5.1 函数式编程实用算法
// 1. 函数组合与管道 const compose = (…fns) => x => fns.reduceRight((acc, fn) => fn(acc), x); const pipe = (…fns) => x => fns.reduce((acc, fn) => fn(acc), x);
// 使用 const add = x => y => x + y; const multiply = x => y => x * y; const square = x => x * x;
const compute = pipe( add(5), // x + 5 multiply(2), // (x+5)*2 square // ((x+5)*2)^2 );
console.log(compute(3)); // ((3+5)*2)^2 = 256
// 2. 柯里化工具函数 const curry = fn => { const arity = fn.length; return function curried(…args) { if (args.length >= arity) { return fn.apply(this, args); } else { return (…moreArgs) => curried.apply(this, args.concat(moreArgs)); } }; };
// 使用柯里化 const sum = curry((a, b, c) => a + b + c); const add5 = sum(5); const add5And10 = add5(10);
console.log(add5And10(15)); // 30
// 3. 惰性求值与无限序列 function* naturalNumbers() { let n = 1; while (true) { yield n++; } }
// 获取前10个偶数 const first10Evens = […naturalNumbers()] .filter(n => n % 2 === 0) .slice(0, 10);
// 4. Transducer(转换器)模式 const mapTransducer = fn => next => (acc, val) => next(acc, fn(val)); const filterTransducer = predicate => next => (acc, val) => predicate(val) ? next(acc, val) : acc;
const transduce = (transducer, reducer, initial, collection) => { const transform = transducer(reducer); return collection.reduce(transform, initial); };
// 使用 const numbers = [1, 2, 3, 4, 5]; const xform = compose( mapTransducer(x => x * 2), filterTransducer(x => x > 5) );
const result = transduce(xform, (acc, val) => […acc, val], [], numbers); // [6, 8, 10]
5.2 实用数据处理算法
// 1. 数据分组与聚合 function groupBy(array, keyFn) { return array.reduce((groups, item) => { const key = keyFn(item); if (!groups[key]) groups[key] = []; groups[key].push(item); return groups; }, {}); }
// 使用 const students = [ { name: 'Alice', grade: 'A', subject: 'Math' }, { name: 'Bob', grade: 'B', subject: 'Math' }, { name: 'Charlie', grade: 'A', subject: 'Science' } ];
const bySubject = groupBy(students, s => s.subject);
// 2. 数据采样与分页 function paginate(array, pageSize, pageNumber) { const start = (pageNumber – 1) * pageSize; const end = start + pageSize; return array.slice(start, end); }
function reservoirSampling(array, k) { const sample = array.slice(0, k); for (let i = k; i < array.length; i++) { const j = Math.floor(Math.random() * (i + 1)); if (j < k) { sample[j] = array[i]; } } return sample; }
// 3. 数据验证与清洗 const validators = { required: value => value != null && value.toString().trim() !== '', email: value => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value), minLength: min => value => value.length >= min, maxLength: max => value => value.length <= max, pattern: regex => value => regex.test(value) };
function validate(data, rules) { const errors = {}; for (const [field, fieldRules] of Object.entries(rules)) { for (const rule of fieldRules) { if (!rule.validator(data[field])) { errors[field] = rule.message; break; } } } return errors; }
// 4. 数据转换管道 class DataPipeline { constructor() { this.steps = []; } addStep(fn) { this.steps.push(fn); return this; } process(data) { return this.steps.reduce((acc, step) => step(acc), data); } }
// 使用 const pipeline = new DataPipeline() .addStep(data => data.filter(item => item.active)) .addStep(data => data.map(item => ({ …item, score: item.points * item.multiplier }))) .addStep(data => data.sort((a, b) => b.score – a.score)) .addStep(data => data.slice(0, 10));
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。




