一、Array篇:
1.数组去重:
function unique (array) {
let res
res= array.filter((item,index,arr)=>{
return arr.indexOf(item)===index
})
return res
}
const unique = arr => [...new Set(arr)];
console.log(uniq([1,2,2,3,3,4]));
2.every:
Array.prototype.sx_every = function(callback){
if(this === [])return true;
let count = 0;
for(let i =0; i<this.length;i++){
callback(this[i],i,this)&&count++;
}
if(count === this.length){
return true;
}else{
return false;
}
}
console.log( [].sx_every((item)=>{
return item>0;
}));
3.fill:
Array.prototype.sx_fill = function (value, start, end) {
start = start < 0 ? start + length : start;
end = end < 0 ? end + length : end;
if (!end) {
end = this.length;
}
for (let i = start; i < end; i++) {
this[i] = value;
}
return this;
};
console.log([1, 2, 3, 4].fill(0, 0, 1));
4.filter:
Array.prototype.sx_filter = function (callback) {
const res = [];
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this) && res.push(this[i]);
}
return res;
};
console.log(
[1, 2, 3, 4].sx_filter((item) => {
return item > 2;
})
);
5.find:
Array.prototype.sx_find = function (callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return this[i];
}
}
};
console.log(
[2, 1, 3, 1].sx_find((item) => {
return item > 0;
})
);
6.flat:
Array.prototype.sx_flat = function (depth = 1) {
let arr = this;
while (arr.some((item) => Array.isArray(item)) && depth > 0) {
arr = [].concat(...arr);
depth--;
}
return arr.filter((item) => item !== undefined);
};
const arr = [
1,
,
3,
4,
[1, , 3, [1, 2, 3, [1, 2, 3]]],
5,
"string",
{ name: "大飞老师" },
];
console.log(arr.sx_flat(1));
7.includes:
Array.prototype.sx_includes = function (value, start = 0) {
start = start < 0 ? this.length + start : start;
for (let i = start; i < this.length; i++) {
if (value === this[i] || Object.is(this[i], value)) {
return true;
}
}
return false;
};
console.log([1, 2, NaN].sx_includes(2));
8.join:
Array.prototype.sx_join = function (sep) {
let str = "";
if (this === []) return "";
else {
for (let i = 0; i < this.length; i++) {
sep = i === this.length - 1 || this.length === 1 ? "" : sep;
str += this[i] + sep;
}
}
return str;
};
console.log([1, 2, , 3].sx_join("_"));
9.map:
Array.prototype.sx_map = function (callback) {
const res = [];
for (let i = 0; i < this.length; i++) {
res.push(callback(this[i], i, this));
}
return res;
};
console.log(
[1, 2, 3, 4].sx_map((item, index, arr) => {
return item;
})
);
10. reduce:
Array.prototype.sx_reduce = function (callback, initValue) {
let acc = 0;
let index = 0;
let that = this;
const _this = this.filter((item) => {
return item !== undefined;
});
const len = !initValue ? _this.length - 1 : _this.length;
if ((_this === undefined || _this === []) && !initValue) {
throw new TypeError("this is null or not defined");
} else if (
(_this.length === 1 && !initValue) ||
(_this.length === 0 && initValue)
) {
return initValue || _this[0];
} else {
for (let i = 0; i < len; i++) {
if (initValue !== undefined) {
if (that.indexOf(_this[i]) !== -1) {
index = that.indexOf(_this[i]);
}
acc = i === 0 ? initValue : acc;
acc = callback(acc, _this[i], index, _this);
} else {
acc = i === 0 ? _this[i] : acc;
if (that.indexOf(_this[i + 1]) !== -1) {
index = that.indexOf(_this[i + 1]);
}
acc = callback(acc, _this[i + 1], index, _this);
}
}
}
return acc;
};
console.log(
[1, , 3].sx_reduce((acc, cur, i, arr) => {
console.log(i);
return acc + cur;
}, 1)
);
11.splice:
Array.prototype._splice = function (...args) {
let deletes = [];
let appends = [];
let heads = [];
let tails = [];
let index, howmany;
if (args.length === 0) return res;
index = args[0];
index = Number(index);
index = index === index ? index : 0;
if (args.length > 1) {
howmany = args[1];
howmany = Number(howmany);
howmany = howmany === howmany ? howmany : 0;
}
if (args.length > 2) {
appends = args.filter((v, i) => i > 1);
}
for (let i = 0; i < this.length; i++) {
if (i < index) {
heads.push(this.shift());
}
if (i <= index + howmany - 1) {
deletes.push(this.shift());
}
if (index + howmany <= i) {
tails.push(this.shift());
}
}
this.unshift(...heads);
this.push(...appends);
this.push(...tails);
return deletes;
};
二、Function篇:
1. apply:
Function.prototype.sx_apply = function (obj, ...args) {
obj = obj || window;
let fn = Symbol();
obj[fn] = this;
return obj[fn](...args.flat());
};
let obj1 = {
name: "木木",
message(age, weight) {
console.log(`${this.name}是${age}岁,体重是${weight}斤`);
},
};
let obj2 = {
name: "mumu",
};
obj1.message.sx_apply(obj2, [18, 60]);
2.call:
Function.prototype.sx_call = function (obj, ...args) {
obj = obj || window;
const fn = Symbol();
obj[fn] = this;
return obj[fn](...args);
};
let obj1 = {
name: "木木",
message(age, weight) {
console.log(`${this.name}是${age}岁,体重是${weight}斤`);
},
};
let obj2 = {
name: "mumu",
};
obj1.message.sx_call(obj2, 18, 60);
3.bind:
Function.prototype.sx_bind = function (obj, ...args) {
obj = obj || window;
args = args ? args : [];
const fn = Symbol();
obj[fn] = this;
return function newFunction(innerArgs) {
innerArgs = innerArgs ? innerArgs : [];
if (this instanceof newFunction) {
return new obj[fn](...args, ...innerArgs);
}
return obj[fn](...args, ...innerArgs);
};
};
let obj1 = {
name: "木木",
callAge(age, weight) {
console.log(`${this.name}是${age}岁,体重是${weight}斤`);
},
};
let obj2 = {
name: "mumu",
};
const res = obj1.callAge.sx_bind(obj2, 18, 60);
res("nunu");
function bar(name) {
this.name = name;
console.log(this.value);
}
let foo = {
value: 1,
};
const result = bar.sx_bind(foo, "shy");
const ob = new result();
console.log(ob.name);
三、Object篇:
1.解析查询字符串参数为对象:
let url = "www.test.com/user?name='lihua'&age=18";
const parseQueryParams = (url) => {
let QueryParamsIndex = url.indexOf("?");
let queryParams = url.slice(QueryParamsIndex + 1);
let arr = queryParams.split("&");
let obj = {};
for (let item of arr) {
let i = item.split("=");
obj[i[0]] = i[1];
}
return obj;
};
let res = parseQueryParams(url);
console.log(res);
2.json对象转为树:
const list = [
{ id: 1, title: "tab1", pId: 0 },
{ id: 2, title: "tab2", pId: 0 },
{ id: 3, title: "tab1-1", pId: 1 },
{ id: 4, title: "tab2-2", pId: 2 },
];
const jsonToTree = (list) => {
let res = [];
let map = list.reduce((res, cur) => ((res[cur.id] = cur), res), {});
console.log(map, "df");
for (const item of list) {
if (item.pId === 0) {
res.push(item);
continue;
}
if (item.pId in map) {
let parent = map[item.pId];
parent.children = parent.children || [];
parent.children.push(item);
}
}
return res;
};
console.log(jsonToTree(list));
treeToflat(树转json)
let data = [
{id:1,title:'标题1',parent_id:0,},
{id:2,title:'标题2',parent_id:0,
children:[
{id:3,title:'标题2-1',parent_id:2,
children:[
{id:4,title:'标题3-1',parent_id:3,
children:[
{id:5,title:'标题4-1',parent_id:4}
]}
]},
{id:6,title:'标题2-2',parent_id:2}
]
}
],
function treeToFlat(data){
return data.reduce((pre,cur)=>{
const {children=[],...i}=cur;
return pre.concat([{...i}],treeToFlat(children))
},[]);
}
console.log(treeToFlat(data));
3.assign:
Object.sx_assign = function (target, ...args) {
if (target === null || target === undefined) {
throw new Error("target不能为null和undefined");
}
target = Object(target);
for (let nextObj of args) {
for (let key in nextObj) {
nextObj.hasOwnProperty(key) && (target[key] = nextObj[key]);
}
}
return target;
};
const testA = {
name: "mumu",
};
const testB = {
name: "nvnv",
age: 18,
};
const testC = {
gender: "男",
};
console.log(Object.sx_assign(testA, testB, testC));
4.create:
Object.sx_create = function (proto, propertyObj) {
if (typeof proto !== "object" && typeof proto !== "function") {
throw new TypeError("Proto should be an Object");
}
if (propertyObj === null) {
throw new TypeError("propertyObj is null");
}
function F() {}
F.prototype = proto;
const obj = new F();
if (propertyObj !== undefined) {
Object.defineProperties(obj, propertyObj);
}
return obj;
};
const obj = {
name: "mumu",
};
const obj2 = {
property1: {
value: 1,
writable: true,
},
property2: {
value: "Hello",
writable: false,
enumerable: true,
configurable: true,
},
};
const obj1 = Object.sx_create(obj, obj2);
console.log(obj1.name, obj1.property1, obj1.property2);
5.entries:
Object.prototype.sx_entries = function (obj) {
let res = [];
for (let key in obj) {
obj.hasOwnProperty(key) && res.push([key, obj[key]]);
}
return res;
};
const obj = {
name: "mumu",
age: 18,
gender: "男",
};
console.log(Object.sx_entries(obj));
6.instanceof:
function myInstanceof(father, child) {
const fp = father.prototype;
let cp = Object.getPrototypeOf(child);
while (cp) {
if (cp === fp) return true;
cp = Object.getPrototypeOf(cp);
}
return false;
}
function Person(name, age) {
this.name = name;
this.age = age;
}
const obj = new Person("nvnv", 18);
obj2 = {};
console.log(myInstanceof(Person, obj2));
7. Object.is:
Object.prototype.sx_is = function (x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
}
return x !== x && y !== y;
};
console.log(Object.sx_is("123", "123"));
四、String篇:
1.实现模板字符串:
let name = "lihua";
let age = 18;
let str = "${name}${age}岁了";
str = str.replace(/\$\{([\w]*)\}/g, function () {
return eval(arguments[1]);
});
console.log(str);
2.slice:
String.prototype.sx_slice = function (start, end) {
start = start < 0 ? this.length + start : start;
end = !end && end !== 0 ? this.length : end;
let str = "";
if (start >= end) return "";
for (let i = start; i < end; i++) {
str += this[i];
}
return str;
};
let str1 = "hello";
console.log(str1.sx_slice(-3));
console.log(str1.slice(-3));
3.substring:
String.prototype.sx_substring = function (start, end) {
if (start === end) return "";
start =
start < 0 || !start ? 0 : start > this.length ? this.length : start;
end = !end || end < 0 ? 0 : end > this.length ? this.length : end;
if (start > end) {
let temp;
temp = start;
start = end;
end = temp;
}
let str = "";
for (let i = start; i < end; i++) {
str += this[i];
}
return str;
};
let str1 = "hello";
console.log(str1.sx_substring(2, 0));
console.log(str1.substring(2, 0));
五、Promise篇:
1.all:
const p1 = Promise.resolve(1);
const p2 = Promise.reject(5);
const p3 = Promise.resolve(3);
const p4 = Promise.reject(4);
let pArr = [p1, p3];
Promise.all = function (pArr) {
let index = 0,
result = [];
return new Promise((resolve, reject) => {
pArr.forEach((p, i) => {
Promise.resolve(p).then(
(value) => {
index++;
result[i] = value;
if (result.length === pArr.length) {
resolve(result);
}
},
(err) => {
reject(err);
}
);
});
});
};
let res = Promise.all(pArr);
console.log(res);
2.allSettled:
Promise.allSettled = function (pArr) {
let result = [];
return new Promise((resolve, reject) => {
pArr.forEach((p) => {
Promise.resolve(p).then(
(value) => {
result.push({
status: "fulfilled",
value,
});
if (pArr.length === result.length) {
resolve(result);
}
},
(reason) => {
result.push({
status: "rejected",
reason,
});
if (pArr.length === result.length) {
resolve(result);
}
}
);
});
});
};
const p1 = Promise.resolve(1);
const p2 = Promise.reject(2);
const p3 = Promise.resolve(3);
const p4 = Promise.reject(4);
let pArr = [p1, p2, p3, p4];
console.log(Promise.allSettled(pArr));
3.any:
Promise.any = function (pArr) {
let index = 0,
result = [];
return new Promise((resolve, reject) => {
pArr.foreach((p, i) => {
Promise.resolve(p).then(
(value) => {
resolve(value);
},
(reason) => {
index++;
result[i] = reject(reason);
if (result.length === pArr.length) {
reject(new AggregateError("All promises were rejected"));
}
}
);
});
});
};
const p1 = Promise.resolve(1);
const p2 = Promise.reject(2);
const p3 = Promise.resolve(3);
const p4 = Promise.reject(4);
let pArr = [p2, p4];
console.log(Promise.any(pArr));
4.finally:
Promise.prototype.sx_finally = function (callback) {
return this.then(
(value) => {
callback();
return value;
},
(reason) => {
callback();
throw reason;
}
);
};
5.race:
Promise.race = function (pArr) {
return new Promise((resolve, reject) => {
pArr.forEach((p, i) => {
resolve(p).then(
(value) => {
resolve(p);
},
(reason) => {
reject(p);
}
);
});
});
};
const p1 = Promise.resolve(1);
const p2 = Promise.reject(2);
const p3 = Promise.resolve(3);
const p4 = Promise.reject(4);
let pArr = [p2, p1, p3, p4];
console.log(Promise.race(pArr));
6.reject:
Promise.sx_reject = function (reason) {
return new Promise((_, reject) => {
reject(reason);
});
};
let p = Promise.resolve(2);
console.log(Promise.sx_reject(p));
7.resolve:
Promise.sx_resolve = function (value) {
if (value instanceof Promise) {
return value;
} else {
return new Promise((resolve) => resolve(value));
}
};
let p2 = Promise.resolve(1);
console.log(Promise.sx_resolve(p2));
8.手写一个完整的Promise:
const PENDING = "pending";
const RESOLVED = "resolved";
const REJECTED = "rejected";
function Promise(executor) {
const self = this;
self.status = PENDING;
self.data = undefined;
self.callbacks = [];
function resolve(value) {
if (self.status !== PENDING) {
return;
}
self.status = RESOLVED;
self.data = value;
if (self.callbacks.length > 0) {
setTimeout(() => {
self.callbacks.forEach((callbacksObj) => {
callbacksObj.onResolved(value);
});
});
}
}
function reject(reason) {
if (self.status !== PENDING) {
return;
}
self.status = REJECTED;
self.data = reason;
if (self.callbacks.length > 0) {
setTimeout(() => {
self.callbacks.forEach((callbacksObj) => {
callbacksObj.onRejected(reason);
});
});
}
}
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
onResolved =
typeof onResolved === "function"
? onResolved
: (value = self.data) => value;
reason = self.result;
onRejected =
typeof onRejected === "function"
? onRejected
: (reason = self.data) => {
throw reason;
};
return new Promise((resolve, reject) => {
function handle(callback) {
try {
const result = callback(self.data);
if (result instanceof Promise) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
console.log(error, "error");
reject(error);
}
}
if (self.status === PENDING) {
self.callbacks.push({
onResolved() {
handle(onResolved);
},
onRejected() {
handle(onRejected);
},
});
} else if (self.status === RESOLVED) {
setTimeout(() => {
handle(onResolved);
});
} else {
setTimeout(() => {
handle(onRejected);
});
}
});
};
Promise.prototype.catch = function (onRejected) {
return this.then(undefined, onRejected);
};
var p = new Promise((resolve, reject) => {
setTimeout(() => {
reject("失败的回调");
console.log(
"promise对象封装异步操作,异步执行微队列中的Onrejected回调函数"
);
});
});
p.then(
(value) => {
console.log(value, "value");
},
(reason) => {
console.log(reason, "reason");
return new Promise((resolve, reject) => {
reject(3);
});
}
).catch((reason) => {
console.log("2", reason);
});
9.并行发送多个任务:
const myFun = async (list, count = 10) => {
let len = list.length;
let temp = len % count;
let res = [];
let queue = [];
times = !temp ? len / count : Math.floor(len / count) + 1;
for (i = 0; i < times; i++) {
let start = i * count;
let end = count + start < len ? count * (i + 1) : len;
queue = list.slice(start, end);
res.push(...(await Promise.all(queue)));
}
return res;
};
console.log(myFun([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4));
10.使用Promies预加载图片:
const imgPreloader = (url) => {
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = () => {
resolve("图片加载成功");
};
image.onerror = () => {
reject("图片加载出错");
};
image.src = url;
});
};
const allImgPreloader = (imgs) => {
let promiseArr = [];
imgs.forEach((src) => {
promiseArr.push(imgPreloader(src));
});
return Promise.all(promiseArr);
};
let imgs = [
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202107%2F14%2F20210714150114_698ae.thumb.1000_0.png&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658470369&t=a22bcc92c65ae42512ef880a00a3c5b0",
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202008%2F05%2F20200805155341_hitag.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658470369&t=68e80f45c093aa3ef3a1d9e45693aa5a",
];
console.log("开始渲染---渲染中。。。");
const res = allImgPreloader(imgs);
res.then((val) => {
console.log("渲染成功");
console.log( val);
});
六、 其他高频:
1.事件订阅与发布:
let eventMap = {};
function pub(msg, ...rest) {
eventMap[msg] &&
eventMap[msg].forEach((cb) => {
cb(...rest);
});
}
function sub(msg, cb) {
eventMap[msg] = eventMap[msg] || [];
eventMap[msg].push(cb);
}
sub("name", (name) => {
console.log("我是" + name);
});
pub("name", "大飞老师");
2.实现原生ajax:
function myAjax(url, method, data) {
let promise = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (
(xhr.status >= 200 && xhr.status < 300) ||
xhr.status === 304
) {
resolve(xhr.response);
} else {
reject(new Error("error"));
}
}
};
if (method.toUpperCase() === "GET") {
let paramslist = [];
for (key in data) {
paramslist.push(key + "=" + data[key]);
}
let params = paramslist.join("&");
url = url + "?" + params;
xhr.open("get", url, false);
xhr.send();
}
if (method.toUpperCase() === "POST") {
xhr.open("post", url, false);
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded;charset=utf-8"
);
xhr.send(data);
}
});
return promise;
}
3.jsonp:
function jsonp({ url, params, callback }) {
return new Promise((resolve, reject) => {
let script = document.createElement("script");
window[callback] = function (data) {
resolve(data);
document.body.removeChild(script);
};
params = { ...params, callback };
let arrs = [];
for (let key in params) {
arrs.push(`${key}=${params[key]}`);
}
script.src = `${url}?${arrs.join("&")}`;
document.body.appendChild(script);
});
}
jsonp({
url: "http://localhost:3000/say",
params: { wd: "hahaha" },
callback: "show",
}).then((data) => {
console.log(data);
});
4.函数防抖:
function debounce(fn, delay = 500) {
let timeId;
return function () {
if (timeId) {
clearTimeout(timeId);
}
timeId = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
var node = document.getElementById("test");
function getUserAction(e) {
console.log(this, e);
}
node.onmousemove = debounce(getUserAction, 1000);
5.函数节流:
function throttle(fn, delay = 500) {
let flag = true;
return function () {
if (!flag) {
return;
}
flag = false;
setTimeout(() => {
fn.apply(this, arguments);
flag = true;
}, delay);
};
}
let node = document.querySelector("#test");
node.addEventListener("mousemove", throttle(test, 1000));
function test(e) {
console.log(this, e);
}
6.函数科里化:
const curry = (fn, ...args) =>
args.length >= fn.length
? fn(...args)
: (..._args) => curry(fn, ...args, ..._args);
const add = (x, y, z) => {
return x + y + z;
};
const add1 = curry(add);
console.log(add1(1, 2, 3));
console.log(add1(1)(2)(3));
7.深拷贝:
function deepClone(obj, hash = new WeakMap()) {
if (obj === null) return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (typeof obj !== "object") return obj;
if (hash.get(obj)) return hash.get(obj);
let cloneObj = new obj.constructor();
hash.set(obj, cloneObj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], hash);
}
}
return cloneObj;
}
let obj = { name: 1, address: { x: 100 } };
obj.o = obj;
let d = deepClone(obj);
obj.address.x = 200;
console.log(d);
8.图片懒加载:
const imgs = document.getElementsByTagName("img");
const viewHeight =
window.innerHeight || document.documentElement.clientHeight;
let num = 0;
function lazyload() {
for (let i = num; i < imgs.length; i++) {
let distance = viewHeight - imgs[i].getBoundingClientRect().top;
if (distance >= 0) {
imgs[i].src = imgs[i].getAttribute("data-src");
num = i + 1;
}
}
}
window.addEventListener("scroll", lazyload, false);
9.自定义迭代器:
function iterator(list) {
let index = 0;
let len = list.length;
return {
next: function () {
let done = index >= len;
let value = !done ? list[index++] : undefined;
return { value, done };
},
};
}
var iterator1 = iterator(["1号选手", "2号选手", "3号选手"]);
console.log(iterator1.next());
console.log(iterator1.next());
console.log(iterator1.next());
console.log(iterator1.next());
10.原型链继承:
function Parent (name,age) {
this.name = name
this.age = age
}
function Child(score) {
this.score = score
this.sayScore = function (){
console.log(this.score)
}
}
Child.prototype = new Parent('ldh',18)
Child.prototype.constructor = Child
const child1 = new Child(45)
console.log(child1.name)
child1.sayScore()
console.log(Child.prototype)
console.log(Child)
11.自定义new操作符:
function myNew(Func, ...args) {
let obj = Object.create(Func.prototype);
const result = Func.apply(obj, args);
return result instanceof Object ? result : obj;
}
function Test(name, age) {
this.name = name;
this.age = age;
}
Test.prototype.sayName = function () {
console.log(this.name);
};
const obj1 = myNew(Test, "lihua", 15);
obj1.sayName();
console.log(obj1.age);
12.trim:
String.prototype.trim = function () {
return this.replace(/^\s+/, "").replace(/\s+&/, "");
};
const str = " qweqweqwe ";
console.log(str);
console.log(str.trim());
七、排序算法:
1.冒泡:
function bubbleSort(arr) {
const len = arr.length;
let flag = false;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
flag = true;
}
}
if (!flag) {
console.log(flag);
return arr;
}
}
return arr;
}
let arr1 = [1, 2, 3, 4];
let arr2 = [5, 2, 1, 4];
res1 = bubbleSort(arr1);
res2 = bubbleSort(arr2);
console.log(res1);
console.log(res2);
2.插入排序:
function insertionSort(arr) {
var len = arr.length;
var preIndex, current;
for (var i = 1; i < len; i++) {
preIndex = i - 1;
current = arr[i];
while(preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = current;
}
return arr;
}
3.快速排序:
const quickSort = (arr) => {
const len = arr.length;
if (len <= 1) return arr;
const midIndex = Math.floor(len / 2);
const leftArr = [];
const rightArr = [];
const midValue = arr.splice(midIndex, 1);
let index = 0;
while (index < len - 1) {
if (arr[index] < midValue) {
leftArr.push(arr[index]);
} else {
rightArr.push(arr[index]);
}
index++;
}
return quickSort(leftArr).concat(midValue).concat(quickSort(rightArr));
};
const arr = [3, 5, 1, 2];
const res = quickSort(arr);
console.log(res);
4.归并排序:
function mergeSort(arr) {
var len = arr.length;
if(len < 2) {
return arr;
}
var middle = Math.floor(len / 2),
left = arr.slice(0, middle),
right = arr.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
return result;
}
console.log(mergeSort([3, 2, 2, 13, 4, 2, 1]));