- 数组扁平化
[1, 3, [5, 2], [2, 3, [4, 5]]]------->[1, 3, 5, 2, 2, 3, 4, 5]
function flat(arr) {
let res = []
for (let a of arr) {
if (Array.isArray(a)) {
res = res.concat(flat(a))
} else {
res.push(a)
}
}
return res
}
function flat2(arr) {
return arr.toString().split(',').map(e => parseInt(e))
}
function flat3(arr) {
while(arr.some( item => Array.isArray(item) )){
arr = [].concat(...arr);
}
return arr;
}
function flatten(arr) {
return arr.reduce((res,next) =>{
return res.concat(Array.isArray(next)? flatten(next) : next);
}, []);
}
- bind
Function.prototype.bind = function(context, ...args) {
let _this = this
return function() {
return _this.apply(context, args)
}
}
- curry
const curry = (fn) => {
let n = fn.length
return function curriedFn(...args) {
if (args.length < n) {
return function(...currArg) {
return curriedFn.apply(null, args.concat(currArg))
}
}
return fn.apply(null, args)
}
};
- Promise
function Promise(executor) {
this.status = 'pending'
this.successVal = undefined
this.errorReason = undefined
this.onFulfilledCallbacks = []
this.onRejectedCallbacks = []
let that = this
function resolve(val) {
if (that.status === 'pending') {
that.status = 'fulfilled'
that.successVal = val
that.onFulfilledCallbacks.forEach(fn => fn())
}
}
function reject(reason) {
if (that.status === 'pending') {
that.status = 'reject'
that.errorReason = reason
that.onRejectedCallbacks.forEach(fn => fn())
}
}
try {
executor(resolve, reject)
} catch(e) {
reject(e)
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (x === promise2) {
reject(new TypeError('...'))
}
let called
if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
try {
let then = x.then
if (typeof then === 'function') {
then.call(x, y => {
if (called) return
called = true
resolvePromise(promise2, y, resolve, reject)
}, err => {
if (called) return
called = true
reject(err)
})
} else {
resolve(x)
}
} catch(e) {
if (called) return
called = true
reject(e)
}
} else {
resolve(x)
}
}
Promise.prototype.then = function(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val
onRejected = typeof onRejected === 'function' ? onRejected : error => {throw error}
let that = this
let promise2 = new Promise(function(resolve, reject) {
if (that.status === 'fulfilled') {
let x = onFulfilled(that.successVal)
resolvePromise(promise2, x, resolve, reject)
}
if (that.status === 'rejected') {
let x = onRejected(that.errorReason)
resolvePromise(promise2, x, resolve, reject)
}
if (that.status === 'pending') {
that.onFulfilledCallbacks.push(() => {
let x = onFulfilled(that.successVal)
resolvePromise(promise2, x, resolve, reject)
})
that.onRejectedCallbacks.push(() => {
let x = onRejected(that.errorReason)
resolvePromise(promise2, x, resolve, reject)
})
}
})
return promise2
}