map
Array.prototype.toMap = function (fn, thisValue) {
if (Object.prototype.toString.call(fn) !== '[object Function]') {
throw new Error('fn is not a function')
}
const arr = []
const curArr = this
for (let i = 0; i < curArr.length; i++) {
arr.push(fn.call(thisValue, curArr[i], i, curArr))
}
return arr
}
filter
Array.prototype.toFilter = function (fn, thisValue) {
if (Object.prototype.toString.call(fn) !== '[object Function]') {
throw new Error('fn is not a function')
}
const arr = []
const curArr = this
for (let i = 0; i < curArr.length; i++) {
const returnValue = fn.call(thisValue, curArr[i], i, curArr)
if (returnValue) {
arr.push(curArr[i])
}
}
return arr
}
reudce
Array.prototype.toReduce = function (fn, initValue) {
const curArr = this
let firstValue
let j = 0
if (initValue) {
firstValue = initValue
} else {
firstValue = curArr[0]
j = 1
}
for(let i = j; i < curArr.length; i++) {
firstValue = fn(firstValue, curArr[i], i, curArr)
}
return firstValue
}
reduce 实现 map
Array.prototype.reduceToMap = function (fn, context) {
const curArr = this;
function reudce(total, cur, index, curArr) {
total.push(fn.call(context, cur, index, curArr))
return total
}
const reuslt = curArr.reduce(reudce, [])
return reuslt
}
console.log('color: #00e600', [1,2,3,4].reduceToMap(ele => ele*2));