Skip to content

Instantly share code, notes, and snippets.

@elycruz
Created October 3, 2020 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elycruz/f33a426e2c2ed715c6f3ffbb0c105b01 to your computer and use it in GitHub Desktop.
Save elycruz/f33a426e2c2ed715c6f3ffbb0c105b01 to your computer and use it in GitHub Desktop.
Utilities for fetching an item's index in an array being treated as a table.
export const
getRowIndex = (itemIdx: number, itemsPerRow: number): number =>
Math.round((itemIdx - (itemIdx % itemsPerRow)) / itemsPerRow),
getColumnIndex = (itemIdx: number, itemsPerRow: number): number =>
itemIdx % itemsPerRow
;
import {getColumnIndex, getRowIndex} from "./array-as-table-utils";
type Index = number;
type ItemsPerRow = number;
describe ('#getRowIndex', () => {
(<[Index, ItemsPerRow, Index][]>[
[0, 5, 0],
[24, 5, 4],
[1, 5, 0],
[23, 5, 4],
[12, 5, 2],
]).forEach(([itemIdx, itemsPerRow, expectedRowIndex]) => {
it(`getRowIndex(${itemIdx}, ${itemsPerRow}) === ${expectedRowIndex}`, function () {
const rslt = getRowIndex(itemIdx, itemsPerRow);
expect(rslt).toEqual(expectedRowIndex);
});
});
});
describe('#getColumnIndex', () => {
(<[Index, ItemsPerRow, Index][]>[
[0, 5, 0],
[24, 5, 4],
[1, 5, 1],
[23, 5, 3],
[12, 5, 2],
]).forEach(([itemIdx, itemsPerRow, expectedRowIndex]) => {
it(`getColumnIndex(${itemIdx}, ${itemsPerRow}) === ${expectedRowIndex}`, function () {
const rslt = getColumnIndex(itemIdx, itemsPerRow);
expect(rslt).toEqual(expectedRowIndex);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment