Generic swap function in TypeScript
10 A generic swap that respects array bounds
fairWrite a function taking an array of any type plus two positions, swapping the elements at those positions and returning the array. Refuse positions that are out of range.
Stuck? Three hints, smallest first
- 1. The signature starts
function swap<T>(items: T[], i: number, j: number). - 2. Under this course’s settings
items[i]isT | undefined, so a bounds check is not optional. - 3. Returning a new array rather than mutating the caller’s one is usually the kinder choice. Show both.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
function swap<T>(items: T[], i: number, j: number): T[] {
if (i < 0 || j < 0 || i >= items.length || j >= items.length) {
throw new RangeError(`swap: ${i} or ${j} is outside 0..${items.length - 1}`);
}
// A copy, so the caller's array is left alone.
const out = [...items];
// The bounds check above is what makes these two reads safe.
const a = out[i] as T;
const b = out[j] as T;
out[i] = b;
out[j] = a;
return out;
}
const plates = ['LAG-441-XA', 'ABJ-772-KM', 'ENU-318-PH'];
const swapped = swap(plates, 0, 2);
const numbers = swap([1, 2, 3, 4], 1, 3);
let refused = '';
try { swap(plates, 0, 9); } catch (err) { refused = (err as RangeError).message; }
console.log('original untouched:', plates);
console.log('swapped copy :', swapped);
console.log('numbers :', numbers);
console.log('refused :', refused);
test('ends were exchanged', swapped, ['ENU-318-PH', 'ABJ-772-KM', 'LAG-441-XA']);
test('the original was not mutated', plates[0], 'LAG-441-XA');
test('works for numbers too', numbers, [1, 4, 3, 2]);
test('out of range was refused', refused.includes('outside'), true);
test('swapping a position with itself is a no-op', swap([1, 2], 0, 0), [1, 2]);
Output
The two as T casts are the interesting part. With noUncheckedIndexedAccess on, out[i] is T | undefined even though the bounds check just proved otherwise, because TypeScript does not track that relationship. This is one of the few places an assertion is genuinely right: the check above it is the proof.