前端手写
author: @linkaimin
Function.prototype.Call = function (context) {
let cxt = context || window
cxt.fn = this;
let args = [...arguments].slice(1)
let res = arguments.length > 1?cxt.fn(args):cxt.fn()
delete cxt.fn
return res;
}Function.prototype.Apply = function (context) {
let cxt = context || window;
cxt.fn = this;
let args = [...arguments][1];
res = arguments[1] ? cxt.fn(args):cxt.fn();
delete cxt.fn;
return res
}Function.prototype.Bind = function (context) {
if (typeof this !== 'function') {
return;
}
let that = this;
let args = [...arguments].slice(1);
function fn() {
let self = this instanceof that ? this : context;
let addArgs = [...arguments];
return that.apply(self, [...args, ...addArgs]);
}
fn.prototype = this.prototype;
return fn;
}function New(Obj,...args){
let obj = Object.create(Obj.prototype);
Obj.apply(obj,args);
return obj;
}function deepClone1(obj) {
var objClone = Array.isArray(obj) ? [] : {};
if (obj && typeof obj === "object") {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === "object") {
objClone[key] = deepClone1(obj[key]);
} else {
objClone[key] = obj[key];
}
}
}
}
return objClone;
}function debounce(func, wait) {
let timer;
return function() {
let context = this;
let args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}function throttle(func, wait) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}class MyPromise {
constructor(executor) {
this.$state = 'PENDING';
this.$value= null;
const resolve = res => {
if (this.$state !== 'PENDING') {
return;
}
this.$state = 'FULFILLED';
this.$value = res;
return res;
};
const reject = err => {
if (this.$state !== 'PENDING') {
return;
}
this.$state = 'REJECTED';
this.$value = err;
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
};
}function sumBigNumber(a, b) {
let res = '';
let temp = 0;
a = a.split(''),
b = b.split('')
while (a.length || b.length || temp) {
temp = temp + ~~a.pop() + ~~b.pop();
res = temp % 10 + res;
temp = temp > 9;
}
return res
}function jsQuickSort(array) {
if (array.length <= 1) {
return array;
}
const pivotIndex = Math.floor(array.length / 2);
const pivot = array.splice(pivotIndex, 1)[0];
const left = [], right = [];
array.forEach(item => {
if (item < pivot) {
left.push(item);
} else {
right.push(item);
}
});
return jsQuickSort(left).concat(pivot, jsQuickSort(right));
}最后更新于
这有帮助吗?