JS常用手寫工具函數(shù)

手寫防抖(debounce)

function debounce(fn, delay) {

? let timer;

? return function(...args) {

? ? clearTimeout(timer);

? ? timer = setTimeout(() => fn.apply(this, args), delay);

? };

}

手寫節(jié)流(throttle)

function throttle(fn, delay) {

? let flag = true;

? return function(...args) {

? ? if (!flag) return;

? ? flag = false;

? ? setTimeout(() => {

? ? ? fn.apply(this, args);

? ? ? flag = true;

? ? }, delay);

? };

}

合并數(shù)組

? ? ? ? let arr1=[1,2,3];

? ? ? ? let arr2=[4,5,6];

? ? ? ? Array.prototype.push.apply(arr1,arr2); //將arr2合并到了arr1中

求數(shù)組最大值

? ? ? ? Math.max.apply(null,arr)

判斷字符類型

? ? ? ? Object.prototype.toString.call({})

手寫 new 操作符

function myNew(Fn, ...args) {

? const obj = Object.create(Fn.prototype);

? const result = Fn.apply(obj, args);

? return result instanceof Object ? result : obj;

}

手寫 instanceof

function myInstanceof(obj, Fn) {

? let proto = obj.__proto__;

? while (proto) {

? ? if (proto === Fn.prototype) return true;

? ? proto = proto.__proto__;

? }

? return false;

}

手寫promise

// promise 構(gòu)造函數(shù)

function Promise (fn) {

? let that = this

? that.status = 'pending' // 存儲(chǔ)promise的state

? that.value = '' // 存儲(chǔ)promise的value

? that.reason = '' // 存儲(chǔ)promise的reason

? that.onFulfilledCb = [] // 存儲(chǔ)then方法中注冊(cè)的回調(diào)函數(shù)(第一個(gè)參數(shù))

? that.onRejectedCb = [] // 存儲(chǔ)then方法中注冊(cè)的回調(diào)函數(shù)(第二個(gè)參數(shù))

? function resolve (value) {

? ? // 將promise的狀態(tài)從pending更改為fulfilled,并且以value為參數(shù)依次調(diào)用then方法中注冊(cè)的回調(diào)

? ? setTimeout (() => {

? ? ? if (that.status === 'pending') {

? ? ? ? that.status = 'fulfilled'

? ? ? ? that.value = value

? ? ? ? that.onFulfilledCb.map( item => {

? ? ? ? ? item(that.value)

? ? ? ? })

? ? ? }

? ? }, 0)

? }

? ?function reject (reason) {

? ? // 將promise的狀態(tài)從pending更改為rejected,并且以reason為參數(shù)依次調(diào)用then方法中注冊(cè)的回調(diào)

? ? setTimeout(() => {

? ? ? if (that.status === 'pending') {

? ? ? ? that.status = 'rejected'

? ? ? ? that.reason = reason

? ? ? ? that.onRejectedCb.map( item => {

? ? ? ? ? item(that.reason)

? ? ? ? })

? ? ? }

? ? }, 0)

? }

? ?fn(resolve, reject)

}

then

Promise.prototype.then = function (onFulfilled, onRejected) {

? let that = this

? let promise2 ?

? onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v

? onRejected = typeof onRejected === 'function' ? onRejected : r => r

? ?if (that.status === 'pending') {

? ? return promise2 = new promise((resolve, reject) => {

? ? ? that.onFulfilledCb.push(value => {

? ? ? ? try {

? ? ? ? ? let x = onFulfilled(value)

? ? ? ? } catch(e) {

? ? ? ? ? reject(e)

? ? ? ? }

? ? ? })

? ? ? ?that.onRejectedCb.push(reason => {

? ? ? ? try {

? ? ? ? ? let x = onRejected(reason)

? ? ? ? } catch(e) {

? ? ? ? ? reject(e)

? ? ? ? }

? ? ? })

? ? })

? }

}

手寫Promise.all

Promise.all = function(promises) {

? return new Promise((resolve, reject) => {

? ? let results = [];

? ? let count = 0;

? ? promises.forEach((promise, i) => {

? ? ? Promise.resolve(promise).then(res => {

? ? ? ? results[i] = res;

? ? ? ? if (++count === promises.length) resolve(results);

? ? ? }).catch(reject);

? ? });

? });

};

