Skip to content

Instantly share code, notes, and snippets.

@Tsugami
Last active December 1, 2021 17:50
Show Gist options
  • Save Tsugami/1a8a119b448babb7c4e8f2b3bafde0ca to your computer and use it in GitHub Desktop.
Save Tsugami/1a8a119b448babb7c4e8f2b3bafde0ca to your computer and use it in GitHub Desktop.
export enum BulkTypes {
SEQUENCE = 'SEQUENCE',
NOT_SEQUENCE = 'NOT_SEQUENCE',
}
interface NotSequenceValue {
numbers: number[];
type: BulkTypes.NOT_SEQUENCE;
}
interface SequenceValue {
numbers: [number, number];
type: BulkTypes.SEQUENCE;
}
type Value = SequenceValue | NotSequenceValue;
export const createBulk = <A, V>(
data: A[],
getNumber: (data: A) => number,
getValue: (data: Value) => V,
): V[] => {
const values: V[] = [];
let i = 0;
while (i < data.length) {
const value = getNumber(data[i]);
const nextValue = getNumber(data[i + 1]);
if (nextValue === value + 1) {
let count = 1;
while (
data[i + count + 1] &&
getNumber(data[i + count + 1]) === getNumber(data[i + count]) + 1
) {
count++;
}
values.push(
getValue({
numbers: [value, getNumber(data[i + count])],
type: BulkTypes.SEQUENCE,
}),
);
i += count + 1;
} else {
let count = 1;
const diffNumbers: number[] = [value];
while (
data[i + count + 1] &&
getNumber(data[i + count + 1]) !== getNumber(data[i + count]) + 1
) {
diffNumbers.push(getNumber(data[i + count]));
count++;
}
values.push(
getValue({
numbers: diffNumbers,
type: BulkTypes.NOT_SEQUENCE,
}),
);
i += count;
}
}
return values;
};
const numbers = [1, 2, 3, 4, 6, 7, 8, 56, 66, 67, 34, 356, 4657, 745, 746, 747];
console.log(createBulk(numbers, (v) => v);
// output:
// [{
// "numbers": [
// 1,
// 4
// ],
// "type": "BULK"
// }, {
// "numbers": [
// 6,
// 8
// ],
// "type": "BULK"
// }, {
// "numbers": [
// 56,
// 66,
// 67,
// 34,
// 356,
// 4657
// ],
// "type": "SEQUENCE"
// }, {
// "numbers": [
// 745,
// 747
// ],
// "type": "BULK"
// }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment