Maps each block of n
consecutive elements using the given function, fn
.
- Use
Array.prototype.slice()
to getarr
withn
elements removed from the left. - Use
Array.prototype.map()
andArray.prototype.slice()
to applyfn
to each block ofn
consecutive elements inarr
.
代码实现
const mapConsecutive = (arr, n, fn) =>
arr.slice(n - 1).map((v, i) => fn(arr.slice(i, i + n)));
mapConsecutive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, x => x.join('-'));
// ['1-2-3', '2-3-4', '3-4-5', '4-5-6', '5-6-7', '6-7-8', '7-8-9', '8-9-10'];
翻译自:https://www.30secondsofcode.org/js/s/map-consecutive-elements