summaryrefslogtreecommitdiff
path: root/packages/sortug/src/utils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/sortug/src/utils.ts')
-rw-r--r--packages/sortug/src/utils.ts50
1 files changed, 35 insertions, 15 deletions
diff --git a/packages/sortug/src/utils.ts b/packages/sortug/src/utils.ts
index 687b8db..43fac8a 100644
--- a/packages/sortug/src/utils.ts
+++ b/packages/sortug/src/utils.ts
@@ -1,25 +1,45 @@
+export function cycleNext(current: number, max: number) {
+ if (current + 1 === max) return 0;
+ else return current + 1;
+}
+export function cyclePrev(current: number, max: number) {
+ if (current === 0) return max;
+ else return current - 1;
+}
+
export function randomFromArray<T>(a: Array<T>): T {
const l = a.length;
- const ind = Math.floor(Math.random() * l);
- if (ind === l) return a[ind - 1];
- else return a[ind];
+ if (l === 0) throw new Error("Empty array!");
+ const randomIdx = Math.floor(Math.random() * l);
+ const idx = randomIdx === l ? randomIdx - 1 : randomIdx;
+ const el = a[idx]!;
+ return el;
}
-export function randomFromArrayAcc<T>(a: Array<T>, s?: Set<T>): T {
- const st = s ? s : new Set(a);
- const l = a.length;
- const ind = Math.floor(Math.random() * l);
- const res = ind === l ? a[ind - 1] : a[ind];
- if (st.has(res)) return randomFromArrayAcc(a, st);
- else {
- st.add(res);
- // TODO have to return this too?
- return res;
- }
+export function randomFromArrayMany<T>(
+ a: Array<T>,
+ count: number,
+ canRepeat = false,
+): Array<T> {
+ if (canRepeat) return [...new Array(count)].map((s) => randomFromArray(a));
+ else return randomFromArrayNoRepeat(a, count);
+}
+export function randomFromArrayNoRepeat<T>(
+ a: Array<T>,
+ count: number,
+ acc?: Set<T>,
+): T[] {
+ const all = new Set(a);
+ const st = acc ? acc : new Set<T>();
+ if (all.size === st.size || st.size === count) return [...st];
+ const el = randomFromArray(a);
+ if (!st.has(el)) st.add(el);
+ return randomFromArrayNoRepeat(a, count, st);
}
+
export function notRandomFromArray<T>(data: string, a: Array<T>): T {
const l = a.length;
const ind = hashTextToNumber(data, l - 1);
- return a[ind];
+ return a[ind]!;
}
function hashTextToNumber(text: string, max: number): number {