手寫 Promise.race

Promise.race = function(promises) {

? return new Promise((resolve, reject) => {

? ? promises.forEach(promise => {

? ? ? Promise.resolve(promise).then(resolve).catch(reject);

? ? });

? });

};

手寫深拷貝(Deep Clone)

function deepClone(obj, map = new WeakMap()) {

? if (typeof obj !== 'object' || obj === null) return obj;

? if (map.has(obj)) return map.get(obj); // 解決循環(huán)引用

? let result = Array.isArray(obj) ? [] : {};

? map.set(obj, result);

? for (let key in obj) {

? ? if (obj.hasOwnProperty(key)) {

? ? ? result[key] = deepClone(obj[key], map);

? ? }

? }

? return result;

}

手寫數(shù)組扁平化(flat)

function flatten(arr) {

? return arr.reduce((prev, curr) =>

? ? prev.concat(Array.isArray(curr) ? flatten(curr) : curr),

? []);

}

手寫函數(shù)柯里化(Currying)

function curry(fn) {

? return function curried(...args) {

? ? if (args.length >= fn.length) {

? ? ? return fn.apply(this, args);

? ? } else {

? ? ? return (...args2) => curried.apply(this, args.concat(args2));

? ? }

? };

}

反柯里化

Function.prototype.uncurrying = function () {

? var that = this;

? return function () {

? ? return Function.prototype.call.apply(that, arguments);

? };

};

function sayHi() {

? return "Hello " + this.value + " " + [].slice.call(arguments);

}

let sayHiuncurrying = sayHi.uncurrying();

console.log(sayHiuncurrying({ value: "world" }, "hahaha"));

手寫?bind?函數(shù)

Function.prototype.myBind = function(context, ...args) {

? const fn = this;

? return function(...args2) {

? ? return fn.apply(context, [...args, ...args2]);

? };

};

冒泡排序

Array.prototype.bubleSort = function () {

? let arr = this, len = arr.length;

? for (let outer = len; outer >= 2; outer--) {

? ? for (let inner = 0; inner <= outer - 1; inner++) {

? ? ? if (arr[inner] > arr[inner + 1]) {

? ? ? ? //升序

? ? ? ? [arr[inner], arr[inner + 1]] = [arr[inner + 1], arr[inner]];

? ? ? ? console.log([arr[inner], arr[inner + 1]]);

? ? ? }

? ? }

? }

? return arr;

}[(1, 2, 3, 4)].bubleSort(); //[1,2,3,4]

選擇排序

Array.prototype.selectSort = function () {

? let arr = this,

? ? len = arr.length;

? for (let i = 0, len = arr.length; i < len; i++) {

? ? for (let j = i, len = arr.length; j < len; j++) {

? ? ? if (arr[i] > arr[j]) {

? ? ? ? [arr[i], arr[j]] = [arr[j], arr[i]];

? ? ? }

? ? }

? }

? return arr;

}[(1, 2, 3, 4)].selectSort(); //[1,2,3,4]

call實(shí)現(xiàn)

Function.prototype.newCall = function (context, ...parameter) {

? context.fn = this;

? context.fn(...parameter);

? delete context.fn;

};

let person = {

? name: "Abiel",

};

function sayHi(age, sex) {

? console.log(this.name, age, sex);

}

sayHi.newCall(person, 25, "男"); // Abiel 25 男

apply實(shí)現(xiàn)

Function.prototype.newApply = function (context, parameter) {

? if (typeof context === "object") {

? ? context = context || window;

? } else {

? ? context = Object.create(null);

? }

? let fn = Symbol();

? context[fn] = this;

? context[fn](...parameter);

? delete context[fn];

};

bind實(shí)現(xiàn)

Function.prototype.bind = function (context, ...innerArgs) {

? var me = this;

? return function (...finnalyArgs) {

? ? return me.call(context, ...innerArgs, ...finnalyArgs);

? };

};

let person = {

? name: "Abiel",

};

function sayHi(age, sex) {

? console.log(this.name, age, sex);

}

let personSayHi = sayHi.bind(person, 25);

personSayHi("男");

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容