常见js

228 阅读5分钟

//判断对象的数据类型const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)const isArray = isType('Array')console.log(isArray([]))//使用reduce实现数组的flat方法(有问题)const selfFlat = function (depth = 1) {    let arr = Array.prototype.slice.call(this);    if( depth === 0 ) return arr;    return arr.reduce((pre, cur) => {        if(Array.isArray(cur)) {            return [...pre, ...selfFlat.call(cur, depth-1)]        }else {            return [...pre, cur]        }    }, [])}//Array.prototype.flat2 = selfFlatlet arr = [1,2,[3,4],[5,[6,7]]]console.log(selfFlat.call(arr,Infinity));function curry(fn) {    if(fn.length <= 1) return fn;    const generator = (...args) => {        if(fn.length === args.length) {            return fn(...args)        }else {            return (...args2) => {                return generator(...args, ...args2)            }        }    }    return generator;}let add = (a,b,c,d) => a+b+c+dconst curriedAdd = curry(add);console.log(curriedAdd(5)(6)(7)(8))//instanceof的实现代码function instance_of(l,r) {    let o = r.prototype;    let l = l._proto_;    while(true) {        if( l === null) return false;        if( l === o) return true;        l=l._proto_;    }}//实现callFunction.prototype.call = function (context){    if(!context){        context = typeof window == 'underfined' ? global : window;     }    context.fn = this;    let args = [...arguments].slice(1);    let result = context.fn(...args);    delete context.fn;    return result;}//applyFunction.prototype.call = function (context,rest){    if(!context){        context = typeof window == 'underfined' ? global : window;     }    context.fn = this;    let result ;    if( rest === null || rest ===undefined) {        result = context.fn(rest);    }else {        resule = context.fn(...rest);    }    delete context.fn;    return result;}//bindFunction.prototype.bind = function (context){    if(typeof this !== 'function') throw new TypeError('Not a function');    let self = this;    let args1 = [...arguments].slice(1);    function Fn(){};    Fn.prototype = this.prototype;    let bound = function () {        let res = [...args1, ...arguments];        context= this instanceof Fn ? this :context||this;        return self.apply(context,res);    }    bound.prototype = new Fn();    return bound;}//newfunction mynew(){    var obj = {}    var constructor = [].shift.call(arguments)    var args = [].slice.call(arguments)    obj.__proto__ = constructor.prototype    var result = constructor.apply(obj, args)    // 判断结果的类型    return (typeof result === 'object' || 'function') ? result : obj  }  //简易版的promisefunction myPromise(constructor){    let self = this;    self.status = 'pending';    self.value = undefined;    self.reason = undefined;    function resolve(value){        if(self.status === 'pending'){            self.value =value;            self.status = 'resolved';        }    }    function reject(reason) {        if(self.status === 'pending') {            self.reason = reason;            self.status = 'rejected';        }    }   try{       constructor(resolve,reject);   }catch(e){       reject(e);   }}myPromise.prototype.then = function(onFullfilled,onRejected) {    let self = this;    switch(self.status){        case 'resolved': onFullfilled(self.value); break;        case 'rejected': onRejected(self.reason); break;        default:break;    }}// .clearfix::AudioBufferSourceNode, .clearfix::after{//     content: " ";//     display: table;// }// .clearfix:: after {//     *zoom: 1;// }// .float_div:after{//  content:".";//  clear:both;//  display:block;//  height:0;//  overflow:hidden;//  visibility:hidden;// }// .float_div{//  zoom:1// } //防抖function debounce_1(func, wait, immediate) {    var timeout,result;    var debounecd = function(){        var context = this;        var args = arguments;        if(timeout) clearTimeout(timeout);        if(immediate){            var callNow = !timeout;            timeout = setTimeout(function(){                timeout = null;            },wait)            if(callNow) result = func.apply(context,args);        }else{            timeout = setTimeout(function(){                func.apply(context,args);            },wait)        }        return result;    };    debounecd.cancel = function(){        clearTimeout(timeout);        timeout = null;    };    return debounce_1;}var count = 1;var container = document.getElementById('container');function getUserAction(e) {    container.innerHTML = count++;};var setUseAction = debounce(getUserAction, 10000, true);container.onmousemove = setUseAction;document.getElementById("button").addEventListener('click', function(){    setUseAction.cancel();})//promiseconst PENDING = "pending";const FULFILLED = "fulfilled";const REJECTED = "rejected";function MyPromise(fn) {    const self = this;    self.value = null;    self.error = null;    self.status = PENDING;    self.onFulfilledCallbacks = [];    self.onRejectedCallbacks = [];    function resolve(value) {        if (self.status === PENDING) {            setTimeout(() => {                self.status = FULFILLED;                self.value = value;                self.onFulfilledCallbacks.forEach((callback) => callback(self.value));            }, 0)        }    }    function reject(error) {        if (self.status === PENDING) {            setTimeout(function() {                self.status = REJECTED;                self.error = error;                self.onRejectedCallbacks.forEach((callback) => callback(self.error));            }, 0)        }    }    fn(resolve, reject);}function resolvePromise(bridgePromise, x, resolve, reject) {    if (x instanceof MyPromise) {        if (x.status === PENDING) {            x.then(y => {                resolvePromise(bridgePromise, y, resolve, reject);            }, error => {                reject(error);            });        } else {            x.then(resolve, reject);        }    } else {        resolve(x);    }}MyPromise.prototype.then = function(onFulfilled, onRejected) {    const self = this;    let bridgePromise;    onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value;    onRejected = typeof onRejected === "function" ? onRejected : error => { throw error };    if (self.status === FULFILLED) {        return bridgePromise = new MyPromise((resolve, reject) => {            setTimeout(() => {                try {                    let x = onFulfilled(self.value);                    resolvePromise(bridgePromise, x, resolve, reject);                } catch (e) {                    reject(e);                }            }, 0);        })    }    if (self.status === REJECTED) {        return bridgePromise = new MyPromise((resolve, reject) => {            setTimeout(() => {                try {                    let x = onRejected(self.error);                    resolvePromise(bridgePromise, x, resolve, reject);                } catch (e) {                    reject(e);                }            }, 0);        });    }    if (self.status === PENDING) {        return bridgePromise = new MyPromise((resolve, reject) => {            self.onFulfilledCallbacks.push((value) => {                try {                    let x = onFulfilled(value);                    resolvePromise(bridgePromise, x, resolve, reject);                } catch (e) {                    reject(e);                }            });            self.onRejectedCallbacks.push((error) => {                try {                    let x = onRejected(error);                    resolvePromise(bridgePromise, x, resolve, reject);                } catch (e) {                    reject(e);                }            });        });    }}MyPromise.prototype.catch = function(onRejected) {    return this.then(null, onRejected);}module.exports = MyPromise//冒泡排序function bubbleSort(arr){    for(var i = 0; i<arr.length-1;i++){        for(var j = 0; j<arr.length-i-1;j++){            if(arr[j]>arr[j+1]){                var temp = arr[j];                arr[j] = arr[j+1];                arr[j+1] = temp;            }        }    }    return arr;}//改进冒泡function bubbleSort1(arr){    let ilen = arr.length;    let i = len -1;    while(i > 0) {        let pos = 0;        for(let j = 0 ; j<i;j++){            if(arr[j]>arr[j+1]){                pos = j;                var temp = arr[j];                arr[j] = arr[j+1];                arr[j+1] = temp;            }        }        i=pos;    }   return arr;}function bubbleSort3(arr3) {    debugger        var low = 0;        var high= arr.length-1; //设置变量的初始值        var tmp,j;        console.time('2.改进后冒泡排序耗时');        while (low < high) {            for (j= low; j< high; ++j) //正向冒泡,找到最大者                if (arr[j]> arr[j+1]) {                    tmp = arr[j]; arr[j]=arr[j+1];arr[j+1]=tmp;                }            --high;                 //修改high值, 前移一位            for (j=high; j>low; --j) //反向冒泡,找到最小者                 if (arr[j]< arr[j-1]) {                    tmp = arr[j]; arr[j]=arr[j+1];arr[j+1]=tmp;                }            ++low;         }     return arr3;    }    var arr=[3,44,38,5,47,15];    console.log(bubbleSort3(arr))//选择排序function selectionSort(arr){    let len = arr.length;    let minIndex,tmp;    for(let i = 0 ; i < len-1; i++ ){        minIndex = i;        for(let j = i+1;j<len;j++){            if(arr[j]<arr[minIndex] ) minIndex = j;        }        tmp = arr[i]; arr[i]=arr[minIndex];arr[minIndex]=tmp;    }  return arr;}var arr=[3,44,38,5,47,15];console.log(selectionSort(arr))//插入排序;function insertionSort(arr){    for (let i = 1; i<arr.length;i++){        let key = arr[i];        let j = i-1;        while( j>=0 && arr[j]>key){            arr[j+1] = arr[j];            j--;        }        arr[j+1] = key;    }    return arr;}var arr=[3,44,38,5,47,15];console.log(insertionSort(arr))function insertionSort1(arr){    for (let i = 1; i<arr.length;i++){        let key = arr[i],low=0,high = i-1;        while(low <= high){            let mid = parseInt((low+high)/2)            if(key < arr[mid]) high = mid-1;            else low = mid +1;        }        for( let j = i-1;j>=low;j--){            arr[j+1] = arr[j];        }        arr[left] = key;    }    return arr;}var arr=[3,44,38,5,47,15];console.log(insertionSort(arr))//归并排序function mergeSort(array) {    var len = array.length;    if(len < 2) {        return array;    }    var middle = Math.floor(len/2),        left = array.slice(0, middle),        right = array.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 (left[0] > right[0]){            result.push(right.shift());        }    }    while(left.length){        result.push(left.shift());    }    while(right.length){        result.push(right.shift());    }}//快速排序function swap(i,j,arr){    let temp = arr[i];        arr[i] = arr[j];        arr[j] = temp;   }function partition(){low, high, arr}{    let i = low, j = high, povit = arr[i];    while(i<j){        while(i<j && arr[j] > povit) j--;        if(i<j) swap(i++,j,arr);        while(i<j && arr[j] <= povit) i++;        if(i<j) swap(i,j--,arr);    }    return i;}function quickSort(low,high,arr){    let mid;    while(low < high){        mid = Math.floor((low+high)/2);        quickSort(low,mid-1,arr);        quickSort(mid+1,high,arr);    }}QuickSort(arr,0,arr.length-1);//防抖function debounce11(func, wait, immediate){    var timeout,result;    return function(){        var context = this;        var args = arguments;        if(timeout) clearTimeout(timeout);        if(immediate){            var callnow = !timeout;            timeout = setTimeout(function(){                timeout = null;            }, wait);            if(callnow) result=func.apply(context, args);        }else{            timeout = setTimeout(function(){                func.apply(context,args);            }, wait);        }          return result;    }}//节流 使用时间戳function throttle(func, wait){    var previous = 0;    return function(){        var now = new Date();        var context = this;        var args = arguments;        if(now - previous > wait){            func.apply(context, args);            previous = now;        }    }}//使用定时器function throttle1(func, wait){    var timeout;    return function(){        var context =this;        var args = arguments;        if(!timeout){            timeout = setTimeout(function(){                timeout = null;                func.apply(context, args)            },wait)         }    }}//深拷贝{let deepCopy = function(obj){    if(typeof obj !== 'object') return;    var newObj = obj instanceof Array ? []:{};    for(let key in obj){        if(obj.hasOwnProperty(key))        newObj[key] = typeof obj[key] === 'objece' ? deepCopy(obj[key]) : obj[key];    }    return newObj;}


加油!

//判断对象的数据类型
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType('Array')
console.log(isArray([]))

//使用reduce实现数组的flat方法(有问题)
const selfFlat = function (depth = 1) {
let arr = Array.prototype.slice.call(this);
if( depth === 0 ) return arr;
return arr.reduce((pre, cur) => {
if(Array.isArray(cur)) {
return [...pre, ...selfFlat.call(cur, depth-1)]
}else {
return [...pre, cur]
}
}, [])
}
//Array.prototype.flat2 = selfFlat
let arr = [1,2,[3,4],[5,[6,7]]]
console.log(selfFlat.call(arr,Infinity));

function curry(fn) {
if(fn.length <= 1) return fn;
const generator = (...args) => {
if(fn.length === args.length) {
return fn(...args)
}else {
return (...args2) => {
return generator(...args, ...args2)
}
}
}
return generator;
}
let add = (a,b,c,d) => a+b+c+d
const curriedAdd = curry(add);
console.log(curriedAdd(5)(6)(7)(8))

//instanceof的实现代码
function instance_of(l,r) {
let o = r.prototype;
let l = l._proto_;
while(true) {
if( l === null) return false;
if( l === o) return true;
l=l._proto_;
}
}
//实现call
Function.prototype.call = function (context){
if(!context){
context = typeof window == 'underfined' ? global : window;
}
context.fn = this;
let args = [...arguments].slice(1);
let result = context.fn(...args);
delete context.fn;
return result;
}
//apply
Function.prototype.call = function (context,rest){
if(!context){
context = typeof window == 'underfined' ? global : window;
}
context.fn = this;
let result ;
if( rest === null || rest ===undefined) {
result = context.fn(rest);
}else {
resule = context.fn(...rest);
}
delete context.fn;
return result;
}

