WordGrid/ui/src/utils.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-08-24 03:23:58 +00:00
import {Letter} from "word_grid";
import {LocationType, PlayableLetterData} from "./elements";
2023-08-22 02:42:22 +00:00
export function addNTimes<T>(array: T[], toAdd: T, times: number) {
for (let i=0; i<times; i++) {
array.push(toAdd);
}
2023-08-24 03:23:58 +00:00
}
export function mergeTrays(existing: PlayableLetterData[], newer: (Letter | undefined)[]): PlayableLetterData[] {
let trayLength = Math.max(existing.length, newer.length);
// we may need to check against the existing tray to retain whatever user reorderings there are
const freeSpots = new Array<number | null>();
for (let i = 0; i<trayLength; i++) {
freeSpots.push(i);
}
existing.filter((x) => {
return x !== undefined && x !== null;
}).forEach((x) => {
if (x.location === LocationType.TRAY) {
freeSpots[x.index] = null;
}
});
const firstNotNull = (): number => {
for (let i of freeSpots) {
if (i !== null) {
freeSpots[i] = null;
return i;
}
}
return null;
}
return newer.map((ld, i) => {
if (ld !== undefined) {
if (existing[i] !== undefined && existing[i] !== null && existing[i].location === LocationType.TRAY) {
ld["index"] = existing[i].index;
} else {
ld["index"] = firstNotNull();
}
ld["location"] = LocationType.TRAY;
}
return ld as PlayableLetterData;
});
2023-08-22 02:42:22 +00:00
}