Skip to content

Commit e5e581a

Browse files
committed
chore: Support x% in sample
1 parent 0378013 commit e5e581a

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

src/ps/handlers/autores.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export function autoResHandler(message: PSMessage) {
3636
if (message.type === 'chat') {
3737
if (['lunarnewyear'].includes(message.target.id)) {
3838
const HONSE_REGEX = /(\w*)horse(\w*)/i;
39-
if (HONSE_REGEX.test(message.content) && sample(20) === 0) {
39+
if (HONSE_REGEX.test(message.content) && sample('5%')) {
4040
const honse = message.content.match(HONSE_REGEX)!;
4141
const honseText = honse[1] || honse[2] ? `*${honse[1]}HONSE${honse[2]}` : '*honse';
4242
message.reply(honseText);

src/utils/random.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,16 @@ export function useRNG(rng?: RNGSource): () => number {
2222
return JSRNG;
2323
}
2424

25+
type Percent = `${number}%`;
2526
function sample(input: null, rng?: RNGSource): number;
2627
function sample(input: number, rng?: RNGSource): number;
2728
function sample(input: [number, number], rng?: RNGSource): number;
2829
function sample(input: Record<string, number>, rng?: RNGSource): string;
29-
function sample(input: null | number | [number, number] | Record<string, number>, rng?: RNGSource): number | string {
30+
function sample(input: Percent, rng?: RNGSource): boolean;
31+
function sample(
32+
input: null | number | [number, number] | Record<string, number> | Percent,
33+
rng?: RNGSource
34+
): number | string | boolean {
3035
const RNG = useRNG(rng);
3136
if (!input) return RNG();
3237
if (typeof input === 'number') return Math.floor(input * RNG());
@@ -42,6 +47,11 @@ function sample(input: null | number | [number, number] | Record<string, number>
4247
const lookup = totalWeight * RNG();
4348
return thresholds.find(([, weight]) => lookup < weight)![0];
4449
}
50+
if (typeof input === 'string' && input.endsWith('%')) {
51+
const percentage = parseFloat(input.slice(0, -1));
52+
if (isNaN(percentage)) throw new Error(`Invalid percentage ${input}`);
53+
return RNG() * 100 < percentage;
54+
}
4555
return RNG();
4656
}
4757

0 commit comments

Comments
 (0)