构建一个序列号数组
Building an array of sequential numbers
我有一个传入数组:
[{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]
所以我需要将传入的数组转换为另一个数组
[0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
我试过这样走:
const convertRangeData = (rangeData) =>
{
const convertedRangeData =
rangeData.reduce( (acc, item) =>
{
const { step, count } = item;
const prev = acc[acc.length - 1];
return [...acc, ...[...Array(count)].fill(step).map((i, idx) => i * (idx + 1) + prev)];
},[0] )
return convertedRangeData;
}
但我有
[0, 0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
使用 Array.from()
创建一个包含范围内值的数组。然后迭代范围数组。
要创建连续范围,请减少 ranges
的数组。创建范围时,从累加器 (acc
) 中取出最后一个数字,并将其用作起始值。
const range = ({ step, count }, start = 0) =>
Array.from({ length: count }, (_, i) => (i + 1) * step + start)
const continuousRange = arr =>
arr.reduce((acc, r) => acc.concat(range(r, acc[acc.length -1])), [])
const ranges = [{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]
const result = continuousRange(ranges)
console.log(result)
我的方式
const ranges = [{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]
const convertRangeData = rangeData => rangeData.reduce((acc, {step,count}) =>
{
let prev = acc[acc.length - 1] || 0
while(count--)
acc.push(prev+=step)
return acc
},[])
console.log( convertRangeData(ranges) )
我有一个传入数组:
[{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]
所以我需要将传入的数组转换为另一个数组
[0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
我试过这样走:
const convertRangeData = (rangeData) =>
{
const convertedRangeData =
rangeData.reduce( (acc, item) =>
{
const { step, count } = item;
const prev = acc[acc.length - 1];
return [...acc, ...[...Array(count)].fill(step).map((i, idx) => i * (idx + 1) + prev)];
},[0] )
return convertedRangeData;
}
但我有
[0, 0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
使用 Array.from()
创建一个包含范围内值的数组。然后迭代范围数组。
要创建连续范围,请减少 ranges
的数组。创建范围时,从累加器 (acc
) 中取出最后一个数字,并将其用作起始值。
const range = ({ step, count }, start = 0) =>
Array.from({ length: count }, (_, i) => (i + 1) * step + start)
const continuousRange = arr =>
arr.reduce((acc, r) => acc.concat(range(r, acc[acc.length -1])), [])
const ranges = [{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]
const result = continuousRange(ranges)
console.log(result)
我的方式
const ranges = [{step: 0, count: 1}, {step: 1, count: 5}, {step: 5, count: 5}]
const convertRangeData = rangeData => rangeData.reduce((acc, {step,count}) =>
{
let prev = acc[acc.length - 1] || 0
while(count--)
acc.push(prev+=step)
return acc
},[])
console.log( convertRangeData(ranges) )