//bind
Function.prototype.bind = function (context){
if(typeof this !== 'function') throw new TypeError('Not a function');
let self = this;
let args1 = [...arguments].slice(1);
function Fn(){};
Fn.prototype = this.prototype;
let bound = function () {
let res = [...args1, ...arguments];
context= this instanceof Fn ? this :context||this;
return self.apply(context,res);

}
bound.prototype = new Fn();
return bound;
}
//new
function mynew(){
var obj = {}
var constructor = [].shift.call(arguments)
var args = [].slice.call(arguments)
obj.__proto__ = constructor.prototype
var result = constructor.apply(obj, args)
// 判断结果的类型
return (typeof result === 'object' || 'function') ? result : obj
}

//简易版的promise
function myPromise(constructor){
let self = this;
self.status = 'pending';
self.value = undefined;
self.reason = undefined;
function resolve(value){
if(self.status === 'pending'){
self.value =value;
self.status = 'resolved';
}
}
function reject(reason) {
if(self.status === 'pending') {
self.reason = reason;
self.status = 'rejected';
}
}
try{
constructor(resolve,reject);
}catch(e){
reject(e);
}
}
myPromise.prototype.then = function(onFullfilled,onRejected) {
let self = this;
switch(self.status){
case 'resolved': onFullfilled(self.value); break;
case 'rejected': onRejected(self.reason); break;
default:break;
}
}
// .clearfix::AudioBufferSourceNode, .clearfix::after{
// content: " ";
// display: table;
// }
// .clearfix:: after {
// *zoom: 1;
// }


