console.log(
"for [22, 31, 32, 33, 42, 52] and [-1 , +1]",
"\nexpect: '[[31,32,33]]' ?",
JSON.stringify([22, 31, 32, 33, 42, 52].reduce(
collectItemSequencesByConditions, {
getPredecessor: currentItem => currentItem - 1,
getSuccessor: currentItem => currentItem + 1,
list: [],
}
).list) === '[[31,32,33]]'
);
console.log(
[22, 31, 32, 33, 42, 52].reduce(
collectItemSequencesByConditions, {
getPredecessor: currentItem => currentItem - 1,
getSuccessor: currentItem => currentItem + 1,
list: [],
}
).list
);
console.log(
"for [22, 31, 32, 33, 42, 52] and [-10 , +10]",
"\nexpect: '[[42,52]]' ?",
JSON.stringify([22, 31, 32, 33, 42, 52].reduce(
collectItemSequencesByConditions, {
getPredecessor: currentItem => currentItem - 10,
getSuccessor: currentItem => currentItem + 10,
list: [],
}
).list) === '[[42,52]]'
);
console.log(
[22, 31, 32, 33, 42, 52].reduce(
collectItemSequencesByConditions, {
getPredecessor: currentItem => currentItem - 10,
getSuccessor: currentItem => currentItem + 10,
list: [],
}
).list
);
console.log(
"for [21, 22, 32, 33, 42, 52] and [-10 , +10]",
"\nexpect: '[[22,32],[42,52]]' ?",
JSON.stringify([21, 22, 32, 33, 42, 52].reduce(
collectItemSequencesByConditions, {
getPredecessor: currentItem => currentItem - 10,
getSuccessor: currentItem => currentItem + 10,
list: [],
}
).list) === '[[22,32],[42,52]]'
);
console.log(
[21, 22, 32, 33, 42, 52].reduce(
collectItemSequencesByConditions, {
getPredecessor: currentItem => currentItem - 10,
getSuccessor: currentItem => currentItem + 10,
list: [],
}
).list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
function collectItemSequencesByConditions(collector, item, idx, arr) {
const { getPredecessor, getSuccessor, list } = collector;
if (getPredecessor(item) === arr[idx - 1]) {
// push item into the most recent sequence list.
list[list.length - 1].push(item);
} else if (getSuccessor(item) === arr[idx + 1]) {
// create a new sequence list with its 1st item.
list.push([ item ]);
}
return collector;
}
</script>