const log = console.warn
let reduce = function (reducer, initialValue) {
let list = this
let result = initialValue ?? list[0]
let len = list.length
for (let index = (initialValue !== undefined ? 0 : 1); index < len; index++) {
result = reducer(result, list[index])
}
return result
}
Array.prototype.reduce = reduce
// log([1, 2].reduce((tol, cur) => tol + cur, ''))
let str = "aaabbc,2,cabc";
str = str.split('').reduce((tol, cur) => {
if (tol[cur] === undefined) {
tol[cur] = 1
} else {
tol[cur]++
}
return tol
}, {})
// log(str)
arr = [1, [2, 3, [4, 5, 6]], 7];
let flatten = function (arr) {
return arr.reduce((tol, cur) => {
if (Array.isArray(cur)) {
return [...tol, ...flatten(cur)]
} else {
return [...tol, cur]
}
}, [])
}
// log(flatten(arr))
data = { b: { c: 4 }, d: [{ e: 5 }, { f: 6 }] }
let parse = function (obj, path) {
let arr = path.split('.')
return arr.reduce((tol, cur) => {
return tol[cur]
}, obj) || obj
}
// log(parse(data, 'd.1.f'))
console