@choksheak/ts-utils 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/asNumber.cjs +39 -0
- package/asNumber.d.mts +6 -0
- package/asNumber.d.ts +6 -0
- package/asNumber.min.cjs +2 -0
- package/asNumber.min.cjs.map +1 -0
- package/asNumber.min.mjs +2 -0
- package/asNumber.min.mjs.map +1 -0
- package/asNumber.mjs +14 -0
- package/average.cjs +15 -7
- package/average.min.cjs +1 -1
- package/average.min.cjs.map +1 -1
- package/average.min.mjs +1 -1
- package/average.min.mjs.map +1 -1
- package/average.mjs +15 -7
- package/isPromise.cjs +40 -0
- package/isPromise.d.mts +19 -0
- package/isPromise.d.ts +19 -0
- package/isPromise.min.cjs +2 -0
- package/isPromise.min.cjs.map +1 -0
- package/isPromise.min.mjs +2 -0
- package/isPromise.min.mjs.map +1 -0
- package/isPromise.mjs +14 -0
- package/kvStore.cjs +5 -4
- package/kvStore.min.cjs +1 -1
- package/kvStore.min.cjs.map +1 -1
- package/kvStore.min.mjs +1 -1
- package/kvStore.min.mjs.map +1 -1
- package/kvStore.mjs +5 -4
- package/mean.cjs +53 -0
- package/mean.d.mts +7 -0
- package/mean.d.ts +7 -0
- package/mean.min.cjs +2 -0
- package/mean.min.cjs.map +1 -0
- package/mean.min.mjs +2 -0
- package/mean.min.mjs.map +1 -0
- package/mean.mjs +26 -0
- package/median.cjs +56 -0
- package/median.d.mts +7 -0
- package/median.d.ts +7 -0
- package/median.min.cjs +2 -0
- package/median.min.cjs.map +1 -0
- package/median.min.mjs +2 -0
- package/median.min.mjs.map +1 -0
- package/median.mjs +29 -0
- package/package.json +65 -1
- package/round.cjs +4 -1
- package/round.d.mts +2 -1
- package/round.d.ts +2 -1
- package/round.min.cjs +1 -1
- package/round.min.cjs.map +1 -1
- package/round.min.mjs +1 -1
- package/round.min.mjs.map +1 -1
- package/round.mjs +4 -1
- package/storageAdapter.d.mts +5 -2
- package/storageAdapter.d.ts +5 -2
- package/storageAdapter.min.cjs +1 -1
- package/storageAdapter.min.cjs.map +1 -1
- package/sum.cjs +17 -7
- package/sum.d.mts +3 -3
- package/sum.d.ts +3 -3
- package/sum.min.cjs +1 -1
- package/sum.min.cjs.map +1 -1
- package/sum.min.mjs +1 -1
- package/sum.min.mjs.map +1 -1
- package/sum.mjs +15 -7
package/kvStore.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/duration.ts","../src/kvStore.ts"],"sourcesContent":["/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n HOURS_PER_DAY,\n MINUTES_PER_HOUR,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * Convenience function to return a duration given an ms or Duration.\n */\nexport function durationOrMsToMs(duration: number | Duration): number {\n return typeof duration === \"number\" ? duration : durationToMs(duration);\n}\n\n/**\n * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * @param style Defaults to 'short'\n */\nexport function formatDuration(duration: Duration, style?: DurationStyle) {\n style = style ?? \"short\";\n const stylePlural = getDurationStyleForPlural(style);\n\n const space = getValueAndUnitSeparator(style);\n\n const a: string[] = [];\n\n for (const unit of DURATION_TYPE_SEQUENCE) {\n const value = duration[unit];\n if (value === undefined) continue;\n\n const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];\n const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];\n a.push(value + space + suffix);\n }\n\n const separator = getDurationTypeSeparator(style);\n return a.join(separator);\n}\n\n/**\n * Convert a millisecond duration into a human-readable duration string.\n *\n * @param options.durationTypeForZero - Defaults to 'milliseconds'\n * @param options.style - Defaults to 'short'\n */\nexport function readableDuration(\n ms: number,\n options?: { durationTypeForZero?: DurationType; style?: DurationStyle },\n): string {\n const duration = msToDuration(ms, options?.durationTypeForZero);\n\n return formatDuration(duration, options?.style);\n}\n\n/** A shortened duration string useful for logging timings. */\nexport function elapsed(ms: number): string {\n // Use long format for 1 minute or over.\n if (ms > MS_PER_MINUTE) {\n return readableDuration(ms);\n }\n\n // Use seconds format for over 100ms.\n if (ms > 100) {\n return `${(ms / 1000).toFixed(3)}s`;\n }\n\n // Use milliseconds format.\n return ms + \"ms\";\n}\n","/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. Extremely simple interface to use indexed DBs.\n * 2. Auto-expirations with GC frees you from worrying about data clean-up.\n * 3. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage, but with\n * async interface functions as required by indexed DB.\n *\n * Why not use the indexed DB directly?\n * It will require you to write a lot of code to reinvent the wheel.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\nimport {\n FullStorageAdapter,\n StorageAdapter,\n StoredObject,\n} from \"./storageAdapter\";\nimport { MS_PER_DAY } from \"./timeConstants\";\n\n/** Global defaults can be updated directly. */\nexport const KvStoreConfig = {\n /**\n * Name of the DB in the indexed DB.\n * Updating the DB name will cause all old entries to be gone.\n */\n dbName: \"KVStore\",\n\n /**\n * Version of the DB schema. Most likely you will never want to change this.\n * Updating the version will cause all old entries to be gone.\n */\n dbVersion: 1,\n\n /**\n * Name of the store within the indexed DB. Each DB can have multiple stores.\n * In practice, it doesn't matter what you name this to be.\n */\n storeName: \"kvStore\",\n\n /** 30 days in ms. */\n expiryMs: MS_PER_DAY * 30,\n\n /** Do GC once per day. */\n gcIntervalMs: MS_PER_DAY,\n};\n\nexport type KvStoreConfig = typeof KvStoreConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureKvStore(config: Partial<KvStoreConfig>) {\n Object.assign(KvStoreConfig, config);\n}\n\n/** Type to represent a full object with metadata stored in the store. */\nexport type KvStoredObject<T> = StoredObject<T> & {\n // The key is required by the ObjectStore.\n key: string;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: KvStoredObject<T>,\n): KvStoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n typeof obj.key !== \"string\" ||\n obj.value === undefined ||\n typeof obj.storedMs !== \"number\" ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\n/**\n * You can create multiple KvStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\n// Using `any` because the store could store any type of data for each key,\n// but the caller can specify a more specific type when calling each of the\n// methods.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class KvStore implements FullStorageAdapter<any> {\n /** We'll init the DB only on first use. */\n private db: IDBDatabase | undefined;\n\n /** Local storage key name for the last GC completed timestamp. */\n public readonly gcMsStorageKey: string;\n\n public readonly dbVersion: number;\n public readonly storeName: string;\n public readonly defaultExpiryMs: number;\n public readonly gcIntervalMs: number;\n\n public constructor(\n public readonly dbName: string,\n options?: {\n dbVersion?: number;\n storeName?: string;\n defaultExpiryMs?: number | Duration;\n gcIntervalMs?: number | Duration;\n },\n ) {\n this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;\n this.storeName = options?.storeName ?? KvStoreConfig.storeName;\n\n this.defaultExpiryMs = options?.defaultExpiryMs\n ? durationOrMsToMs(options.defaultExpiryMs)\n : KvStoreConfig.expiryMs;\n\n this.gcIntervalMs = options?.gcIntervalMs\n ? durationOrMsToMs(options.gcIntervalMs)\n : KvStoreConfig.gcIntervalMs;\n\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(this.storeName, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(\n db.transaction(this.storeName, mode),\n reject,\n );\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(this.storeName);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n /** Set a value in the store. */\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: KvStoredObject<T> = {\n key,\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n /** Mainly used to get the expiration timestamp of an object. */\n public async getStoredObject<T>(\n key: string,\n ): Promise<KvStoredObject<T> | undefined> {\n const stored = await this.transact<KvStoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get<T>(key: string): Promise<T | undefined> {\n const obj = await this.getStoredObject<T>(key);\n\n return obj?.value;\n }\n\n /** Generic way to iterate through all entries. */\n public async forEach<T>(\n callback: (\n key: string,\n value: T,\n expiryMs: number,\n storedMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj !== undefined) {\n await callback(\n String(cursor.key),\n obj.value as T,\n obj.expiryMs,\n obj.storedMs,\n );\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /**\n * Returns the number of items in the store. Note that getting the size\n * requires iterating through the entire store because the items could expire\n * at any time, and hence the size is a dynamic number.\n */\n public async size(): Promise<number> {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n /** Remove all items from the store. */\n public async clear(): Promise<void> {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /**\n * Returns all items as map of key to value, mainly used for debugging dumps.\n * The type T is applied to all values, even though they might not be of type\n * T (in the case when you store different data types in the same store).\n */\n public async asMap<T>(): Promise<Map<string, StoredObject<T>>> {\n const map = new Map<string, StoredObject<T>>();\n await this.forEach((key, value, expiryMs, storedMs) => {\n map.set(key, { value: value as T, expiryMs, storedMs });\n });\n return map;\n }\n\n /** Returns the ms timestamp for the last GC (garbage collection). */\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n /** Set the ms timestamp for the last GC (garbage collection). */\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due, else do nothing. */\n public async gc(): Promise<void> {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + this.gcIntervalMs) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /**\n * Perform garbage collection immediately without checking whether we are\n * due for the next GC or not.\n */\n public async gcNow(): Promise<void> {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expiryMs: number) => {\n if (value === undefined || Date.now() >= expiryMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Returns `this` casted into a StorageAdapter<T>. */\n public asStorageAdapter<T>(): StorageAdapter<T> {\n return this as StorageAdapter<T>;\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KvStore(KvStoreConfig.dbName);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nexport class KvStoreItem<T> {\n public readonly defaultExpiryMs: number;\n\n public constructor(\n public readonly key: string,\n defaultExpiryMs: number | Duration = KvStoreConfig.expiryMs,\n public readonly store = kvStore,\n ) {\n this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);\n }\n\n /** Set a value in the store. */\n public async set(\n value: T,\n expiryDeltaMs: number | undefined = this.defaultExpiryMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs, storedMs } =\n * await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<KvStoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n /** Delete this key from the store. */\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/** Create a KV store item with a key and a default expiration. */\nexport function kvStoreItem<T>(\n key: string,\n expiryMs?: number | Duration,\n store = kvStore,\n): KvStoreItem<T> {\n expiryMs = expiryMs && durationOrMsToMs(expiryMs);\n\n return new KvStoreItem<T>(key, expiryMs, store);\n}\n"],"mappings":"AA0LO,SAASA,EAAaC,EAA4B,CACvD,IAAMC,GAAUD,EAAS,MAAQ,GAAK,MAChCE,GAAWF,EAAS,OAAS,GAAK,KAClCG,GAAUH,EAAS,SAAW,GAAK,IACnCI,GAAUJ,EAAS,SAAW,GAAK,IACnCK,EAAOL,EAAS,cAAgB,EAEtC,OAAOC,EAASC,EAAUC,EAASC,EAASC,CAC9C,CAKO,SAASC,EAAiB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ACWlB,EAChBmB,EAAqCtC,EAAc,SACnCuC,EAAQH,EACxB,CAHgB,SAAAjB,EAEA,WAAAoB,EAEhB,KAAK,gBAAkBD,GAAmB1B,EAAiB0B,CAAe,CAC5E,CARgB,gBAWhB,MAAa,IACXlB,EACAC,EAAoC,KAAK,gBAC1B,CACf,MAAM,KAAK,MAAM,IAAI,KAAK,IAAKD,EAAOC,CAAa,CACrD,CAQA,MAAa,iBAA0D,CACrE,OAAO,MAAM,KAAK,MAAM,gBAAgB,KAAK,GAAG,CAClD,CAGA,MAAa,KAA8B,CACzC,OAAO,MAAM,KAAK,MAAM,IAAI,KAAK,GAAG,CACtC,CAGA,MAAa,QAAwB,CACnC,MAAM,KAAK,MAAM,OAAO,KAAK,GAAG,CAClC,CACF,EAGO,SAASmB,EACdrB,EACAW,EACAS,EAAQH,EACQ,CAChB,OAAAN,EAAWA,GAAYlB,EAAiBkB,CAAQ,EAEzC,IAAIO,EAAelB,EAAKW,EAAUS,CAAK,CAChD","names":["durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","KvStoreConfig","configureKvStore","config","validateStoredObject","obj","withOnError","request","reject","event","KvStore","dbName","options","durationOrMsToMs","resolve","db","mode","callback","transaction","objectStore","key","value","expiryDeltaMs","nowMs","k","stored","e","cursor","count","keys","map","expiryMs","storedMs","lastGcMsStr","ms","lastGcMs","keysToDelete","kvStore","KvStoreItem","defaultExpiryMs","store","kvStoreItem"]}
|
|
1
|
+
{"version":3,"sources":["../src/duration.ts","../src/kvStore.ts"],"sourcesContent":["/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n HOURS_PER_DAY,\n MINUTES_PER_HOUR,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * Convenience function to return a duration given an ms or Duration.\n */\nexport function durationOrMsToMs(duration: number | Duration): number {\n return typeof duration === \"number\" ? duration : durationToMs(duration);\n}\n\n/**\n * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * @param style Defaults to 'short'\n */\nexport function formatDuration(duration: Duration, style?: DurationStyle) {\n style = style ?? \"short\";\n const stylePlural = getDurationStyleForPlural(style);\n\n const space = getValueAndUnitSeparator(style);\n\n const a: string[] = [];\n\n for (const unit of DURATION_TYPE_SEQUENCE) {\n const value = duration[unit];\n if (value === undefined) continue;\n\n const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];\n const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];\n a.push(value + space + suffix);\n }\n\n const separator = getDurationTypeSeparator(style);\n return a.join(separator);\n}\n\n/**\n * Convert a millisecond duration into a human-readable duration string.\n *\n * @param options.durationTypeForZero - Defaults to 'milliseconds'\n * @param options.style - Defaults to 'short'\n */\nexport function readableDuration(\n ms: number,\n options?: { durationTypeForZero?: DurationType; style?: DurationStyle },\n): string {\n const duration = msToDuration(ms, options?.durationTypeForZero);\n\n return formatDuration(duration, options?.style);\n}\n\n/** A shortened duration string useful for logging timings. */\nexport function elapsed(ms: number): string {\n // Use long format for 1 minute or over.\n if (ms > MS_PER_MINUTE) {\n return readableDuration(ms);\n }\n\n // Use seconds format for over 100ms.\n if (ms > 100) {\n return `${(ms / 1000).toFixed(3)}s`;\n }\n\n // Use milliseconds format.\n return ms + \"ms\";\n}\n","/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. Extremely simple interface to use indexed DBs.\n * 2. Auto-expirations with GC frees you from worrying about data clean-up.\n * 3. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage, but with\n * async interface functions as required by indexed DB.\n *\n * Why not use the indexed DB directly?\n * It will require you to write a lot of code to reinvent the wheel.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\nimport {\n FullStorageAdapter,\n StorageAdapter,\n StoredObject,\n} from \"./storageAdapter\";\nimport { MS_PER_DAY } from \"./timeConstants\";\n\n/** Global defaults can be updated directly. */\nexport const KvStoreConfig = {\n /**\n * Name of the DB in the indexed DB.\n * Updating the DB name will cause all old entries to be gone.\n */\n dbName: \"KVStore\",\n\n /**\n * Version of the DB schema. Most likely you will never want to change this.\n * Updating the version will cause all old entries to be gone.\n */\n dbVersion: 1,\n\n /**\n * Name of the store within the indexed DB. Each DB can have multiple stores.\n * In practice, it doesn't matter what you name this to be.\n */\n storeName: \"kvStore\",\n\n /** 30 days in ms. */\n expiryMs: MS_PER_DAY * 30,\n\n /** Do GC once per day. */\n gcIntervalMs: MS_PER_DAY,\n};\n\nexport type KvStoreConfig = typeof KvStoreConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureKvStore(config: Partial<KvStoreConfig>) {\n Object.assign(KvStoreConfig, config);\n}\n\n/** Type to represent a full object with metadata stored in the store. */\nexport type KvStoredObject<T> = StoredObject<T> & {\n // The key is required by the ObjectStore.\n key: string;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: KvStoredObject<T>,\n): KvStoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n typeof obj.key !== \"string\" ||\n obj.value === undefined ||\n typeof obj.storedMs !== \"number\" ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\n/**\n * You can create multiple KvStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\n// Using `any` because the store could store any type of data for each key,\n// but the caller can specify a more specific type when calling each of the\n// methods.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class KvStore implements FullStorageAdapter<any> {\n /** We'll init the DB only on first use. */\n private db: IDBDatabase | undefined;\n\n /** Local storage key name for the last GC completed timestamp. */\n public readonly gcMsStorageKey: string;\n\n public readonly dbVersion: number;\n public readonly storeName: string;\n public readonly defaultExpiryMs: number;\n public readonly gcIntervalMs: number;\n\n public constructor(\n public readonly dbName: string,\n options?: {\n dbVersion?: number;\n storeName?: string;\n defaultExpiryMs?: number | Duration;\n gcIntervalMs?: number | Duration;\n },\n ) {\n this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;\n this.storeName = options?.storeName ?? KvStoreConfig.storeName;\n\n this.defaultExpiryMs = options?.defaultExpiryMs\n ? durationOrMsToMs(options.defaultExpiryMs)\n : KvStoreConfig.expiryMs;\n\n this.gcIntervalMs = options?.gcIntervalMs\n ? durationOrMsToMs(options.gcIntervalMs)\n : KvStoreConfig.gcIntervalMs;\n\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(this.storeName, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(\n db.transaction(this.storeName, mode),\n reject,\n );\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(this.storeName);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n /** Set a value in the store. */\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: KvStoredObject<T> = {\n key,\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n /** Mainly used to get the expiration timestamp of an object. */\n public async getStoredObject<T>(\n key: string,\n ): Promise<KvStoredObject<T> | undefined> {\n const stored = await this.transact<KvStoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get<T>(key: string): Promise<T | undefined> {\n const obj = await this.getStoredObject<T>(key);\n\n return obj?.value;\n }\n\n /** Generic way to iterate through all entries. */\n public async forEach<T>(\n callback: (\n key: string,\n value: T,\n expiryMs: number,\n storedMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj !== undefined) {\n await callback(\n String(cursor.key),\n obj.value as T,\n obj.expiryMs,\n obj.storedMs,\n );\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /**\n * Returns the number of items in the store. Note that getting the size\n * requires iterating through the entire store because the items could expire\n * at any time, and hence the size is a dynamic number.\n */\n public async size(): Promise<number> {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n /** Remove all items from the store. */\n public async clear(): Promise<void> {\n await this.transact<void>(\"readwrite\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.clear(), reject);\n\n request.onsuccess = () => {\n resolve();\n };\n });\n }\n\n /**\n * Returns all items as map of key to value, mainly used for debugging dumps.\n * The type T is applied to all values, even though they might not be of type\n * T (in the case when you store different data types in the same store).\n */\n public async asMap<T>(): Promise<Map<string, StoredObject<T>>> {\n const map = new Map<string, StoredObject<T>>();\n await this.forEach((key, value, expiryMs, storedMs) => {\n map.set(key, { value: value as T, expiryMs, storedMs });\n });\n return map;\n }\n\n /** Returns the ms timestamp for the last GC (garbage collection). */\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n /** Set the ms timestamp for the last GC (garbage collection). */\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due, else do nothing. */\n public async gc(): Promise<void> {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + this.gcIntervalMs) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /**\n * Perform garbage collection immediately without checking whether we are\n * due for the next GC or not.\n */\n public async gcNow(): Promise<void> {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expiryMs: number) => {\n if (value === undefined || Date.now() >= expiryMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Returns `this` casted into a StorageAdapter<T>. */\n public asStorageAdapter<T>(): StorageAdapter<T> {\n return this as StorageAdapter<T>;\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KvStore(KvStoreConfig.dbName);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nexport class KvStoreItem<T> {\n public readonly defaultExpiryMs: number;\n\n public constructor(\n public readonly key: string,\n defaultExpiryMs: number | Duration = KvStoreConfig.expiryMs,\n public readonly store = kvStore,\n ) {\n this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);\n }\n\n /** Set a value in the store. */\n public async set(\n value: T,\n expiryDeltaMs: number | undefined = this.defaultExpiryMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs, storedMs } =\n * await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<KvStoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n /** Delete this key from the store. */\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/** Create a KV store item with a key and a default expiration. */\nexport function kvStoreItem<T>(\n key: string,\n expiryMs?: number | Duration,\n store = kvStore,\n): KvStoreItem<T> {\n expiryMs = expiryMs && durationOrMsToMs(expiryMs);\n\n return new KvStoreItem<T>(key, expiryMs, store);\n}\n"],"mappings":"AA0LO,SAASA,EAAaC,EAA4B,CACvD,IAAMC,GAAUD,EAAS,MAAQ,GAAK,MAChCE,GAAWF,EAAS,OAAS,GAAK,KAClCG,GAAUH,EAAS,SAAW,GAAK,IACnCI,GAAUJ,EAAS,SAAW,GAAK,IACnCK,EAAOL,EAAS,cAAgB,EAEtC,OAAOC,EAASC,EAAUC,EAASC,EAASC,CAC9C,CAKO,SAASC,EAAiBN,EAAqC,CACpE,OAAO,OAAOA,GAAa,SAAWA,EAAWD,EAAaC,CAAQ,CACxE,CChLO,IAAMO,EAAgB,CAK3B,OAAQ,UAMR,UAAW,EAMX,UAAW,UAGX,SAAU,MAAa,GAGvB,aAAc,KAChB,EAKO,SAASC,EAAiBC,EAAgC,CAC/D,OAAO,OAAOF,EAAeE,CAAM,CACrC,CAYA,SAASC,EACPC,EAC+B,CAC/B,GACE,GAACA,GACD,OAAOA,GAAQ,UACf,OAAOA,EAAI,KAAQ,UACnBA,EAAI,QAAU,QACd,OAAOA,EAAI,UAAa,UACxB,OAAOA,EAAI,UAAa,UACxB,KAAK,IAAI,GAAKA,EAAI,UAKpB,OAAOA,CACT,CAGA,SAASC,EACPC,EACAC,EACG,CACH,OAAAD,EAAQ,QAAWE,GAAU,CAC3BD,EAAOC,CAAK,CACd,EAEOF,CACT,CAUO,IAAMG,EAAN,KAAiD,CA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EAAWA,GAAYjB,EAAiBiB,CAAQ,EAEzC,IAAIO,EAAejB,EAAKU,EAAUS,CAAK,CAChD","names":["durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","KvStoreConfig","configureKvStore","config","validateStoredObject","obj","withOnError","request","reject","event","KvStore","dbName","options","durationOrMsToMs","resolve","db","mode","callback","transaction","objectStore","key","value","expiryDeltaMs","nowMs","k","stored","e","cursor","count","map","expiryMs","storedMs","lastGcMsStr","ms","lastGcMs","keysToDelete","kvStore","KvStoreItem","defaultExpiryMs","store","kvStoreItem"]}
|
package/kvStore.mjs
CHANGED
|
@@ -220,11 +220,12 @@ var KvStore = class {
|
|
|
220
220
|
}
|
|
221
221
|
/** Remove all items from the store. */
|
|
222
222
|
async clear() {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
223
|
+
await this.transact("readwrite", (objectStore, resolve, reject) => {
|
|
224
|
+
const request = withOnError(objectStore.clear(), reject);
|
|
225
|
+
request.onsuccess = () => {
|
|
226
|
+
resolve();
|
|
227
|
+
};
|
|
226
228
|
});
|
|
227
|
-
await this.delete(keys);
|
|
228
229
|
}
|
|
229
230
|
/**
|
|
230
231
|
* Returns all items as map of key to value, mainly used for debugging dumps.
|
package/mean.cjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/mean.ts
|
|
21
|
+
var mean_exports = {};
|
|
22
|
+
__export(mean_exports, {
|
|
23
|
+
mean: () => mean
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(mean_exports);
|
|
26
|
+
|
|
27
|
+
// src/asNumber.ts
|
|
28
|
+
function asNumber(u) {
|
|
29
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
30
|
+
return u;
|
|
31
|
+
}
|
|
32
|
+
const n = Number(u);
|
|
33
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
34
|
+
return n;
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/sum.ts
|
|
40
|
+
function sum(numbers) {
|
|
41
|
+
return numbers.reduce((accumulated, current) => {
|
|
42
|
+
return accumulated + asNumber(current);
|
|
43
|
+
}, 0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/mean.ts
|
|
47
|
+
function mean(numbers) {
|
|
48
|
+
return numbers.length > 0 ? sum(numbers) / numbers.length : 0;
|
|
49
|
+
}
|
|
50
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
51
|
+
0 && (module.exports = {
|
|
52
|
+
mean
|
|
53
|
+
});
|
package/mean.d.mts
ADDED
package/mean.d.ts
ADDED
package/mean.min.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var u=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var c=(n,r)=>{for(var e in r)u(n,e,{get:r[e],enumerable:!0})},s=(n,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of b(r))!p.call(n,t)&&t!==e&&u(n,t,{get:()=>r[t],enumerable:!(o=f(r,t))||o.enumerable});return n};var k=n=>s(u({},"__esModule",{value:!0}),n);var a={};c(a,{mean:()=>w});module.exports=k(a);function m(n){if(typeof n=="number"&&isFinite(n))return n;let r=Number(n);return typeof r=="number"&&isFinite(r)?r:0}function i(n){return n.reduce((r,e)=>r+m(e),0)}function w(n){return n.length>0?i(n)/n.length:0}0&&(module.exports={mean});
|
|
2
|
+
//# sourceMappingURL=mean.min.cjs.map
|
package/mean.min.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mean.ts","../src/asNumber.ts","../src/sum.ts"],"sourcesContent":["import { sum } from \"./sum\";\n\n/**\n * Compute the mean (average) of all the numbers in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function mean(numbers: unknown[]): number {\n return numbers.length > 0 ? sum(numbers) / numbers.length : 0;\n}\n","/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n","import { asNumber } from \"./asNumber\";\n\n/**\n * Add all the numbers together in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function sum(numbers: unknown[]): number {\n return numbers.reduce((accumulated: number, current: unknown) => {\n return accumulated + asNumber(current);\n }, 0);\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,IAAA,eAAAC,EAAAH,GCGO,SAASI,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAMC,EAAI,OAAOD,CAAC,EAClB,OAAI,OAAOC,GAAM,UAAY,SAASA,CAAC,EAC9BA,EAKF,CACT,CCZO,SAASC,EAAIC,EAA4B,CAC9C,OAAOA,EAAQ,OAAO,CAACC,EAAqBC,IACnCD,EAAcE,EAASD,CAAO,EACpC,CAAC,CACN,CFJO,SAASE,EAAKC,EAA4B,CAC/C,OAAOA,EAAQ,OAAS,EAAIC,EAAID,CAAO,EAAIA,EAAQ,OAAS,CAC9D","names":["mean_exports","__export","mean","__toCommonJS","asNumber","u","n","sum","numbers","accumulated","current","asNumber","mean","numbers","sum"]}
|
package/mean.min.mjs
ADDED
package/mean.min.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/asNumber.ts","../src/sum.ts","../src/mean.ts"],"sourcesContent":["/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n","import { asNumber } from \"./asNumber\";\n\n/**\n * Add all the numbers together in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function sum(numbers: unknown[]): number {\n return numbers.reduce((accumulated: number, current: unknown) => {\n return accumulated + asNumber(current);\n }, 0);\n}\n","import { sum } from \"./sum\";\n\n/**\n * Compute the mean (average) of all the numbers in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function mean(numbers: unknown[]): number {\n return numbers.length > 0 ? sum(numbers) / numbers.length : 0;\n}\n"],"mappings":"AAGO,SAASA,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAMC,EAAI,OAAOD,CAAC,EAClB,OAAI,OAAOC,GAAM,UAAY,SAASA,CAAC,EAC9BA,EAKF,CACT,CCZO,SAASC,EAAIC,EAA4B,CAC9C,OAAOA,EAAQ,OAAO,CAACC,EAAqBC,IACnCD,EAAcE,EAASD,CAAO,EACpC,CAAC,CACN,CCJO,SAASE,EAAKC,EAA4B,CAC/C,OAAOA,EAAQ,OAAS,EAAIC,EAAID,CAAO,EAAIA,EAAQ,OAAS,CAC9D","names":["asNumber","u","n","sum","numbers","accumulated","current","asNumber","mean","numbers","sum"]}
|
package/mean.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// src/asNumber.ts
|
|
2
|
+
function asNumber(u) {
|
|
3
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
4
|
+
return u;
|
|
5
|
+
}
|
|
6
|
+
const n = Number(u);
|
|
7
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
8
|
+
return n;
|
|
9
|
+
}
|
|
10
|
+
return 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/sum.ts
|
|
14
|
+
function sum(numbers) {
|
|
15
|
+
return numbers.reduce((accumulated, current) => {
|
|
16
|
+
return accumulated + asNumber(current);
|
|
17
|
+
}, 0);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/mean.ts
|
|
21
|
+
function mean(numbers) {
|
|
22
|
+
return numbers.length > 0 ? sum(numbers) / numbers.length : 0;
|
|
23
|
+
}
|
|
24
|
+
export {
|
|
25
|
+
mean
|
|
26
|
+
};
|
package/median.cjs
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/median.ts
|
|
21
|
+
var median_exports = {};
|
|
22
|
+
__export(median_exports, {
|
|
23
|
+
median: () => median
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(median_exports);
|
|
26
|
+
|
|
27
|
+
// src/asNumber.ts
|
|
28
|
+
function asNumber(u) {
|
|
29
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
30
|
+
return u;
|
|
31
|
+
}
|
|
32
|
+
const n = Number(u);
|
|
33
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
34
|
+
return n;
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/median.ts
|
|
40
|
+
function median(numbers) {
|
|
41
|
+
if (numbers.length === 0) {
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
const sorted = numbers.map(asNumber).slice().sort();
|
|
45
|
+
const middleIndex = Math.floor(sorted.length / 2);
|
|
46
|
+
if (sorted.length % 2 === 1) {
|
|
47
|
+
return sorted[middleIndex];
|
|
48
|
+
}
|
|
49
|
+
const value1 = sorted[middleIndex - 1];
|
|
50
|
+
const value2 = sorted[middleIndex];
|
|
51
|
+
return (value1 + value2) / 2;
|
|
52
|
+
}
|
|
53
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
54
|
+
0 && (module.exports = {
|
|
55
|
+
median
|
|
56
|
+
});
|
package/median.d.mts
ADDED
package/median.d.ts
ADDED
package/median.min.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var i=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var c=(e,n)=>{for(var t in n)i(e,t,{get:n[t],enumerable:!0})},l=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of s(n))!f.call(e,r)&&r!==t&&i(e,r,{get:()=>n[r],enumerable:!(o=m(n,r))||o.enumerable});return e};var a=e=>l(i({},"__esModule",{value:!0}),e);var p={};c(p,{median:()=>b});module.exports=a(p);function u(e){if(typeof e=="number"&&isFinite(e))return e;let n=Number(e);return typeof n=="number"&&isFinite(n)?n:0}function b(e){if(e.length===0)return 0;let n=e.map(u).slice().sort(),t=Math.floor(n.length/2);if(n.length%2===1)return n[t];let o=n[t-1],r=n[t];return(o+r)/2}0&&(module.exports={median});
|
|
2
|
+
//# sourceMappingURL=median.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/median.ts","../src/asNumber.ts"],"sourcesContent":["import { asNumber } from \"./asNumber\";\n\n/**\n * Compute the median (middle number) of all the numbers in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function median(numbers: unknown[]): number {\n if (numbers.length === 0) {\n return 0;\n }\n\n // Create a copy with slice() to avoid mutating the original array.\n const sorted = numbers.map(asNumber).slice().sort();\n\n const middleIndex = Math.floor(sorted.length / 2);\n\n // Is odd length -> return middle number.\n if (sorted.length % 2 === 1) {\n return sorted[middleIndex];\n }\n\n // Is even length -> return mean of middle 2 numbers.\n const value1 = sorted[middleIndex - 1];\n const value2 = sorted[middleIndex];\n return (value1 + value2) / 2;\n}\n","/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,IAAA,eAAAC,EAAAH,GCGO,SAASI,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAM,EAAI,OAAOA,CAAC,EAClB,OAAI,OAAO,GAAM,UAAY,SAAS,CAAC,EAC9B,EAKF,CACT,CDZO,SAASC,EAAOC,EAA4B,CACjD,GAAIA,EAAQ,SAAW,EACrB,MAAO,GAIT,IAAMC,EAASD,EAAQ,IAAIE,CAAQ,EAAE,MAAM,EAAE,KAAK,EAE5CC,EAAc,KAAK,MAAMF,EAAO,OAAS,CAAC,EAGhD,GAAIA,EAAO,OAAS,IAAM,EACxB,OAAOA,EAAOE,CAAW,EAI3B,IAAMC,EAASH,EAAOE,EAAc,CAAC,EAC/BE,EAASJ,EAAOE,CAAW,EACjC,OAAQC,EAASC,GAAU,CAC7B","names":["median_exports","__export","median","__toCommonJS","asNumber","u","median","numbers","sorted","asNumber","middleIndex","value1","value2"]}
|
package/median.min.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function r(e){if(typeof e=="number"&&isFinite(e))return e;let n=Number(e);return typeof n=="number"&&isFinite(n)?n:0}function s(e){if(e.length===0)return 0;let n=e.map(r).slice().sort(),t=Math.floor(n.length/2);if(n.length%2===1)return n[t];let o=n[t-1],i=n[t];return(o+i)/2}export{s as median};
|
|
2
|
+
//# sourceMappingURL=median.min.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/asNumber.ts","../src/median.ts"],"sourcesContent":["/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n","import { asNumber } from \"./asNumber\";\n\n/**\n * Compute the median (middle number) of all the numbers in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function median(numbers: unknown[]): number {\n if (numbers.length === 0) {\n return 0;\n }\n\n // Create a copy with slice() to avoid mutating the original array.\n const sorted = numbers.map(asNumber).slice().sort();\n\n const middleIndex = Math.floor(sorted.length / 2);\n\n // Is odd length -> return middle number.\n if (sorted.length % 2 === 1) {\n return sorted[middleIndex];\n }\n\n // Is even length -> return mean of middle 2 numbers.\n const value1 = sorted[middleIndex - 1];\n const value2 = sorted[middleIndex];\n return (value1 + value2) / 2;\n}\n"],"mappings":"AAGO,SAASA,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAM,EAAI,OAAOA,CAAC,EAClB,OAAI,OAAO,GAAM,UAAY,SAAS,CAAC,EAC9B,EAKF,CACT,CCZO,SAASC,EAAOC,EAA4B,CACjD,GAAIA,EAAQ,SAAW,EACrB,MAAO,GAIT,IAAMC,EAASD,EAAQ,IAAIE,CAAQ,EAAE,MAAM,EAAE,KAAK,EAE5CC,EAAc,KAAK,MAAMF,EAAO,OAAS,CAAC,EAGhD,GAAIA,EAAO,OAAS,IAAM,EACxB,OAAOA,EAAOE,CAAW,EAI3B,IAAMC,EAASH,EAAOE,EAAc,CAAC,EAC/BE,EAASJ,EAAOE,CAAW,EACjC,OAAQC,EAASC,GAAU,CAC7B","names":["asNumber","u","median","numbers","sorted","asNumber","middleIndex","value1","value2"]}
|
package/median.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// src/asNumber.ts
|
|
2
|
+
function asNumber(u) {
|
|
3
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
4
|
+
return u;
|
|
5
|
+
}
|
|
6
|
+
const n = Number(u);
|
|
7
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
8
|
+
return n;
|
|
9
|
+
}
|
|
10
|
+
return 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/median.ts
|
|
14
|
+
function median(numbers) {
|
|
15
|
+
if (numbers.length === 0) {
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
const sorted = numbers.map(asNumber).slice().sort();
|
|
19
|
+
const middleIndex = Math.floor(sorted.length / 2);
|
|
20
|
+
if (sorted.length % 2 === 1) {
|
|
21
|
+
return sorted[middleIndex];
|
|
22
|
+
}
|
|
23
|
+
const value1 = sorted[middleIndex - 1];
|
|
24
|
+
const value2 = sorted[middleIndex];
|
|
25
|
+
return (value1 + value2) / 2;
|
|
26
|
+
}
|
|
27
|
+
export {
|
|
28
|
+
median
|
|
29
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@choksheak/ts-utils",
|
|
3
3
|
"license": "The Unlicense",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.3",
|
|
5
5
|
"description": "Random Typescript utilities with support for full tree-shaking",
|
|
6
6
|
"private": false,
|
|
7
7
|
"scripts": {
|
|
@@ -98,6 +98,19 @@
|
|
|
98
98
|
"default": "./arrayBuffer.cjs"
|
|
99
99
|
}
|
|
100
100
|
},
|
|
101
|
+
"./asNumber": {
|
|
102
|
+
"types": "./asNumber.d.ts",
|
|
103
|
+
"import": {
|
|
104
|
+
"production": "./asNumber.min.mjs",
|
|
105
|
+
"development": "./asNumber.mjs",
|
|
106
|
+
"default": "./asNumber.mjs"
|
|
107
|
+
},
|
|
108
|
+
"require": {
|
|
109
|
+
"production": "./asNumber.min.cjs",
|
|
110
|
+
"development": "./asNumber.cjs",
|
|
111
|
+
"default": "./asNumber.cjs"
|
|
112
|
+
}
|
|
113
|
+
},
|
|
101
114
|
"./assert": {
|
|
102
115
|
"types": "./assert.d.ts",
|
|
103
116
|
"import": {
|
|
@@ -176,6 +189,19 @@
|
|
|
176
189
|
"default": "./isEmpty.cjs"
|
|
177
190
|
}
|
|
178
191
|
},
|
|
192
|
+
"./isPromise": {
|
|
193
|
+
"types": "./isPromise.d.ts",
|
|
194
|
+
"import": {
|
|
195
|
+
"production": "./isPromise.min.mjs",
|
|
196
|
+
"development": "./isPromise.mjs",
|
|
197
|
+
"default": "./isPromise.mjs"
|
|
198
|
+
},
|
|
199
|
+
"require": {
|
|
200
|
+
"production": "./isPromise.min.cjs",
|
|
201
|
+
"development": "./isPromise.cjs",
|
|
202
|
+
"default": "./isPromise.cjs"
|
|
203
|
+
}
|
|
204
|
+
},
|
|
179
205
|
"./iterators": {
|
|
180
206
|
"types": "./iterators.d.ts",
|
|
181
207
|
"import": {
|
|
@@ -228,6 +254,32 @@
|
|
|
228
254
|
"default": "./logging.cjs"
|
|
229
255
|
}
|
|
230
256
|
},
|
|
257
|
+
"./mean": {
|
|
258
|
+
"types": "./mean.d.ts",
|
|
259
|
+
"import": {
|
|
260
|
+
"production": "./mean.min.mjs",
|
|
261
|
+
"development": "./mean.mjs",
|
|
262
|
+
"default": "./mean.mjs"
|
|
263
|
+
},
|
|
264
|
+
"require": {
|
|
265
|
+
"production": "./mean.min.cjs",
|
|
266
|
+
"development": "./mean.cjs",
|
|
267
|
+
"default": "./mean.cjs"
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
"./median": {
|
|
271
|
+
"types": "./median.d.ts",
|
|
272
|
+
"import": {
|
|
273
|
+
"production": "./median.min.mjs",
|
|
274
|
+
"development": "./median.mjs",
|
|
275
|
+
"default": "./median.mjs"
|
|
276
|
+
},
|
|
277
|
+
"require": {
|
|
278
|
+
"production": "./median.min.cjs",
|
|
279
|
+
"development": "./median.cjs",
|
|
280
|
+
"default": "./median.cjs"
|
|
281
|
+
}
|
|
282
|
+
},
|
|
231
283
|
"./nonEmpty": {
|
|
232
284
|
"types": "./nonEmpty.d.ts",
|
|
233
285
|
"import": {
|
|
@@ -390,6 +442,9 @@
|
|
|
390
442
|
"arrayBuffer": [
|
|
391
443
|
"./arrayBuffer.d.ts"
|
|
392
444
|
],
|
|
445
|
+
"asNumber": [
|
|
446
|
+
"./asNumber.d.ts"
|
|
447
|
+
],
|
|
393
448
|
"assert": [
|
|
394
449
|
"./assert.d.ts"
|
|
395
450
|
],
|
|
@@ -408,6 +463,9 @@
|
|
|
408
463
|
"isEmpty": [
|
|
409
464
|
"./isEmpty.d.ts"
|
|
410
465
|
],
|
|
466
|
+
"isPromise": [
|
|
467
|
+
"./isPromise.d.ts"
|
|
468
|
+
],
|
|
411
469
|
"iterators": [
|
|
412
470
|
"./iterators.d.ts"
|
|
413
471
|
],
|
|
@@ -420,6 +478,12 @@
|
|
|
420
478
|
"logging": [
|
|
421
479
|
"./logging.d.ts"
|
|
422
480
|
],
|
|
481
|
+
"mean": [
|
|
482
|
+
"./mean.d.ts"
|
|
483
|
+
],
|
|
484
|
+
"median": [
|
|
485
|
+
"./median.d.ts"
|
|
486
|
+
],
|
|
423
487
|
"nonEmpty": [
|
|
424
488
|
"./nonEmpty.d.ts"
|
|
425
489
|
],
|
package/round.cjs
CHANGED
|
@@ -29,7 +29,10 @@ function round(n, numDecimalPlaces = 0) {
|
|
|
29
29
|
return Math.round(n * multipler) / multipler;
|
|
30
30
|
}
|
|
31
31
|
function roundS(n, numDecimalPlaces = 0) {
|
|
32
|
-
return round(n, numDecimalPlaces).
|
|
32
|
+
return round(n, numDecimalPlaces).toLocaleString("en-US", {
|
|
33
|
+
minimumFractionDigits: numDecimalPlaces,
|
|
34
|
+
maximumFractionDigits: numDecimalPlaces
|
|
35
|
+
});
|
|
33
36
|
}
|
|
34
37
|
// Annotate the CommonJS export names for ESM import in node:
|
|
35
38
|
0 && (module.exports = {
|
package/round.d.mts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
declare function round(n: number, numDecimalPlaces?: number): number;
|
|
8
8
|
/**
|
|
9
9
|
* Returns a string with the number in the exact number of decimal places
|
|
10
|
-
* specified, in case the number ends with zeroes
|
|
10
|
+
* specified, in case the number ends with zeroes, and adding commas for each
|
|
11
|
+
* group of 3 significant digits.
|
|
11
12
|
*/
|
|
12
13
|
declare function roundS(n: number, numDecimalPlaces?: number): string;
|
|
13
14
|
|
package/round.d.ts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
declare function round(n: number, numDecimalPlaces?: number): number;
|
|
8
8
|
/**
|
|
9
9
|
* Returns a string with the number in the exact number of decimal places
|
|
10
|
-
* specified, in case the number ends with zeroes
|
|
10
|
+
* specified, in case the number ends with zeroes, and adding commas for each
|
|
11
|
+
* group of 3 significant digits.
|
|
11
12
|
*/
|
|
12
13
|
declare function roundS(n: number, numDecimalPlaces?: number): string;
|
|
13
14
|
|
package/round.min.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var i=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var b=(r,n)=>{for(var t in n)i(r,t,{get:n[t],enumerable:!0})},d=(r,n,t,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of g(n))!p.call(r,o)&&o!==t&&i(r,o,{get:()=>n[o],enumerable:!(u=m(n,o))||u.enumerable});return r};var x=r=>d(i({},"__esModule",{value:!0}),r);var a={};b(a,{round:()=>e,roundS:()=>S});module.exports=x(a);function e(r,n=0){let t=Math.pow(10,n);return Math.round(r*t)/t}function S(r,n=0){return e(r,n).toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n})}0&&(module.exports={round,roundS});
|
|
2
2
|
//# sourceMappingURL=round.min.cjs.map
|
package/round.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/round.ts"],"sourcesContent":["/**\n * Simplifies rounding of floating point numbers. Note that if your number ends\n * with zeros, and you convert the number to string, you will lose the zeroes\n * at the end. To show the exact number of decimal places, you'll need to use\n * toFixed(). E.g. round(1.20, 2).toFixed(2).\n */\nexport function round(n: number, numDecimalPlaces = 0): number {\n const multipler = Math.pow(10, numDecimalPlaces);\n return Math.round(n * multipler) / multipler;\n}\n\n/**\n * Returns a string with the number in the exact number of decimal places\n * specified, in case the number ends with zeroes.\n */\nexport function roundS(n: number, numDecimalPlaces = 0): string {\n return round(n, numDecimalPlaces).
|
|
1
|
+
{"version":3,"sources":["../src/round.ts"],"sourcesContent":["/**\n * Simplifies rounding of floating point numbers. Note that if your number ends\n * with zeros, and you convert the number to string, you will lose the zeroes\n * at the end. To show the exact number of decimal places, you'll need to use\n * toFixed(). E.g. round(1.20, 2).toFixed(2).\n */\nexport function round(n: number, numDecimalPlaces = 0): number {\n const multipler = Math.pow(10, numDecimalPlaces);\n return Math.round(n * multipler) / multipler;\n}\n\n/**\n * Returns a string with the number in the exact number of decimal places\n * specified, in case the number ends with zeroes, and adding commas for each\n * group of 3 significant digits.\n */\nexport function roundS(n: number, numDecimalPlaces = 0): string {\n return round(n, numDecimalPlaces).toLocaleString(\"en-US\", {\n minimumFractionDigits: numDecimalPlaces,\n maximumFractionDigits: numDecimalPlaces,\n });\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,WAAAE,EAAA,WAAAC,IAAA,eAAAC,EAAAJ,GAMO,SAASE,EAAMG,EAAWC,EAAmB,EAAW,CAC7D,IAAMC,EAAY,KAAK,IAAI,GAAID,CAAgB,EAC/C,OAAO,KAAK,MAAMD,EAAIE,CAAS,EAAIA,CACrC,CAOO,SAASJ,EAAOE,EAAWC,EAAmB,EAAW,CAC9D,OAAOJ,EAAMG,EAAGC,CAAgB,EAAE,eAAe,QAAS,CACxD,sBAAuBA,EACvB,sBAAuBA,CACzB,CAAC,CACH","names":["round_exports","__export","round","roundS","__toCommonJS","n","numDecimalPlaces","multipler"]}
|
package/round.min.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function o(n
|
|
1
|
+
function o(r,n=0){let t=Math.pow(10,n);return Math.round(r*t)/t}function i(r,n=0){return o(r,n).toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n})}export{o as round,i as roundS};
|
|
2
2
|
//# sourceMappingURL=round.min.mjs.map
|
package/round.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/round.ts"],"sourcesContent":["/**\n * Simplifies rounding of floating point numbers. Note that if your number ends\n * with zeros, and you convert the number to string, you will lose the zeroes\n * at the end. To show the exact number of decimal places, you'll need to use\n * toFixed(). E.g. round(1.20, 2).toFixed(2).\n */\nexport function round(n: number, numDecimalPlaces = 0): number {\n const multipler = Math.pow(10, numDecimalPlaces);\n return Math.round(n * multipler) / multipler;\n}\n\n/**\n * Returns a string with the number in the exact number of decimal places\n * specified, in case the number ends with zeroes.\n */\nexport function roundS(n: number, numDecimalPlaces = 0): string {\n return round(n, numDecimalPlaces).
|
|
1
|
+
{"version":3,"sources":["../src/round.ts"],"sourcesContent":["/**\n * Simplifies rounding of floating point numbers. Note that if your number ends\n * with zeros, and you convert the number to string, you will lose the zeroes\n * at the end. To show the exact number of decimal places, you'll need to use\n * toFixed(). E.g. round(1.20, 2).toFixed(2).\n */\nexport function round(n: number, numDecimalPlaces = 0): number {\n const multipler = Math.pow(10, numDecimalPlaces);\n return Math.round(n * multipler) / multipler;\n}\n\n/**\n * Returns a string with the number in the exact number of decimal places\n * specified, in case the number ends with zeroes, and adding commas for each\n * group of 3 significant digits.\n */\nexport function roundS(n: number, numDecimalPlaces = 0): string {\n return round(n, numDecimalPlaces).toLocaleString(\"en-US\", {\n minimumFractionDigits: numDecimalPlaces,\n maximumFractionDigits: numDecimalPlaces,\n });\n}\n"],"mappings":"AAMO,SAASA,EAAMC,EAAWC,EAAmB,EAAW,CAC7D,IAAMC,EAAY,KAAK,IAAI,GAAID,CAAgB,EAC/C,OAAO,KAAK,MAAMD,EAAIE,CAAS,EAAIA,CACrC,CAOO,SAASC,EAAOH,EAAWC,EAAmB,EAAW,CAC9D,OAAOF,EAAMC,EAAGC,CAAgB,EAAE,eAAe,QAAS,CACxD,sBAAuBA,EACvB,sBAAuBA,CACzB,CAAC,CACH","names":["round","n","numDecimalPlaces","multipler","roundS"]}
|
package/round.mjs
CHANGED
|
@@ -4,7 +4,10 @@ function round(n, numDecimalPlaces = 0) {
|
|
|
4
4
|
return Math.round(n * multipler) / multipler;
|
|
5
5
|
}
|
|
6
6
|
function roundS(n, numDecimalPlaces = 0) {
|
|
7
|
-
return round(n, numDecimalPlaces).
|
|
7
|
+
return round(n, numDecimalPlaces).toLocaleString("en-US", {
|
|
8
|
+
minimumFractionDigits: numDecimalPlaces,
|
|
9
|
+
maximumFractionDigits: numDecimalPlaces
|
|
10
|
+
});
|
|
8
11
|
}
|
|
9
12
|
export {
|
|
10
13
|
round,
|
package/storageAdapter.d.mts
CHANGED
|
@@ -19,8 +19,11 @@ type StoredObject<T> = {
|
|
|
19
19
|
/**
|
|
20
20
|
* Full interface for a storage implementation. Each method can be either sync
|
|
21
21
|
* or async, and the interface works with either implementation scheme.
|
|
22
|
+
*
|
|
23
|
+
* Note: We are using `interface` instead of `type ... &` because typedoc
|
|
24
|
+
* cannot handle the `&` syntax to merge types.
|
|
22
25
|
*/
|
|
23
|
-
|
|
26
|
+
interface FullStorageAdapter<T> extends StorageAdapter<T> {
|
|
24
27
|
set: (key: string, value: T, expiryDeltaMs?: number | Duration) => Promise<void> | void;
|
|
25
28
|
getStoredObject: (key: string) => Promise<StoredObject<T> | undefined> | StoredObject<T> | undefined;
|
|
26
29
|
forEach(callback: (key: string, value: T, expiryMs: number, storedMs: number) => void | Promise<void>): Promise<void> | void;
|
|
@@ -28,6 +31,6 @@ type FullStorageAdapter<T> = StorageAdapter<T> & {
|
|
|
28
31
|
asMap<T>(): Promise<Map<string, StoredObject<T>>> | Map<string, StoredObject<T>>;
|
|
29
32
|
gc: () => Promise<void> | void;
|
|
30
33
|
gcNow: () => Promise<void> | void;
|
|
31
|
-
}
|
|
34
|
+
}
|
|
32
35
|
|
|
33
36
|
export type { FullStorageAdapter, StorageAdapter, StoredObject };
|