1
0

refactor random options init and merge

This commit is contained in:
2024-05-08 20:42:49 +02:00
parent a140245c05
commit 3af744c24d

View File

@@ -41,7 +41,7 @@ function mergeOptions<T>(first: RandomOptions<T> | undefined, second: RandomOpti
} }
function withDefaultOptions<T>(options: RandomOptions<T> | undefined): Required<RandomOptions<T>> { function withDefaultOptions<T>(options: RandomOptions<T> | undefined): Required<RandomOptions<T>> {
if (!options) { if (!options || options === defaultOptions) {
return defaultOptions; return defaultOptions;
} }
@@ -52,8 +52,8 @@ function withDefaultOptions<T>(options: RandomOptions<T> | undefined): Required<
}; };
} }
export function getRandomElement<T>(sequence: Iterable<T>, options?: RandomOptions<T>) { function _getRandomElement<T>(sequence: Iterable<T>, options: Required<RandomOptions<T>>) {
const { predicate, weight, random } = withDefaultOptions(options); const { predicate, weight, random } = options;
let result: T | undefined = undefined; let result: T | undefined = undefined;
let resultIndex = -1; let resultIndex = -1;
@@ -89,7 +89,7 @@ export function getRandomElement<T>(sequence: Iterable<T>, options?: RandomOptio
export class RandomPicker<T> { export class RandomPicker<T> {
readonly #elements: Iterable<T>; readonly #elements: Iterable<T>;
readonly #flags: BitArray; readonly #flags: BitArray;
readonly #options: RandomOptions<T>; readonly #options: Required<RandomOptions<T>>;
public constructor(elements: T[], options?: RandomOptions<T>) { public constructor(elements: T[], options?: RandomOptions<T>) {
this.#elements = elements; this.#elements = elements;
@@ -116,7 +116,7 @@ export class RandomPicker<T> {
} }
public next() { public next() {
const result = getRandomElement(this.#elements, this.#options); const result = _getRandomElement(this.#elements, this.#options);
if (result.index < 0) { if (result.index < 0) {
this.reset(); this.reset();