Compare commits
4 Commits
Author | SHA1 | Date | |
---|---|---|---|
91dc17667e | |||
11cfc67650 | |||
4ed23e1502 | |||
e3bbd13ed8 |
14
index.html
14
index.html
@ -1,19 +1,9 @@
|
||||
<html>
|
||||
<body>
|
||||
<script type="module">
|
||||
import {Cache, Database} from './dist/index.mjs';
|
||||
import {PES} from './dist/index.mjs';
|
||||
|
||||
const db = new Database('test');
|
||||
db.connection.then(() => {
|
||||
console.log(db.tables);
|
||||
});
|
||||
|
||||
const table = window.table = await db.createTable('test2');
|
||||
table.add({ name: 'Alice', age: 30 });
|
||||
table.add({ name: 'Bob', age: 24 });
|
||||
table.add({ name: 'Carol', age: 30 });
|
||||
|
||||
console.log(db.tables);
|
||||
console.log(PES`storage${'Test/Test'}:d`);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.25.9",
|
||||
"version": "0.25.14",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
19
src/cache.ts
19
src/cache.ts
@ -1,5 +1,5 @@
|
||||
import {Table} from './database.ts';
|
||||
import {deepCopy, JSONSanitize} from './objects.ts';
|
||||
import {deepCopy, includes, JSONSanitize} from './objects.ts';
|
||||
|
||||
export type CacheOptions = {
|
||||
/** Delete keys automatically after x amount of seconds */
|
||||
@ -35,8 +35,10 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
if(options.storage) {
|
||||
if(options.storage instanceof Table) {
|
||||
(async () => (await options.storage?.getAll()).forEach((v: any) => {
|
||||
console.log(v);
|
||||
this.add(v)
|
||||
if(v) {
|
||||
try { this.add(v) }
|
||||
catch { }
|
||||
}
|
||||
}))()
|
||||
} else if(options.storageKey) {
|
||||
const stored = options.storage?.getItem(options.storageKey);
|
||||
@ -58,6 +60,7 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
private getKey(value: T): K {
|
||||
if(!this.key) throw new Error('No key defined');
|
||||
if(value[this.key] === undefined) throw new Error(`${this.key.toString()} Doesn't exist on ${JSON.stringify(value, null, 2)}`);
|
||||
return <K>value[this.key];
|
||||
}
|
||||
|
||||
@ -146,6 +149,16 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the first cached item to match a filter
|
||||
* @param {Partial<T>} filter Partial item to match
|
||||
* @param {Boolean} expired Include expired items, defaults to false
|
||||
* @returns {T | undefined} Cached item or undefined if nothing matched
|
||||
*/
|
||||
find(filter: Partial<T>, expired?: boolean): T | undefined {
|
||||
return <T>Object.values(this.store).find((row: any) => (expired || !row._expired) && includes(row, filter));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get item from the cache
|
||||
* @param {K} key Key to lookup
|
||||
|
@ -48,7 +48,7 @@ export function PES(str: TemplateStringsArray, ...args: any[]) {
|
||||
if(str[i]) combined.push(str[i]);
|
||||
if(args[i]) combined.push(args[i]);
|
||||
}
|
||||
const [paths, methods] = combined.join('').split(':');
|
||||
const [paths, methods] = combined.join('/').split(':');
|
||||
return PathEvent.toString(paths, <any>methods?.split(''));
|
||||
}
|
||||
|
||||
@ -254,8 +254,8 @@ export class PathEventEmitter implements IPathEventEmitter{
|
||||
constructor(public readonly prefix: string = '') { }
|
||||
|
||||
emit(event: Event, ...args: any[]) {
|
||||
const parsed = new PathEvent(`${this.prefix}/${new PathEvent(event).toString()}`);
|
||||
this.listeners.filter(l => PathEvent.has(l[0], `${this.prefix}/${event}`))
|
||||
const parsed = PE`${this.prefix}/${event}`;
|
||||
this.listeners.filter(l => PathEvent.has(l[0], parsed))
|
||||
.forEach(async l => l[1](parsed, ...args));
|
||||
};
|
||||
|
||||
|
32
src/time.ts
32
src/time.ts
@ -190,3 +190,35 @@ export async function sleepWhile(fn : () => boolean | Promise<boolean>, checkInt
|
||||
export function timeUntil(date: Date | number): number {
|
||||
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert a timezone string (e.g., "America/Toronto") to its current UTC offset in minutes.
|
||||
* @param {string} tz - Timezone string, e.g. "America/Toronto"
|
||||
* @param {Date} [date=new Date()] - The date for which you want the offset (default is now)
|
||||
* @returns {number} - Offset in minutes (e.g., -240)
|
||||
*/
|
||||
export function timezoneOffset(tz: string, date: Date = new Date()): number {
|
||||
const dtf = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: tz,
|
||||
hour12: false,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
const parts = dtf.formatToParts(date);
|
||||
const get = (type: string) => Number(parts.find(v => v.type === type)?.value);
|
||||
const y = get('year');
|
||||
const mo = get('month');
|
||||
const d = get('day');
|
||||
const h = get('hour');
|
||||
const m = get('minute');
|
||||
const s = get('second');
|
||||
|
||||
const asUTC = Date.UTC(y, mo - 1, d, h, m, s);
|
||||
const asLocal = date.getTime();
|
||||
return Math.round((asLocal - asUTC) / 60000);
|
||||
}
|
||||
|
Reference in New Issue
Block a user