深度克隆,数组扁平化,快速排序
深度克隆
1 function deepClone(source) { 2 if (Array.isArray(source)) { 3 const target = []; 4 for (let item of source) { 5 target.push(deepClone(item)); 6 } 7 return target; 8 } 9 if (Object.prototype.toString.call(source) === "[object Object]") { 10 const target = {}; 11 for (let key in source) { 12 target[key] = deepClone(source[key]); 13 } 14 return target; 15 } 16 // 其它类型的克隆 17 return source; 18 }
数组扁平化
1 function platten(source) { 2 let target = []; 3 for (let item of source) { 4 Array.isArray(item) 5 ? (target = target.concat(platten(item))) // 向外层数组合并 6 : target.push(item); 7 } 8 return target; 9 }
快速排序
1 function fastSort(source) { 2 let middle = source.shift(), 3 left = [], 4 right = []; 5 for (let item of source) { 6 // undefined 不做处理 7 item < middle ? left.push(item) : right.push(item); 8 } 9 left = left.length > 1 ? fastSort(left) : left; 10 right = right.length > 1 ? fastSort(right) : right; 11 return [...left, middle, ...right]; 12 }
THE END