前端手写代码整理(个人整理_彦超)

防抖函数

const debounce = (fn, wait) => {
	let _ = ''
	return (...arg) => {
		clearTimeout(_)
		_ = setTimeout(() => {
			fn.apply(this, arg)
		}, wait)
	}
}
input.addEventListener("input", debounce(ajax, 1000));

节流函数

const throttle = (fn, s) => {
	let a = +new Date(),
		_    
	return (...arg) => {
		let b = +new Date() - a
		if (b > s) {
			_ = setTimeout(() => {
				fn(arg);
				_ = ''
			}, s)
			a = +new Date()
		}
	}
}
input.addEventListener("input", throttle(ajax, 1000));

睡眠函数

function sleep(s){
	return new Promise(resolve=>{
		setTimeout(resolve,s)
	})
}

运行
sleep(1000).then(()=>alert(1))
            或
!async function run() {
	await sleep(1500);
	console.log('start await');
}()

js进行浮点运算

let float_ = (...arg) => {    
	let len = Math.max(...arg.map(i => {
		let [, _] = String(i).split('.')
		console.log(_)
		return _ ? _.length : ''
	}))
	return arg.reduce((all, i) => all + i * len / len, 0)
}

函数克里化

let curry = fn => ju = (...arg) => arg.length == fn.length ? fn(...arg) : (...args) => ju(...arg, ...args)

手写ajax

let ajax=obj=>{
	let _=Object.assign({
		methods:'GET',
		url:'www.xxx.com',
		data:''
	},obj)
	return new Promise((resolve,reject)=>{
		let xhr = new XMLHttpRequest,
			sendData = ''
		if(_.data){
			for(let i in _.data){
				sendData += `&${i}=${_.data[i]}`
			}
		}
		let url = sendData ? `${obj.url}?${sendData}` : obj.url
		if (methods = 'GET') {
			xhr.open('GET', obj.url, true)
			xhr.send(sendData)
		}
		if (methods = 'POST') {
			xhr.open('POST', obj.url, true)
			xhr.send(sendData.slice(1))
		}
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200 || XHR.status === 304) {
					resolve(JSON.parse(xhr.responseText))
				} else {
					reject(Error)
				}
			}
		}
	})
}

队列函数(无论是否异步按照顺序调用函数)

let stack=[],
    index=0
function next(){
	var fn=stack[i]
	index += 1 
	if (typeof fn == 'function') {
		fn();
	}
}	
function fn1(){
	console.log('第一个调用')
	next();
}
function fn2(){
	setTimeout(function() {
		console.log('第二个被调用');
		next();
	}, 1000)
}
function fn3() {
	console.log('第三个调用');
	next();
}
stack.push(fn1, fn2, fn3)
next();

使用async写异步函数(图片是否被正确加载)

async function load(url) {
	var image = new Image();
	image.onload = function() { //图片加载成功,调用resolve方法
		return console.log(image)
	};
	image.onerror = function() { //图片加载不成功,调用reject方法
		throw '错误'
	};
	image.src = url;
}
运行
~async function img() {
	return await load(
		'https://www.xxx.com'
	)
}()

Instanceof函数

function Instanceof_(obj, fn) {
	while (true) {
		if (obj.__proto__ === null) return false
		if (obj.__proto__ === fn.prototype) return true
		 obj= obj.__proto__;
	}
}

call函数

Function.prototype.call_ = function() {
	let obj = Array.from(arguments)[0] || window,
		arg = Array.from(arguments).slice(1),
		key = Symbol(),
		result
	obj[key] = this
	result = obj[key](...arg)
	delete obj[key]
	return result
}

bind函数

Function.prototype.bind_ = function() {
	let obj = Array.from(arguments)[0] || window,
		arg = Array.from(arguments).slice(1),
		self = this
	return function(){
		let args=Array.from(arguments).slice(1)
		return self.call(obj,[...arg,...args])
	}
}

EventEmitter(收集发布)

class EventEmitter {
	constructor() {
		this.obj = {}
	}
	on(key, fn) {
		let Events = []
		Event.push(fn)
		this.obj[key] = Event
	}
	emit(key, ...arg) {
		let Events = this.obj[key]
		if (Events.length) {
			Events.forEach(i => i(...arg))
		}
	}
}

深拷贝(解决循环引用)

function clone(target, map = new WeakMap()) {
    if (typeof target === 'object') {
        let cloneTarget = Array.isArray(target) ? [] : {};
        if (map.get(target)) {
            return map.get(target);
        }
        map.set(target, cloneTarget);
        for (const key in target) {
            cloneTarget[key] = clone(target[key], map);
        }
        return cloneTarget;
    } else {
        return target;
    }
};

dom节点的遍历

function one_(node) {
	if (node.nodeType == 1) {
		console.log(node.tagName.toLowerCase())
	}
	for (var i = 0; i < node.childNodes.length; i++) {
		if (node.childNodes[i].nodeType === 1) {
			one_(node.childNodes[i])
		}
	}
}

LRU算法

class Lru_cache {
	constructor(max) {
		this.max = max;
		this.cache = new Map();
	}
	get(key) {
		let value = this.cache.get(key);
		if (!value) return;
		this.cache.delete(key);
		this.cache.set(key, value);
		return value;
	}
	add(key, value) {
		if (this.cache.size > this.max - 1) {
			const keys = this.cache.keys().next().value;
			this.cache.delete(keys);
		}
		this.cache.set(key, value);
	}

}

es5继承

