🏂 @e280/stz
我每天的打字员
环境不可知的零依赖工具和公用事业。 以 https://e280.org/ (中文(简体) )
🍴 器具
⏳ aync/fns 图像
📣 子键
🧹 家务
🎲 兰德
✅ 好吧,错误,结果
🧬 十六进制及更多
npm install @e280/stz
import {got} from "@e280/stz"
餐具
- 已经 ——如果值为无效或未定义,则抛出错误.
const value = got(nullableValue) - 需求 ——返回地图值,如果缺少,则丢出错误.
const value = need(map, "my_key") - 保证 ——获得-或创建地图值.
const value = guarantee(map, "my_key", () => 123) - 设置 ——同时设置许多地图条目.
setEntries(map, [["my_key1", 123], ["my_key2", 234]]) - 双图 - 就像普通地图,但是..
keyOf让它双侧.const labels = new Bimap<number, string>() labels.set(1, "alpha") labels.set(2, "bravo") // it's a normal map. labels.get(1) // "alpha" // but it also has this 'keyOf' method. labels.keyOf("alpha") // 1 - 何时 - 做一些事情 当事情是真实的.
when(map.size > 10, () => console.log(map)) - 给定 当事物不是无效的,也不是没有定义时,做点什么.
given(map.get(id), item => console.log(item)) - 计数 - 绝对数字.
for (const i of count(4)) console.log(i) - 网格 ——斜列和行.
for (const [x, y] of grid(2, 4)) console.log(x, y) - 数组限制 ——以倒放最老来限制数组长度.
const trimmed = arraylimit(["a", "b", "c", "d"], 2) // ["c", "d"] // returns new array if trimming happens, // otherwise returns the same array unchanged. - 烟斗 ——通过数fns运行数据.
const result = pipe(rawData) .to(parse) .to(validate) .to(normalize) .done() - 缩写 ——在对象条目上映射.
const alpha = {alpha: 1, bravo: 2, charlie: 3}obmap(alpha, n => n * 10) // {alpha: 10, bravo: 20, charlie: 30} - 过滤器 ——过滤对象条目.
obfilter(alpha, n => n > 1) // {bravo: 2, charlie: 3} - 深冻 ——递归对象. 冻结对象树.
const freezie = deepFreeze({alpha: 123}) freezie.alpha = 5 // throws error - 深等号 ——检查两个对象树是否有相同的原始值.
deepEqual({alpha: 123}, {alpha: 123}) // true - 是快乐 ——用合适的类型警卫检查物品的身份.
isHappy(0) // true if not null nor undefined. isSad(undefined) // true if null or undefined. isBoolean(true) // true isNumber(123) // true isString("hello") // true isBigint(123n) // true isArray([]) // true isObject({}) // true isFn(() => {}) // true isSymbol(Symbol()) // true - 秒数 ——持续时间和时间戳.
持续时间 :
日期后的时间戳。 现在 :seconds(1) // 1000 minutes(1) hours(1) days(1)
日期前的时间戳。 现在:futureSeconds(1) futureMinutes(1) futureHours(1) futureDays(1)pastSeconds(1) pastMinutes(1) pastHours(1) pastDays(1)
*
- 睡觉 ——归还一个以后会解决的承诺.
await nap(1000) // sleep for one second. - 周期 ——再三调用fn回放.
const stop = cycle(async() => { console.log("hello!", Date.now()) await nap(1000) // once per second. })stop() // cancel the cycle. - 并行 ——等待一批出名的承诺.
const {user, settings} = await concurrent({ user: myFetchUser(), settings: myFetchSettings(), }) - 推迟 ——一个承诺,你可以解决/从外部拒绝.
const ready = defer<string>() ready.resolve("hello") await ready // "hello"ready.reject(new Error("rejected")) - 收集 ——能同步到阵列.
const entries = await collect(kv.entries()) - 一次 - 只执行一次fn.
const init = once(() => connect()) init() init() // doesn't initialize twice. - 队列 使async fn呼叫一次工作.
const save = queue(async(myData: string) => myWriteData(myData)) await Promise.all([save("a"), save("b"), save("c")]) // actually executes sequentially. - 车道 ——制造一台能执行任意aync fn的一时一机.
const mutex = lane() await Promise.all([ mutex(async() => writeMyData("a")), mutex(async() => writeMyData("b")), mutex(async() => writeMyData("c")), ]) // executes jobs sequentially. - 截止日期 ——增加过期超时.
const connection = await deadline(10_000, connect) // throw DeadlineError after 10s unless connect resolves. // connect can be a promise or an async fn. - 弹跳 - 一段时间后调用dudupe.
const search = debounce(250, async(s: string) => query(s)) search("l") search("lo") await search("lol") // last one actually runs. - 微弹跳 - 调试这个微工作.
let count = 0 const run = microbounce(() => count++) const done = run() run() run() await done count // 1
{\fn黑体\fs22\bord1\shad0\3ahbe\4ah00\fscx67\fscy66\2chffffff\3ch808080}你是谁
- 子键 ——创建订阅者fn.
const on = subby<[number]>()const off = on(x => console.log(x))on.publish(123) // 123off() // stop listening. - 阴道 ——创建出版社fn.
const publish = pubby<[number]>()const off = publish.on(x => console.log(x))publish(123) // 123off() // stop listening. - {\fn黑体\fs22\bord1\shad0\3ahbe\4ah00\fscx67\fscy66\2chffffff\3ch808080}"subby"和"pubby" 都给你一个好包.
// limited 'on' and 'publish' fns without whole toolkit. const {on, publish} = subby()const {publishAsync} = subby() await publishAsync(123) // awaits every listener (they can be async).const [value] = await on.next() // wait for the next publish. // value is 123on.set.size // direct access to the set of listeners.
家居管理
- 页:1 ——事件听众.
import {ev} from "@e280/stz" const off = ev(window, { keydown: event => console.log(event), keyup: event => console.log(event), }) off() // removes both listeners - 处置者 ——清理资源.
更多的处置者诡计.const dispose = disposer() dispose.schedule(() => console.log("dispose 1")) dispose.schedule(() => console.log("dispose 2")) dispose.schedule(cycle(myGameloop)) dispose.schedule(ev(window, {keydown: myKeydown})) dispose() // dispose everything backwards // *dispose ev* // *dispose cycle* // "dispose 2" // "dispose 1"const myThing = dispose.own(new MyThing(), t => t.dispose()) // create a thing and schedule its disposeconst myThing = dispose.disposable(new MyThing()) // return and schedule a Disposable thingconst {dispose, schedule, own, disposable} = disposer() schedule(cycle(myGameloop)) const myThing = disposable(new MyThing) dispose()
兰德
- 兰德 ——随机效用.
const rand = new Rand(Math.random)const rand = new Rand(mulberry(123)) // seeded pseudo-random number generatorrand.u32() // get a random unsigned 32-bit integer. // 3286174905 rand.roll(0.25) // 25% chance of true. // false rand.range(10, 20) // random float between two numbers. // 14.8591238 rand.integerRange(1, 6) // inclusive integer range. // 4 rand.index(7) // given array length, pick an array index. // 5 rand.pick(["a", "b", "c"]) // pick your poison. // "c" rand.select(2, ["a", "b", "c"]) // pick multiple. // ["a", "c"] rand.yoink(["a", "b", "c"]) // remove and return one array element. // "a" rand.extract(2, ["a", "b", "c"]) // yoink multiple. // ["b", "c"] rand.shuffle(["a", "b", "c"]) // random-sort array in-place. // ["c", "a", "b"] - 浆果 ——种子假随机数生成器.
const random = mulberry(123) random() // 0.7872516233474016 random() // 0.1785435655619949 - 兰德32 ——密码随机无符号32位整数.
rand32() // 3948271056 - hash32 键盘 ——将 en混合为32位整数(快,非晶体).
hash32(123, "hello", 234, "world") // 1012994381
好吧,错误,结果
- 还好 —— 说
Ok<Value>表明成功.ok(123) // {ok: true, value: 123} - 错误 —— 说
Err<E>- 表示失败.err("fail") // {ok: false, error: "fail"} Result<Value, E>表明某种东西可能成功或失败.let result: Result<number, "fail"> = ok(123) result = err("fail")- 获取 Ok/ Get Err - 获得价值,或
undefined。 。 。 .getOk(ok(123)) // 123 getOk(err("fail")) // undefined getErr(ok(123)) // undefined getErr(err("fail")) // "fail" - 获取 Ok/ gotErr - 得到价值,或掷出.
gotOk(ok(123)) // 123 gotOk(err("fail")) // throws Error("fail") gotErr(ok(123)) // throws error gotErr(err("fail")) // "fail"
十六岁及以上
- 六进制 ——编码/解码为十六进制数据.
hex(bytes) // encode Uint8Array bytes to string. hex.toBytes(string) // decode string to bytes. hex.toInteger(string) // decode string as integer. hex.fromInteger(n) // encode integer as a string. hex.random(32) // generate random encoded string, 32 bytes.// we have more than just hex. hex(bytes) // string base2(bytes) // string base36(bytes) // string base58(bytes) // string base62(bytes) // string base64(bytes) // string base64url(bytes) // string - txt 时 ——文本数据.
txt(bytes) // convert utf8 bytes to string. txt.toBytes("hello") // convert string to utf8 bytes. - 字节 - 公用事业.
bytes.eq(bytesA, bytesB) // true if they're equal. bytes.random(32) // get 32 crypto-random bytes. - 数据查看 ——制作一个匹配打入数组的偏移的 DataView .
dataView(new Uint8Array([0, 1, 2, 3, 4]))