refactor
This commit is contained in:
@@ -1,19 +1,11 @@
|
||||
import { BitArray } from "./bitarray.js";
|
||||
import { asArray } from "./utils.js";
|
||||
|
||||
export interface ElementPredicate<T = any> {
|
||||
(index: number, obj: T): boolean;
|
||||
}
|
||||
export type ElementPredicate<T = any> = (index: number, obj: T) => boolean;
|
||||
export type ElementWeight<T = any> = (index: number, obj: T) => number;
|
||||
export type RandomGenerator = () => number;
|
||||
|
||||
export interface ElementWeight<T = any> {
|
||||
(index: number, obj: T): number;
|
||||
}
|
||||
|
||||
export interface RandomGenerator {
|
||||
(): number;
|
||||
}
|
||||
|
||||
export interface RandomOptions<T> {
|
||||
export interface RandomOptions<T = any> {
|
||||
predicate?: ElementPredicate<T>;
|
||||
weight?: ElementWeight<T>;
|
||||
random?: RandomGenerator;
|
||||
@@ -23,7 +15,7 @@ export const alwaysTrue: ElementPredicate = () => true;
|
||||
export const weightOfOne: ElementWeight = () => 1.0;
|
||||
export const mathRandom: RandomGenerator = () => Math.random();
|
||||
|
||||
const defaultOptions = Object.freeze<Required<RandomOptions<any>>>({
|
||||
const defaultOptions = Object.freeze<Required<RandomOptions>>({
|
||||
predicate: alwaysTrue,
|
||||
weight: weightOfOne,
|
||||
random: mathRandom
|
||||
@@ -50,7 +42,7 @@ function mergeOptions<T>(first: RandomOptions<T> | undefined, second: RandomOpti
|
||||
|
||||
function withDefaultOptions<T>(options: RandomOptions<T> | undefined): Required<RandomOptions<T>> {
|
||||
if (!options) {
|
||||
return { ...defaultOptions };
|
||||
return defaultOptions;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -98,7 +90,7 @@ export class RandomPicker<T> {
|
||||
public constructor(elements: T[], options?: RandomOptions<T>) {
|
||||
this.#elements = elements;
|
||||
this.#flags = new BitArray(elements.length);
|
||||
this.#options = withDefaultOptions(mergeOptions({ predicate: (i, o) => this.#flags.get(i) }, options));
|
||||
this.#options = withDefaultOptions(mergeOptions({ predicate: i => this.#flags.get(i) }, options));
|
||||
|
||||
this.reset();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user