Compare commits
20 Commits
Author | SHA1 | Date | |
---|---|---|---|
76b570b3fe | |||
4fecf10d11 | |||
028b9c0f4c | |||
d938996a66 | |||
cdcaeda67c | |||
482c90b53b | |||
7500ba502f | |||
edc059d17d | |||
48cfbee46e | |||
26cc18ffb3 | |||
3fd5c5ed57 | |||
2e4559d805 | |||
95f8d5762c | |||
3bc82fab45 | |||
6b15848896 | |||
9a0f32323e | |||
f952abc95a | |||
21fc1378b8 | |||
a03567eba3 | |||
f9fc4fb7ff |
15
index.html
15
index.html
@ -1,15 +0,0 @@
|
||||
<!Doctype html>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>@ztimson/utils sandbox</title>
|
||||
</head>
|
||||
<body>
|
||||
<script type="module">
|
||||
import {PathEvent} from './dist/index.mjs';
|
||||
|
||||
console.log(PathEvent.filter(['payments/ztimson:cr', 'logs/momentum:c', 'data/Testing:r'], 'data'));
|
||||
console.log(PathEvent.filter(['data/Submissions/Test:r'], 'data/Submissions/Test/test.html'));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
11
package.json
11
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.23.17",
|
||||
"version": "0.24.11",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
@ -14,9 +14,9 @@
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs",
|
||||
"types": "./dist/index.d.ts"
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@ -26,6 +26,9 @@
|
||||
"test:coverage": "npx jest --coverage",
|
||||
"watch": "npx vite build --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"var-persist": "^1.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"jest": "^29.7.0",
|
||||
@ -34,7 +37,7 @@
|
||||
"typedoc": "^0.26.7",
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^5.0.12",
|
||||
"vite-plugin-dts": "^3.7.2"
|
||||
"vite-plugin-dts": "^4.5.3"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
|
@ -29,6 +29,14 @@ export class ASet<T> extends Array {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all elements
|
||||
*/
|
||||
clear() {
|
||||
this.splice(0, this.length);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete elements from set
|
||||
* @param items Elements that will be deleted
|
||||
|
78
src/cache.ts
78
src/cache.ts
@ -7,22 +7,25 @@ export type CacheOptions = {
|
||||
storage?: Storage;
|
||||
/** Key cache will be stored under */
|
||||
storageKey?: string;
|
||||
/** Keep or delete cached items once expired, defaults to delete */
|
||||
expiryPolicy?: 'delete' | 'keep';
|
||||
}
|
||||
|
||||
export type CachedValue<T> = T & {_expired?: boolean};
|
||||
|
||||
/**
|
||||
* Map of data which tracks whether it is a complete collection & offers optional expiry of cached values
|
||||
*/
|
||||
export class Cache<K extends string | number | symbol, T> {
|
||||
private store = <Record<K, T>>{};
|
||||
private store: Record<K, T> = <any>{};
|
||||
|
||||
/** Support index lookups */
|
||||
[key: string | number | symbol]: T | any;
|
||||
[key: string | number | symbol]: CachedValue<T> | any;
|
||||
/** Whether cache is complete */
|
||||
complete = false;
|
||||
|
||||
/**
|
||||
* Create new cache
|
||||
*
|
||||
* @param {keyof T} key Default property to use as primary key
|
||||
* @param options
|
||||
*/
|
||||
@ -39,7 +42,7 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
return new Proxy(this, {
|
||||
get: (target: this, prop: string | symbol) => {
|
||||
if(prop in target) return (target as any)[prop];
|
||||
return deepCopy(target.store[prop as K]);
|
||||
return this.get(prop as K, true);
|
||||
},
|
||||
set: (target: this, prop: string | symbol, value: any) => {
|
||||
if(prop in target) (target as any)[prop] = value;
|
||||
@ -54,18 +57,22 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
return <K>value[this.key];
|
||||
}
|
||||
|
||||
private save() {
|
||||
if(this.options.storageKey && this.options.storage)
|
||||
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all cached items
|
||||
*
|
||||
* @return {T[]} Array of items
|
||||
*/
|
||||
all(): T[] {
|
||||
return deepCopy(Object.values(this.store));
|
||||
all(expired?: boolean): CachedValue<T>[] {
|
||||
return deepCopy<any>(Object.values(this.store)
|
||||
.filter((v: any) => expired || !v._expired));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new item to the cache. Like set, but finds key automatically
|
||||
*
|
||||
* @param {T} value Item to add to cache
|
||||
* @param {number | undefined} ttl Override default expiry
|
||||
* @return {this}
|
||||
@ -78,12 +85,12 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
/**
|
||||
* Add several rows to the cache
|
||||
*
|
||||
* @param {T[]} rows Several items that will be cached using the default key
|
||||
* @param complete Mark cache as complete & reliable, defaults to true
|
||||
* @return {this}
|
||||
*/
|
||||
addAll(rows: T[], complete = true): this {
|
||||
this.clear();
|
||||
rows.forEach(r => this.add(r));
|
||||
this.complete = complete;
|
||||
return this;
|
||||
@ -93,26 +100,36 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
* Remove all keys from cache
|
||||
*/
|
||||
clear() {
|
||||
this.store = <Record<K, T>>{};
|
||||
this.complete = false;
|
||||
this.store = <any>{};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an item from the cache
|
||||
*
|
||||
* @param {K} key Item's primary key
|
||||
*/
|
||||
delete(key: K) {
|
||||
delete this.store[key];
|
||||
if(this.options.storageKey && this.options.storage)
|
||||
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return cache as an array of key-value pairs
|
||||
* @return {[K, T][]} Key-value pairs array
|
||||
*/
|
||||
entries(): [K, T][] {
|
||||
return <[K, T][]>Object.entries(this.store);
|
||||
entries(expired?: boolean): [K, CachedValue<T>][] {
|
||||
return deepCopy<any>(Object.entries(this.store)
|
||||
.filter((v: any) => expired || !v?._expired));
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually expire a cached item
|
||||
* @param {K} key Key to expire
|
||||
*/
|
||||
expire(key: K) {
|
||||
this.complete = false;
|
||||
if(this.options.expiryPolicy == 'keep') (<any>this.store[key])._expired = true;
|
||||
else this.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -120,50 +137,53 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
* @param {K} key Key to lookup
|
||||
* @return {T} Cached item
|
||||
*/
|
||||
get(key: K): T {
|
||||
return deepCopy(this.store[key]);
|
||||
get(key: K, expired?: boolean): T | null {
|
||||
const cached = deepCopy<any>(this.store[key] ?? null);
|
||||
if(expired || !cached?._expired) return cached;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of cached keys
|
||||
*
|
||||
* @return {K[]} Array of keys
|
||||
*/
|
||||
keys(): K[] {
|
||||
return <K[]>Object.keys(this.store);
|
||||
keys(expired?: boolean): K[] {
|
||||
return <K[]>Object.keys(this.store)
|
||||
.filter(k => expired || !(<any>this.store)[k]._expired);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get map of cached items
|
||||
*
|
||||
* @return {Record<K, T>}
|
||||
*/
|
||||
map(): Record<K, T> {
|
||||
return deepCopy(this.store);
|
||||
map(expired?: boolean): Record<K, CachedValue<T>> {
|
||||
const copy: any = deepCopy(this.store);
|
||||
if(!expired) Object.keys(copy).forEach(k => {
|
||||
if(copy[k]._expired) delete copy[k]
|
||||
});
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an item to the cache manually specifying the key
|
||||
*
|
||||
* @param {K} key Key item will be cached under
|
||||
* @param {T} value Item to cache
|
||||
* @param {number | undefined} ttl Override default expiry in seconds
|
||||
* @return {this}
|
||||
*/
|
||||
set(key: K, value: T, ttl = this.options.ttl): this {
|
||||
if(this.options.expiryPolicy == 'keep') delete (<any>this.store[key])._expired;
|
||||
this.store[key] = value;
|
||||
if(this.options.storageKey && this.options.storage)
|
||||
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
|
||||
this.save();
|
||||
if(ttl) setTimeout(() => {
|
||||
this.complete = false;
|
||||
this.delete(key);
|
||||
this.expire(key);
|
||||
this.save();
|
||||
}, ttl * 1000);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all cached items
|
||||
*
|
||||
* @return {T[]} Array of items
|
||||
*/
|
||||
values = this.all();
|
||||
|
19
src/csv.ts
19
src/csv.ts
@ -23,29 +23,29 @@ export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
|
||||
i++;
|
||||
} else inQuotes = !inQuotes;
|
||||
} else if (char === ',' && !inQuotes) {
|
||||
columns.push(current);
|
||||
columns.push(current.trim()); // Trim column values
|
||||
current = '';
|
||||
} else current += char;
|
||||
}
|
||||
columns.push(current);
|
||||
columns.push(current.trim()); // Trim last column value
|
||||
return columns.map(col => col.replace(/^"|"$/g, '').replace(/""/g, '"'));
|
||||
}
|
||||
|
||||
// Split rows
|
||||
// Normalize line endings and split rows
|
||||
const rows = [];
|
||||
let currentRow = '', inQuotes = false;
|
||||
for (const char of csv) {
|
||||
for (const char of csv.replace(/\r\n/g, '\n')) { // Normalize \r\n to \n
|
||||
if (char === '"') inQuotes = !inQuotes;
|
||||
if (char === '\n' && !inQuotes) {
|
||||
rows.push(currentRow);
|
||||
rows.push(currentRow.trim()); // Trim row
|
||||
currentRow = '';
|
||||
} else currentRow += char;
|
||||
}
|
||||
if(currentRow) rows.push(currentRow);
|
||||
if (currentRow) rows.push(currentRow.trim()); // Trim last row
|
||||
|
||||
// Figure out headers
|
||||
// Extract headers
|
||||
let headers: any = hasHeaders ? rows.splice(0, 1)[0] : null;
|
||||
if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g);
|
||||
if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g)?.map((h: any) => h.trim());
|
||||
|
||||
// Parse rows
|
||||
return <T[]>rows.map(r => {
|
||||
@ -64,6 +64,7 @@ export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert an array of objects to a CSV string
|
||||
*
|
||||
@ -80,7 +81,7 @@ export function toCsv(target: any, flatten=true) {
|
||||
const value = dotNotation<any>(row, h);
|
||||
if(value == null) return '';
|
||||
if(typeof value == 'object') return `"${JSONSanitize(value).replaceAll('"', '""')}"`;
|
||||
if(typeof value == 'string' && /[\n"]/g.test(value)) return `"${value.replaceAll('"', '""')}"`;
|
||||
if(typeof value == 'string' && /[\n",]/g.test(value)) return `"${value.replaceAll('"', '""')}"`;
|
||||
return value;
|
||||
}).join(','))
|
||||
].join('\n');
|
||||
|
13
src/http.ts
13
src/http.ts
@ -30,7 +30,13 @@ class HttpResponse<T = any> extends Response {
|
||||
url!: string;
|
||||
|
||||
constructor(resp: Response, stream: ReadableStream) {
|
||||
super(stream, {headers: resp.headers, status: resp.status, statusText: resp.statusText});
|
||||
const body = [204, 205, 304].includes(resp.status) ? null : stream;
|
||||
super(body, {
|
||||
headers: resp.headers,
|
||||
status: resp.status,
|
||||
statusText: resp.statusText,
|
||||
});
|
||||
|
||||
this.ok = resp.ok;
|
||||
this.redirected = resp.redirected;
|
||||
this.type = resp.type;
|
||||
@ -70,8 +76,9 @@ export class Http {
|
||||
|
||||
request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> {
|
||||
if(!this.url && !opts.url) throw new Error('URL needs to be set');
|
||||
let url = (opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1');
|
||||
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += '#' + opts.fragment;
|
||||
let url = opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '');
|
||||
url = url.replaceAll(/([^:]\/)\/+/g, '$1');
|
||||
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : `${url}#${opts.fragment}`;
|
||||
if(opts.query) {
|
||||
const q = Array.isArray(opts.query) ? opts.query :
|
||||
Object.keys(opts.query).map(k => ({key: k, value: (<any>opts.query)[k]}))
|
||||
|
@ -19,3 +19,4 @@ export * from './search';
|
||||
export * from './string';
|
||||
export * from './time';
|
||||
export * from './types';
|
||||
export * from 'var-persist';
|
||||
|
@ -6,7 +6,7 @@ import {JSONAttemptParse} from './objects.ts';
|
||||
* @param {string} token JWT to decode
|
||||
* @return {unknown} JWT payload
|
||||
*/
|
||||
export function jwtDecode<T>(token: string): T {
|
||||
export function decodeJwt<T>(token: string): T {
|
||||
const base64 = token.split('.')[1]
|
||||
.replace(/-/g, '+').replace(/_/g, '/');
|
||||
return <T>JSONAttemptParse(decodeURIComponent(atob(base64).split('').map(function(c) {
|
||||
|
12
src/misc.ts
12
src/misc.ts
@ -1,6 +1,18 @@
|
||||
import {PathEvent} from './path-events.ts';
|
||||
import {md5} from './string';
|
||||
|
||||
/**
|
||||
* Run a stringified function with arguments asynchronously
|
||||
* @param {object} args Map of key/value arguments
|
||||
* @param {string} fn Function as string
|
||||
* @param {boolean} async Run with async (returns a promise)
|
||||
* @return {T | Promise<T>} Function return result
|
||||
*/
|
||||
export function fn<T>(args: object, fn: string, async: boolean = false): T {
|
||||
const keys = Object.keys(args);
|
||||
return new Function(...keys, `return (${async ? 'async ' : ''}(${keys.join(',')}) => { ${fn} })(${keys.join(',')})`)(...keys.map(k => (<any>args)[k]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get profile image from Gravatar
|
||||
*
|
||||
|
@ -109,7 +109,6 @@ export function encodeQuery(data: any): string {
|
||||
).join('&');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Recursively flatten a nested object, while maintaining key structure
|
||||
*
|
||||
|
@ -31,7 +31,7 @@ export function PE(str: TemplateStringsArray, ...args: any[]) {
|
||||
if(str[i]) combined.push(str[i]);
|
||||
if(args[i]) combined.push(args[i]);
|
||||
}
|
||||
return new PathEvent(combined.join(''));
|
||||
return new PathEvent(combined.join('/'));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -79,20 +79,20 @@ export class PathEvent {
|
||||
set none(v: boolean) { v ? this.methods = new ASet<Method>(['n']) : this.methods.delete('n'); }
|
||||
/** Create method specified */
|
||||
get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) }
|
||||
set create(v: boolean) { v ? this.methods.delete('n').add('c') : this.methods.delete('c'); }
|
||||
set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); }
|
||||
/** Read method specified */
|
||||
get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) }
|
||||
set read(v: boolean) { v ? this.methods.delete('n').add('r') : this.methods.delete('r'); }
|
||||
set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); }
|
||||
/** Update method specified */
|
||||
get update(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('u')) }
|
||||
set update(v: boolean) { v ? this.methods.delete('n').add('u') : this.methods.delete('u'); }
|
||||
set update(v: boolean) { v ? this.methods.delete('n').delete('*').add('u') : this.methods.delete('u'); }
|
||||
/** Delete method specified */
|
||||
get delete(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('d')) }
|
||||
set delete(v: boolean) { v ? this.methods.delete('n').add('d') : this.methods.delete('d'); }
|
||||
set delete(v: boolean) { v ? this.methods.delete('n').delete('*').add('d') : this.methods.delete('d'); }
|
||||
|
||||
constructor(Event: string | PathEvent) {
|
||||
if(typeof Event == 'object') return Object.assign(this, Event);
|
||||
let [p, scope, method] = Event.replaceAll(/\/{2,}/g, '/').split(':');
|
||||
constructor(e: string | PathEvent) {
|
||||
if(typeof e == 'object') return Object.assign(this, e);
|
||||
let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
|
||||
if(!method) method = scope || '*';
|
||||
if(p == '*' || !p && method == '*') {
|
||||
p = '';
|
||||
@ -100,14 +100,14 @@ export class PathEvent {
|
||||
}
|
||||
let temp = p.split('/').filter(p => !!p);
|
||||
this.module = temp.splice(0, 1)[0]?.toLowerCase() || '';
|
||||
this.fullPath = p;
|
||||
this.path = temp.join('/');
|
||||
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
|
||||
this.name = temp.pop() || '';
|
||||
this.methods = new ASet(<any>method.split(''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
|
||||
* Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
|
||||
* combined until a "none" is reached
|
||||
*
|
||||
* @param {string | PathEvent} paths Events as strings or pre-parsed
|
||||
@ -199,14 +199,14 @@ export class PathEvent {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create event string from its components
|
||||
* Create event string from its components
|
||||
*
|
||||
* @param {string | string[]} path Event path
|
||||
* @param {Method} methods Event method
|
||||
* @return {string} String representation of Event
|
||||
*/
|
||||
static toString(path: string | string[], methods: Method | Method[]): string {
|
||||
let p = makeArray(path).filter(p => p != null).join('/');
|
||||
let p = makeArray(path).filter(p => !!p).join('/');
|
||||
p = p?.trim().replaceAll(/\/{2,}/g, '/').replaceAll(/(^\/|\/$)/g, '');
|
||||
if(methods?.length) p += `:${makeArray(methods).map(m => m.toLowerCase()).join('')}`;
|
||||
return p;
|
||||
@ -223,7 +223,7 @@ export class PathEvent {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create event string from its components
|
||||
* Create event string from its components
|
||||
*
|
||||
* @return {string} String representation of Event
|
||||
*/
|
||||
@ -235,11 +235,12 @@ export class PathEvent {
|
||||
export type PathListener = (event: PathEvent, ...args: any[]) => any;
|
||||
export type PathUnsubscribe = () => void;
|
||||
|
||||
export type Event = string | PathEvent;
|
||||
export interface IPathEventEmitter {
|
||||
emit(event: string, ...args: any[]): void;
|
||||
emit(event: Event, ...args: any[]): void;
|
||||
off(listener: PathListener): void;
|
||||
on(event: string, listener: PathListener): PathUnsubscribe;
|
||||
once(event: string, listener?: PathListener): Promise<any>;
|
||||
on(event: Event | Event[], listener: PathListener): PathUnsubscribe;
|
||||
once(event: Event | Event[], listener?: PathListener): Promise<any>;
|
||||
relayEvents(emitter: PathEventEmitter): void;
|
||||
}
|
||||
|
||||
@ -249,8 +250,10 @@ export interface IPathEventEmitter {
|
||||
export class PathEventEmitter implements IPathEventEmitter{
|
||||
private listeners: [PathEvent, PathListener][] = [];
|
||||
|
||||
emit(event: string | PathEvent, ...args: any[]) {
|
||||
const parsed = new PathEvent(event);
|
||||
constructor(public readonly prefix: string = '') { }
|
||||
|
||||
emit(event: Event, ...args: any[]) {
|
||||
const parsed = new PathEvent(`${this.prefix}/${typeof event == 'string' ? event : event.toString()}`);
|
||||
this.listeners.filter(l => PathEvent.has(l[0], event))
|
||||
.forEach(async l => l[1](parsed, ...args));
|
||||
};
|
||||
@ -259,12 +262,15 @@ export class PathEventEmitter implements IPathEventEmitter{
|
||||
this.listeners = this.listeners.filter(l => l[1] != listener);
|
||||
}
|
||||
|
||||
on(event: string | string[], listener: PathListener): PathUnsubscribe {
|
||||
makeArray(event).forEach(e => this.listeners.push([new PathEvent(e), listener]));
|
||||
on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
|
||||
makeArray(event).forEach(e => this.listeners.push([
|
||||
new PathEvent(`${this.prefix}/${typeof e == 'string' ? event : event.toString()}`),
|
||||
listener
|
||||
]));
|
||||
return () => this.off(listener);
|
||||
}
|
||||
|
||||
once(event: string | string[], listener?: PathListener): Promise<any> {
|
||||
once(event: Event | Event[], listener?: PathListener): Promise<any> {
|
||||
return new Promise(res => {
|
||||
const unsubscribe = this.on(event, (event: PathEvent, ...args: any[]) => {
|
||||
res(args.length < 2 ? args[0] : args);
|
||||
|
@ -1,4 +1,4 @@
|
||||
import {dotNotation, JSONAttemptParse} from './objects';
|
||||
import {dotNotation, JSONAttemptParse, JSONSerialize} from './objects.ts';
|
||||
|
||||
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
|
||||
if(!rows) return [];
|
||||
@ -12,27 +12,48 @@ export function search(rows: any[], search: string, regex?: boolean, transform:
|
||||
try { return RegExp(search, 'gm').test(v.toString()); }
|
||||
catch { return false; }
|
||||
}).length
|
||||
} else {
|
||||
return logicTest(r, search);
|
||||
}
|
||||
// Make sure at least one OR passes
|
||||
const or = search.split('||').map(p => p.trim()).filter(p => !!p);
|
||||
return -1 != or.findIndex(p => {
|
||||
// Make sure all ANDs pass
|
||||
const and = p.split('&&').map(p => p.trim()).filter(p => !!p);
|
||||
return and.filter(p => {
|
||||
// Boolean operator
|
||||
const prop = /(\w+)\s*(==?|!=|>=|>|<=|<)\s*(\w+)/g.exec(p);
|
||||
if(prop) {
|
||||
const a = JSON.stringify(JSONAttemptParse(dotNotation<any>(value, prop[1])));
|
||||
const operator = prop[2] == '=' ? '==' : prop[2];
|
||||
const b = JSON.stringify(JSONAttemptParse(prop[3]));
|
||||
return eval(`${a} ${operator} ${b}`);
|
||||
}
|
||||
// Case-sensitive
|
||||
const v = Object.values(value).join('');
|
||||
if(/[A-Z]/g.test(search)) return v.includes(p);
|
||||
// Case-insensitive
|
||||
return v.toLowerCase().includes(p);
|
||||
}).length == and.length;
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Test an object against a logic condition. By default values are checked
|
||||
* @param {string} condition
|
||||
* @param {object} target
|
||||
* @return {boolean}
|
||||
*/
|
||||
export function logicTest(target: object, condition: string): boolean {
|
||||
const evalBoolean = (a: any, op: string, b: any): boolean => {
|
||||
switch(op) {
|
||||
case '=':
|
||||
case '==': return a == b;
|
||||
case '!=': return a != b;
|
||||
case '>': return a > b;
|
||||
case '>=': return a >= b;
|
||||
case '<': return a < b;
|
||||
case '<=': return a <= b;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
const or = condition.split('||').map(p => p.trim()).filter(p => !!p);
|
||||
return -1 != or.findIndex(p => {
|
||||
// Make sure all ANDs pass
|
||||
const and = p.split('&&').map(p => p.trim()).filter(p => !!p);
|
||||
return and.filter(p => {
|
||||
// Boolean operator
|
||||
const prop = /(\S+)\s*(==?|!=|>=|>|<=|<)\s*(\S+)/g.exec(p);
|
||||
if(prop) {
|
||||
const key = Object.keys(target).find(k => k.toLowerCase() == prop[1].toLowerCase());
|
||||
return evalBoolean(dotNotation<any>(target, key || prop[1]), prop[2], JSONAttemptParse(prop[3]));
|
||||
}
|
||||
// Case-sensitive
|
||||
const v = Object.values(target).map(JSONSerialize).join('');
|
||||
if(/[A-Z]/g.test(condition)) return v.includes(p);
|
||||
// Case-insensitive
|
||||
return v.toLowerCase().includes(p);
|
||||
}).length == and.length;
|
||||
});
|
||||
}
|
||||
|
@ -19,12 +19,10 @@ export const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/';
|
||||
export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST;
|
||||
|
||||
/**
|
||||
* Converts text to camel case
|
||||
* Converts text to camelCase
|
||||
*/
|
||||
export function camelCase(text?: string) {
|
||||
if(!text) return '';
|
||||
text = text.replaceAll(/^[0-9]+/g, '')
|
||||
.replaceAll(/[^a-zA-Z0-9]+(\w?)/g, (...args) => args[1]?.toUpperCase() || '');
|
||||
export function camelCase(str?: string) {
|
||||
const text = pascalCase(str);
|
||||
return text[0].toLowerCase() + text.slice(1);
|
||||
}
|
||||
|
||||
@ -74,6 +72,17 @@ export function insertAt(target: string, str: string, index: number): String {
|
||||
return `${target.slice(0, index)}${str}${target.slice(index + 1)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts text to kebab-case
|
||||
*/
|
||||
export function kebabCase(str: string) {
|
||||
if(!str) return '';
|
||||
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
|
||||
.replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `-${args[0].toLowerCase()}`)
|
||||
.replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}-${args[2]}`)
|
||||
.replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `-${args[1] ?? ''}`).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add padding to string
|
||||
*
|
||||
@ -96,6 +105,18 @@ export function pad(text: any, length: number, char: string = ' ', start = true)
|
||||
return text.toString().padEnd(length, char);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert text to PascalCase
|
||||
* @param {string} str
|
||||
* @return {string}
|
||||
*/
|
||||
export function pascalCase(str?: string) {
|
||||
if(!str) return '';
|
||||
const text = str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
|
||||
.replaceAll(/[^a-zA-Z0-9]+(\w?)/g, (...args) => args[1]?.toUpperCase() || '');
|
||||
return text[0].toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random hexadecimal value
|
||||
*
|
||||
@ -159,6 +180,17 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts text to snake_case
|
||||
*/
|
||||
export function snakeCase(str?: string) {
|
||||
if(!str) return '';
|
||||
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
|
||||
.replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `_${args[0].toLowerCase()}`)
|
||||
.replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}_${args[2]}`)
|
||||
.replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `_${args[1] ?? ''}`).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice a string together (Similar to Array.splice)
|
||||
*
|
||||
|
@ -95,7 +95,7 @@ export function formatDate(format = 'YYYY-MM-DD H:mm', date: Date | number | str
|
||||
return (offset > 0 ? '-' : '') + `${hours}:${minutes.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
if(typeof date == 'number' || typeof date == 'string') date = new Date(date);
|
||||
if(typeof date == 'number' || typeof date == 'string' || date == null) date = new Date(date);
|
||||
|
||||
// Handle timezones
|
||||
let t!: [string, number];
|
||||
|
@ -18,3 +18,10 @@
|
||||
export function typeKeys<T extends object>() {
|
||||
return Object.keys(<T>{}) as Array<keyof T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark all properties as writable
|
||||
*/
|
||||
export type Writable<T> = {
|
||||
-readonly [P in keyof T]: T[P]
|
||||
};
|
||||
|
@ -1,36 +1,18 @@
|
||||
import {sleep, parseUrl} from '../src';
|
||||
import {fn} from '../src';
|
||||
|
||||
describe('Miscellanies Utilities', () => {
|
||||
describe('sleep', () => {
|
||||
test('wait until', async () => {
|
||||
const wait = ~~(Math.random() * 500);
|
||||
const time = new Date().getTime();
|
||||
await sleep(wait);
|
||||
expect(new Date().getTime()).toBeGreaterThanOrEqual(time + wait);
|
||||
});
|
||||
});
|
||||
|
||||
describe('urlParser', () => {
|
||||
test('localhost w/ port', () => {
|
||||
const parsed = parseUrl('http://localhost:4200/some/path?q1=test1&q2=test2#frag');
|
||||
expect(parsed.protocol).toStrictEqual('http');
|
||||
expect(parsed.host).toStrictEqual('localhost:4200');
|
||||
expect(parsed.domain).toStrictEqual('localhost');
|
||||
expect(parsed.port).toStrictEqual(4200);
|
||||
expect(parsed.path).toStrictEqual('/some/path');
|
||||
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
|
||||
expect(parsed.fragment).toStrictEqual('frag');
|
||||
describe('fn', () => {
|
||||
test('async', async () => {
|
||||
const test = {a: Math.random()};
|
||||
const resp = fn(test, 'return a;', true);
|
||||
expect(resp instanceof Promise).toBeTruthy();
|
||||
expect(await resp).toEqual(test['a']);
|
||||
});
|
||||
|
||||
test('advanced URL', () => {
|
||||
const parsed = parseUrl('https://sub.domain.example.com/some/path?q1=test1&q2=test2#frag');
|
||||
expect(parsed.protocol).toStrictEqual('https');
|
||||
expect(parsed.host).toStrictEqual('sub.domain.example.com');
|
||||
expect(parsed.domain).toStrictEqual('example.com');
|
||||
expect(parsed.subdomain).toStrictEqual('sub.domain');
|
||||
expect(parsed.path).toStrictEqual('/some/path');
|
||||
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
|
||||
expect(parsed.fragment).toStrictEqual('frag');
|
||||
test('sync', async () => {
|
||||
const test = {a: Math.random()};
|
||||
const resp = fn(test, 'return a;3');
|
||||
expect(resp).toEqual(test['a']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
43
tests/path-events.spec.ts
Normal file
43
tests/path-events.spec.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import {PathEvent} from '../src';
|
||||
|
||||
describe('Path Events', () => {
|
||||
describe('malformed', () => {
|
||||
test('starting slash', async () =>
|
||||
expect(new PathEvent('/module').toString()).toEqual('module:*'));
|
||||
test('trailing slash', async () =>
|
||||
expect(new PathEvent('module/').toString()).toEqual('module:*'));
|
||||
test('double slash', async () =>
|
||||
expect(new PathEvent('module////path').toString()).toEqual('module/path:*'));
|
||||
});
|
||||
|
||||
describe('methods', () => {
|
||||
test('custom', async () => {
|
||||
expect(new PathEvent('module:t').methods.includes('t')).toBeTruthy();
|
||||
expect(new PathEvent('module:t').methods.includes('z')).toBeFalsy();
|
||||
});
|
||||
test('create', async () =>
|
||||
expect(new PathEvent('module:crud').create).toBeTruthy());
|
||||
test('read', async () =>
|
||||
expect(new PathEvent('module:crud').read).toBeTruthy());
|
||||
test('update', async () =>
|
||||
expect(new PathEvent('module:crud').update).toBeTruthy());
|
||||
test('delete', async () =>
|
||||
expect(new PathEvent('module:crud').delete).toBeTruthy());
|
||||
test('none', async () => {
|
||||
const event = new PathEvent('module:n');
|
||||
expect(event.none).toBeTruthy();
|
||||
expect(event.create).toBeFalsy();
|
||||
expect(event.read).toBeFalsy();
|
||||
expect(event.update).toBeFalsy();
|
||||
expect(event.delete).toBeFalsy()
|
||||
});
|
||||
test('wildcard', async () => {
|
||||
const event = new PathEvent('module:*');
|
||||
expect(event.none).toBeFalsy();
|
||||
expect(event.create).toBeTruthy();
|
||||
expect(event.read).toBeTruthy();
|
||||
expect(event.update).toBeTruthy();
|
||||
expect(event.delete).toBeTruthy()
|
||||
});
|
||||
});
|
||||
});
|
@ -1,4 +1,5 @@
|
||||
import {matchAll, randomString, randomStringBuilder} from "../src";
|
||||
import {matchAll, parseUrl, randomString, randomStringBuilder} from "../src";
|
||||
|
||||
|
||||
describe('String Utilities', () => {
|
||||
describe('randomString', () => {
|
||||
@ -47,4 +48,28 @@ describe('String Utilities', () => {
|
||||
test('using regex', () => expect(matchAll('fooBar fooBar FooBar', /fooBar/g).length).toBe(2));
|
||||
test('using malformed regex', () => expect(() => matchAll('fooBar fooBar FooBar', /fooBar/)).toThrow());
|
||||
});
|
||||
|
||||
describe('urlParser', () => {
|
||||
test('localhost', () => {
|
||||
const parsed = parseUrl('http://localhost:4200/some/path?q1=test1&q2=test2#frag');
|
||||
expect(parsed.protocol).toStrictEqual('http');
|
||||
expect(parsed.host).toStrictEqual('localhost:4200');
|
||||
expect(parsed.domain).toStrictEqual('localhost');
|
||||
expect(parsed.port).toStrictEqual(4200);
|
||||
expect(parsed.path).toStrictEqual('/some/path');
|
||||
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
|
||||
expect(parsed.fragment).toStrictEqual('frag');
|
||||
});
|
||||
|
||||
test('subdomains', () => {
|
||||
const parsed = parseUrl('https://sub.domain.example.com/some/path?q1=test1&q2=test2#frag');
|
||||
expect(parsed.protocol).toStrictEqual('https');
|
||||
expect(parsed.host).toStrictEqual('sub.domain.example.com');
|
||||
expect(parsed.domain).toStrictEqual('example.com');
|
||||
expect(parsed.subdomain).toStrictEqual('sub.domain');
|
||||
expect(parsed.path).toStrictEqual('/some/path');
|
||||
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
|
||||
expect(parsed.fragment).toStrictEqual('frag');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
12
tests/time.spec.ts
Normal file
12
tests/time.spec.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import {sleep} from '../src';
|
||||
|
||||
describe('Time Utilities', () => {
|
||||
describe('sleep', () => {
|
||||
test('wait until', async () => {
|
||||
const wait = ~~(Math.random() * 500);
|
||||
const time = new Date().getTime();
|
||||
await sleep(wait);
|
||||
expect(new Date().getTime()).toBeGreaterThanOrEqual(time + wait);
|
||||
});
|
||||
});
|
||||
});
|
Reference in New Issue
Block a user