function Far(name){
        this.name = name;
        this.color = ["red","green","blue"];
    }
    Far.prototype.sayName = function(){
        console.log(this.name);
    };
function Son(name,age){
        Far.call(this,name);
        this.age  = age;
    }
	Son.prototype=Object.creat(Far.prototype)
	San.prototype.constructor = San

es6继承

class Big {
	constructor(name) {
		this.name = name
	}
	getName() {
		return this.name
	}
}
class Small extends Big {
	constructor(name, sex) {
		super(name)
		this.sex = sex
	} 
	getSex() {
		return this.sex
	}
}

var big = new Big('o( ̄ヘ ̄o#)')
var small = new Small('o( ̄ヘ ̄o#)', '♀')
console.log(big.getName())
console.log(small.getName())

手写new

function new_(fn,arg){
	let obj={}
	Object.getPrototypeOf(obj,fn.prototype)
	fn.apply(obj,arg)
	return obj
}

手写Object.create

function _create(obj) {
	function C() {}
	C.prototype = obj;
	return new C();
}

手写Promise

class MyPromise {  
constructor(fn) {
	this.status = 'padding'
	this.data = ''
	this.error = ''
	this.resolveArr = []
	this.rejectArr = []
	let resolve = (data) => {
		setTimeout(() => {
			if (this.status == 'padding') {
				this.data = data
				this.status = 'resolved'
				this.resolveArr.forEach(i => i())
			}
		}, 0);
	}
	let reject = (error) => {
		setTimeout(() => {
			if (this.status == 'padding') {
				this.error = error
				this.status = 'rejected'
				this.rejectArr.forEach(i => i())
			}
		}, 0);
	}
	fn(resolve, reject)
}
then(Onresolve, Onreject) {
	if (this.status == 'resolved') {
		return new MyPromise((resolve, reject) => {
			let res = Onresolve(this.data)
			if (res instanceof MyPromise) {
				res.then(resolve, reject)
			} else {
				resolve(res)
			}
		})
	}
	if (this.status == 'rejected') {
		return new MyPromise((resolve, reject) => {
			let res = Onreject(this.error)
			if (res instanceof MyPromise) {
				res.then(resolve, reject)
			} else {
				resolve(res)
			}
		})
	}
	if (this.status == 'padding') {
		return new MyPromise((resolve, reject) => {
			this.resolveArr.push(() => {
				let res = Onresolve(this.data)
				if (res instanceof MyPromise) {
					res.then(resolve, reject)
				} else {
					resolve(res)
				}
			})
			this.rejectArr.push(() => {
				let res = Onreject(this.error)
				if (res instanceof MyPromise) {
					res.then(resolve, reject)
				} else {
					resolve(res)
				}
			})
		})
	}
}
static resolve(data) {
	return new MyPromise(resolve => resolve(data))
}
static reject(error) {
	return new MyPromise(reject => reject(error))
}
}

手写reduce

Array.prototype.reduce_2 = function(fn, back) {
	let arr = this
	for (var i=0; i < arr.length; i++) {
		return !back ? fn(arr[i], arr[i + 1], i + 1, arr) : fn(back, arr[i], i, arr)
	}
}

手写map

Array.prototype.map_ = function(fn) {
	let arr = this
	let arr_ = []
	for (let i = 0; i < arr.length; i++) {
		arr_[i] = fn(arr[i], i, arr)
	}
	return arr_
}

手写filter

Array.prototype.filter_=function(fn){
	let arr=this,
	arr_=[]
	for (let i = 0; i < arr.length; i++) {
		if(fn(arr[i],i,arr)){
			arr_[i]=arr[i]
		}
	}
	return arr_
}

实现冒泡排序

function bubbing_(arr) {
	for (let i = 0; i < arr.length - 1; i++) {
		for (let j = 0; j < arr.length - 1 - i; j++) {
			if (arr[j] > arr[j + 1]) {
				[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
			}
		}
	}
	return arr
}

实现选择排序

function select_(arr) {
	for (let i = 0; i < arr.length; i++) {
		for (let j = i + 1; j < arr.length; j++) {
			if (arr[j] < arr[i]) {
				[arr[j], arr[i]] = [arr[i], arr[j]]
			}
		}
	}
	return arr
}

实现插入排序

function insert(array) {
	for (let i = 1; i < array.length; i++) { 
		var j = i - 1; 
		while (j >= 0 && array[j] > array[i]) { 
			[arr[j], arr[i]] = [arr[i], arr[j]] 
			j--;
		}
	}
	return array;
}

实现快速排序

function fast_(arr) {
	let len = arr.length,
		r = [],
		l = [],
		bsc = arr[0]
	if (len < 2) {
		return arr
	}
	for (let i = 1; i < len; i++) {
		if (arr[i] < bsc) {
			l.push(arr[i])
		} else {
			r.push(arr[i])
		}
	}
	return [...k(l), bsc, ...k(r)]
}

取任意区间任意个任意值

function yi(mi, ma, k) {
	if (mi > ma)[mi, ma] = [ma, mi]
	let max = Math.floor(ma),
		min = Math.ceil(mi),
		o = new Set()
	while (o.size < k) {
		o.add(Math.floor(Math.random() * (max - min + 1)) + min)
	}
	let c = [...o].sort((a, b) => {
		return a - b
	}) 
	let _c = c.reduce((a, b) => a + b, 0)
	return _c
}

你可能感兴趣的:(前端手写代码整理(个人整理_彦超))