DEV Community

loading...

Discussion on: Daily Challenge #278 - Find all non-consecutive numbers

Collapse
aminnairi profile image
Amin

TypeScript

interface IndexValue {
    index: number;
    value: number;
}

/**
 * Return all numbers with their index & value that are not following the others.
 *
 * @example
 * getNonConsecutives([1, 2, 3]);
 * getNonConsecutives([1, 2, 4]);
 */
function getNonConsecutives(numbers: Readonly<Array<number>>): Array<IndexValue> {
    const nonConsecutives: Array<IndexValue> = [];
    const count: number = numbers.length;

    for (let index: number = 1; index < count; index++) {
        const current: number = numbers[index];
        const previous: number = numbers[index - 1];
        const expectedCurrent: number = previous + 1;

        if (expectedCurrent === current) {
            continue;
        }

        nonConsecutives.push({index, value: current});
    }

    return nonConsecutives;
}