flotilla/src/lib/util.ts

32 lines
1 KiB
TypeScript
Raw Normal View History

2025-01-28 21:04:37 +00:00
import {hexToBytes, bytesToHex} from "@noble/hashes/utils"
import * as nip19 from "nostr-tools/nip19"
2025-02-05 23:15:50 +00:00
import {range, DAY} from "@welshman/lib"
2025-01-28 21:04:37 +00:00
2024-11-18 23:41:58 +00:00
export const displayList = <T>(xs: T[], conj = "and", n = 6, locale = "en-US") => {
const stringItems = xs.map(String)
if (xs.length > n + 2) {
const formattedList = new Intl.ListFormat(locale, {style: "long", type: "unit"}).format(
stringItems.slice(0, n),
)
return `${formattedList}, ${conj} ${xs.length - n} others`
}
return new Intl.ListFormat(locale, {style: "long", type: "conjunction"}).format(stringItems)
}
2025-01-28 21:04:37 +00:00
export const nsecEncode = (secret: string) => nip19.nsecEncode(hexToBytes(secret))
export const nsecDecode = (nsec: string) => {
const {type, data} = nip19.decode(nsec)
if (type !== "nsec") throw new Error(`Invalid nsec: ${nsec}`)
return bytesToHex(data)
}
2025-02-05 18:47:56 +00:00
2025-02-05 23:15:50 +00:00
export const day = (seconds: number) => Math.floor(seconds / DAY).toString()
2025-02-05 18:47:56 +00:00
2025-02-05 23:15:50 +00:00
export const daysBetween = (start: number, end: number) => [...range(start, end, DAY)].map(day)