You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
823 B
TypeScript

export const randomSelectNoRepeat = (
arr: string[] | any[],
count: number,
mapper?: (obj: any) => any
) => {
const length = arr.length;
let availableNum = 0;
let lottery = {} as any;
while (availableNum < count) {
let code = Math.random() * length;
if (code === length) code -= 1;
code = Math.floor(code);
if (lottery[code]) continue;
lottery[code] = mapper
? mapper(arr[code])
: typeof arr[code] === "string"
? arr[code]
: {
...arr[code],
};
availableNum++;
}
return Object.values(lottery) as any[];
};
export const randomSelect = (arr: any[], noReturn = 0) => {
if (Math.random() < noReturn) return undefined;
const length = arr.length;
let code = Math.random() * length;
if (code === length) code -= 1;
return arr[code];
};