Random 随机
draw(随机取一个)
从列表中获取随机项
基本用法
绘制,比如“从一副牌中抽一张牌”,用于从数组中获取一个随机项目。
ts
import { draw } from "radash";
const fish = ["marlin", "bass", "trout"];
draw(fish); // => a random fish
random(随机数)
生成一个随机数
基本用法
生成在范围内的数字。此函数适用于实用工具,而非加密。
ts
import { random } from "radash";
random(0, 100); // => a random number between 0 and 100
shuffle(洗牌)
随机打乱数组
基本用法
给定一个项目数组,返回一个随机顺序的新数组。
ts
import { shuffle } from "radash";
const fish = [
{
name: "Marlin",
weight: 105,
source: "ocean",
},
{
name: "Salmon",
weight: 22,
source: "river",
},
{
name: "Salmon",
weight: 22,
source: "river",
},
];
shuffle(fish);
请注意,这不是一个顶尖性能优化的函数。此函数经过简化优化,最适合用作实用工具。如果性能是您的优先考虑因素,请使用一个随机性和/或洗牌库。
uid(唯一标识符)
生成一个唯一标识符
基本用法
生成带有可选特殊字符的唯一字符串。
ts
import { uid } from "radash";
uid(7); // => UaOKdlW
uid(20, "*"); // => dyJdbC*NsEgcnGjTHS
请注意,此函数针对简单性和易用性进行了优化 -- 而非性能或安全性。如果您需要创建通用唯一或密码随机字符串,请使用专门用于此目的的软件包。
series(系列)
创建一个有序序列对象
基本用法
有时您可能有一个枚举或联合类型,可能是一个状态,它具有固有顺序,并且您需要按顺序处理值。 series
函数接受许多值并返回一个对象,让您可以对这些值进行有序逻辑处理。
ts
import { series } from "radash";
type Weekday = "monday" | "tuesday" | "wednesday" | "thursday" | "friday";
const weekdays = series<Weekday>([
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
]);
weekdays.min("tuesday", "thursday"); // => 'tuesday'
weekdays.max("wednesday", "monday"); // => 'wednesday'
weekdays.next("wednesday"); // => 'thursday'
weekdays.previous("tuesday"); // => 'monday'
weekdays.first(); // => 'monday'
weekdays.last(); // => 'friday'
weekdays.next("friday"); // => null
weekdays.next("friday", weekdays.first()); // => 'monday'
weekdays.spin("monday", 3); // => 'thursday'
复杂数据类型
在处理对象时,您需要为 series
提供第二个参数,即一个函数,用于将非原始值转换为可进行相等性检查的标识。
ts
import { series } from "radash";
type Weekday = {
day: "monday" | "tuesday" | "wednesday" | "thursday" | "friday";
};
const weekdays = series<Weekday>(
[
{ day: "monday" },
{ day: "tuesday" },
{ day: "wednesday" },
{ day: "thursday" },
{ day: "friday" },
],
(w) => w.day
);
weekdays.next({ day: "wednesday" }); // => { day: 'thursday' }
weekdays.previous({ day: "tuesday" }); // => { day: 'monday' }