// .float_div:after{
// content:".";
// clear:both;
// display:block;
// height:0;
// overflow:hidden;
// visibility:hidden;
// }
// .float_div{
// zoom:1
// }

//防抖
function debounce_1(func, wait, immediate) {
var timeout,result;
var debounecd = function(){
var context = this;
var args = arguments;
if(timeout) clearTimeout(timeout);
if(immediate){
var callNow = !timeout;
timeout = setTimeout(function(){
timeout = null;
},wait)
if(callNow) result = func.apply(context,args);
}else{
timeout = setTimeout(function(){
func.apply(context,args);
},wait)
}
return result;
};
debounecd.cancel = function(){
clearTimeout(timeout);
timeout = null;
};
return debounce_1;

}
var count = 1;
var container = document.getElementById('container');

function getUserAction(e) {
container.innerHTML = count++;
};

var setUseAction = debounce(getUserAction, 10000, true);

container.onmousemove = setUseAction;

document.getElementById("button").addEventListener('click', function(){
setUseAction.cancel();
})
//promise
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function MyPromise(fn) {
const self = this;
self.value = null;
self.error = null;
self.status = PENDING;
self.onFulfilledCallbacks = [];
self.onRejectedCallbacks = [];

function resolve(value) {
if (self.status === PENDING) {
setTimeout(() => {
self.status = FULFILLED;
self.value = value;
self.onFulfilledCallbacks.forEach((callback) => callback(self.value));
}, 0)
}
}

function reject(error) {
if (self.status === PENDING) {
setTimeout(function() {
self.status = REJECTED;
self.error = error;
self.onRejectedCallbacks.forEach((callback) => callback(self.error));
}, 0)
}
}
fn(resolve, reject);
}

function resolvePromise(bridgePromise, x, resolve, reject) {
if (x instanceof MyPromise) {
if (x.status === PENDING) {
x.then(y => {
resolvePromise(bridgePromise, y, resolve, reject);
}, error => {
reject(error);
});
} else {
x.then(resolve, reject);
}
} else {
resolve(x);
}
}

