promise.all 思路
promise.all =function (arr){
return new Promise((resolve,reject)=>{
if(Array.isArray((array)){
throw new TypeError()
}
var length = arr.length;
var resolveNum = 0;
var resolveResult = [];
for (let i=0;i<length;i++){
arr[i].then(data =>{
resolveNum++;
resolveResult.push(data)
if(resolveNum ==length){
return resolve(resolveResult)
}
}).catch(data =>{
return reject(data)
})
}
})
}
`Promise.retry = function(fn, times, delay) {
return new Promise(function(resolve, reject){
var error;
var attempt = function() {
if (times == 0) {
reject(error);
} else {
fn().then(resolve)
.catch(function(e){
times--;
error = e;
setTimeout(function(){attempt()}, delay);
});
}
};
attempt();
});
};``
实现数组flat,filter
// 数组扁平化
toString().split(',')
// 展平一级
function flat(arr){
var result = [];
for(var i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
result = result.concat(flat(arr[i]))
}else{
result.push(arr[i]);
}
}
return result;
}
/ 数组过滤
Array.prototype.myFilter = function(fn,context){
if(typeof fn != 'function'){
throw new TypeError(`${fn} is not a function`)
}
let arr = this;
let reuslt = []
for(var i = 0;i < arr.length; i++){
let temp= fn.call(context,arr[i],i,arr);
if(temp){
result.push(arr[i]);
}
}
return result
}
Array.prototype.myForeach = function(fn,context){
if(typeof fn != 'function'){
throw new TypeError(`${fn} is not a function`)
}
let arr = this;
for(var i = 0;i < arr.length; i++){
fn.call(context,arr[i],i,arr);
}
}
Array.prototype.myMap = function(fn,context){
if(typeof fn != 'function'){
throw new TypeError(`${fn} is not a function`)
}
let arr = this;
let reuslt = []
for(var i = 0;i < arr.length; i++){
result.push(fn.call(context,arr[i],i,arr));
}
return result;
}