示例输入:['1', '2'], ['a', 'b'], ['+', '-', 'x']
示例输出:["1a+", "1a-", "1ax", "1b+", "1b-", "1bx", "2a+", "2a-", "2ax", "2b+", "2b-", "2bx"]
代码:
// 中规中矩的思路,用 reduce 迭代每个 item
let Descartes = (...items) => items.reduce((acc, cur) => {
let ret = []
if (!acc.length) {
acc = cur
} else {
acc.forEach(i => {
cur.forEach(j => {
ret.push(i + j)
})
})
}
return ret
})
比较牛逼的代码:
// 已有的笛卡尔积结果 map 新元素的各项
let Descartes = (...items) => items.reduce((acc, cur) => (!acc.length) ? cur : acc.map(e => cur.map(u => e + u)).reduce((pre, e) => pre.concat(e), []), [])
判断一组数字是否连续,并将连续的部分以区间的形式展示
示例输入:[1, 2, 3, 4, 6, 8, 9, 10]
示例输出:["1-4", 6, "8-10"]
代码:
// 先聚合为连续区间的二维数组,再 map 展示之
let isContinuous = arr => arr.reduce((acc, cur, idx, arr) => idx === 0
? [ ...acc, [cur] ]
: arr[idx - 1] + 1 === arr[idx]
? acc.concat([ acc.pop().slice(0, 1).concat(cur) ])
: [ ...acc, [cur] ],
[]
)
.map(x => Array.isArray(x) ? x.join('-') : x)
示例输入:
var obj = [
{ id:3, parent: null },
{ id:1, parent: 2 },
{ id:2, parent: 3 },
]
示例输出:
{
id: 3,
parent: null,
child: {
id: 2,
parent: 3,
child: {
id: 1,
parent: 2
}
}
}
代码:
// 先根据 parent 的关系排个序,然后 reduce 遍历一遍生成结果
let target = null
const sortedArr = []
while (sortedArr.length < obj.length) {
const item = obj.find(x => x.parent === target)
target = item.id
sortedArr.unshift(item)
}
sortedArr.reduce((acc, cur) => (acc ? { ...cur, child: acc } : cur))