MyPromise.prototype.then = function(onFulfilled, onRejected) {
const self = this;
let bridgePromise;
onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value;
onRejected = typeof onRejected === "function" ? onRejected : error => { throw error };
if (self.status === FULFILLED) {
return bridgePromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
let x = onFulfilled(self.value);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
})
}
if (self.status === REJECTED) {
return bridgePromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
let x = onRejected(self.error);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
}
if (self.status === PENDING) {
return bridgePromise = new MyPromise((resolve, reject) => {
self.onFulfilledCallbacks.push((value) => {
try {
let x = onFulfilled(value);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
});
self.onRejectedCallbacks.push((error) => {
try {
let x = onRejected(error);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
}
}
MyPromise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
}
module.exports = MyPromise


//冒泡排序
function bubbleSort(arr){
for(var i = 0; i<arr.length-1;i++){
for(var j = 0; j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
//改进冒泡
function bubbleSort1(arr){
let ilen = arr.length;
let i = len -1;
while(i > 0) {
let pos = 0;
for(let j = 0 ; j<i;j++){
if(arr[j]>arr[j+1]){
pos = j;
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
i=pos;
}
return arr;
}

function bubbleSort3(arr3) {
debugger
var low = 0;
var high= arr.length-1; //设置变量的初始值
var tmp,j;
console.time('2.改进后冒泡排序耗时');
while (low < high) {
for (j= low; j< high; ++j) //正向冒泡,找到最大者
if (arr[j]> arr[j+1]) {
tmp = arr[j]; arr[j]=arr[j+1];arr[j+1]=tmp;
}
--high; //修改high值, 前移一位
for (j=high; j>low; --j) //反向冒泡,找到最小者
if (arr[j]< arr[j-1]) {
tmp = arr[j]; arr[j]=arr[j+1];arr[j+1]=tmp;
}
++low;
}
return arr3;
}
var arr=[3,44,38,5,47,15];
console.log(bubbleSort3(arr))

//选择排序
function selectionSort(arr){
let len = arr.length;
let minIndex,tmp;
for(let i = 0 ; i < len-1; i++ ){
minIndex = i;
for(let j = i+1;j<len;j++){
if(arr[j]<arr[minIndex] ) minIndex = j;
}
tmp = arr[i]; arr[i]=arr[minIndex];arr[minIndex]=tmp;
}
return arr;
}
var arr=[3,44,38,5,47,15];
console.log(selectionSort(arr))


//插入排序;
function insertionSort(arr){
for (let i = 1; i<arr.length;i++){
let key = arr[i];
let j = i-1;
while( j>=0 && arr[j]>key){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
return arr;
}
var arr=[3,44,38,5,47,15];
console.log(insertionSort(arr))

function insertionSort1(arr){
for (let i = 1; i<arr.length;i++){
let key = arr[i],low=0,high = i-1;
while(low <= high){
let mid = parseInt((low+high)/2)
if(key < arr[mid]) high = mid-1;
else low = mid +1;
}
for( let j = i-1;j>=low;j--){
arr[j+1] = arr[j];
}
arr[left] = key;
}
return arr;
}
var arr=[3,44,38,5,47,15];
console.log(insertionSort(arr))

//归并排序
function mergeSort(array) {
var len = array.length;
if(len < 2) {
return array;
}
var middle = Math.floor(len/2),
left = array.slice(0, middle),
right = array.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 (left[0] > right[0]){
result.push(right.shift());
}
}
while(left.length){
result.push(left.shift());
}
while(right.length){
result.push(right.shift());
}
}

//快速排序
function swap(i,j,arr){
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

function partition(){low, high, arr}{
let i = low, j = high, povit = arr[i];
while(i<j){
while(i<j && arr[j] > povit) j--;
if(i<j) swap(i++,j,arr);
while(i<j && arr[j] <= povit) i++;
if(i<j) swap(i,j--,arr);
}
return i;
}

function quickSort(low,high,arr){
let mid;
while(low < high){
mid = Math.floor((low+high)/2);
quickSort(low,mid-1,arr);
quickSort(mid+1,high,arr);
}
}

QuickSort(arr,0,arr.length-1);

//防抖
function debounce11(func, wait, immediate){
var timeout,result;
return function(){
var context = this;
var args = arguments;
if(timeout) clearTimeout(timeout);
if(immediate){
var callnow = !timeout;
timeout = setTimeout(function(){
timeout = null;
}, wait);
if(callnow) result=func.apply(context, args);
}else{
timeout = setTimeout(function(){
func.apply(context,args);
}, wait);
}
return result;
}
}
//节流 使用时间戳
function throttle(func, wait){
var previous = 0;
return function(){
var now = new Date();
var context = this;
var args = arguments;
if(now - previous > wait){
func.apply(context, args);
previous = now;
}
}
}

//使用定时器
function throttle1(func, wait){
var timeout;
return function(){
var context =this;
var args = arguments;
if(!timeout){
timeout = setTimeout(function(){
timeout = null;
func.apply(context, args)
},wait)
}
}

}

//深拷贝{
let deepCopy = function(obj){
if(typeof obj !== 'object') return;
var newObj = obj instanceof Array ? []:{};
for(let key in obj){
if(obj.hasOwnProperty(key))
newObj[key] = typeof obj[key] === 'objece' ? deepCopy(obj[key]) : obj[key];
}
return newObj;
}