Files
covergen/frontend/src/lib/randomlabel.ts
Jur van den Berg cb8400eea3
Some checks reported errors
continuous-integration/drone/push Build was killed
Cleanup frontend
2022-04-19 22:07:43 +02:00

29 lines
830 B
TypeScript

import { readonly, Ref, ref } from 'vue';
/**
* Random labels as a library function.
* Will return a random label from the given options.
* Calling the `update` function that is returned will pick a new label.
* @param options
*/
export function randomLabel(options: string[]) {
const label = ref<string>();
const randomLabel = () => {
let newLabel;
do {
newLabel = options[Math.floor(Math.random() * options.length)];
} while (newLabel === label.value);
return newLabel;
};
label.value = randomLabel();
return {
// This type refinement is proper as the `undefined` value can never happen from this point onwards
label: readonly(label as Ref<string>),
// Updates the returned `label` with a new randomly chosen one
update() {
label.value = randomLabel();
},
};
}