Compare commits
16 Commits
Author | SHA1 | Date | |
---|---|---|---|
edc059d17d | |||
48cfbee46e | |||
26cc18ffb3 | |||
3fd5c5ed57 | |||
2e4559d805 | |||
95f8d5762c | |||
3bc82fab45 | |||
6b15848896 | |||
9a0f32323e | |||
f952abc95a | |||
21fc1378b8 | |||
a03567eba3 | |||
f9fc4fb7ff | |||
ff16f3bf9b | |||
e0085ecb6f | |||
1c2c18b65d |
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",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.23.14",
|
"version": "0.24.4",
|
||||||
"description": "Utility library",
|
"description": "Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@ -14,9 +14,9 @@
|
|||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
"import": "./dist/index.mjs",
|
"import": "./dist/index.mjs",
|
||||||
"require": "./dist/index.cjs",
|
"require": "./dist/index.cjs"
|
||||||
"types": "./dist/index.d.ts"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@ -26,6 +26,9 @@
|
|||||||
"test:coverage": "npx jest --coverage",
|
"test:coverage": "npx jest --coverage",
|
||||||
"watch": "npx vite build --watch"
|
"watch": "npx vite build --watch"
|
||||||
},
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"var-persist": "^1.0.1"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^29.5.12",
|
"@types/jest": "^29.5.12",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
@ -34,7 +37,7 @@
|
|||||||
"typedoc": "^0.26.7",
|
"typedoc": "^0.26.7",
|
||||||
"typescript": "^5.3.3",
|
"typescript": "^5.3.3",
|
||||||
"vite": "^5.0.12",
|
"vite": "^5.0.12",
|
||||||
"vite-plugin-dts": "^3.7.2"
|
"vite-plugin-dts": "^4.5.3"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist"
|
"dist"
|
||||||
|
10
src/cache.ts
10
src/cache.ts
@ -22,7 +22,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Create new cache
|
* Create new cache
|
||||||
*
|
|
||||||
* @param {keyof T} key Default property to use as primary key
|
* @param {keyof T} key Default property to use as primary key
|
||||||
* @param options
|
* @param options
|
||||||
*/
|
*/
|
||||||
@ -56,7 +55,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all cached items
|
* Get all cached items
|
||||||
*
|
|
||||||
* @return {T[]} Array of items
|
* @return {T[]} Array of items
|
||||||
*/
|
*/
|
||||||
all(): T[] {
|
all(): T[] {
|
||||||
@ -65,7 +63,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a new item to the cache. Like set, but finds key automatically
|
* Add a new item to the cache. Like set, but finds key automatically
|
||||||
*
|
|
||||||
* @param {T} value Item to add to cache
|
* @param {T} value Item to add to cache
|
||||||
* @param {number | undefined} ttl Override default expiry
|
* @param {number | undefined} ttl Override default expiry
|
||||||
* @return {this}
|
* @return {this}
|
||||||
@ -78,12 +75,12 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Add several rows to the cache
|
* Add several rows to the cache
|
||||||
*
|
|
||||||
* @param {T[]} rows Several items that will be cached using the default key
|
* @param {T[]} rows Several items that will be cached using the default key
|
||||||
* @param complete Mark cache as complete & reliable, defaults to true
|
* @param complete Mark cache as complete & reliable, defaults to true
|
||||||
* @return {this}
|
* @return {this}
|
||||||
*/
|
*/
|
||||||
addAll(rows: T[], complete = true): this {
|
addAll(rows: T[], complete = true): this {
|
||||||
|
this.clear();
|
||||||
rows.forEach(r => this.add(r));
|
rows.forEach(r => this.add(r));
|
||||||
this.complete = complete;
|
this.complete = complete;
|
||||||
return this;
|
return this;
|
||||||
@ -98,7 +95,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete an item from the cache
|
* Delete an item from the cache
|
||||||
*
|
|
||||||
* @param {K} key Item's primary key
|
* @param {K} key Item's primary key
|
||||||
*/
|
*/
|
||||||
delete(key: K) {
|
delete(key: K) {
|
||||||
@ -126,7 +122,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a list of cached keys
|
* Get a list of cached keys
|
||||||
*
|
|
||||||
* @return {K[]} Array of keys
|
* @return {K[]} Array of keys
|
||||||
*/
|
*/
|
||||||
keys(): K[] {
|
keys(): K[] {
|
||||||
@ -135,7 +130,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get map of cached items
|
* Get map of cached items
|
||||||
*
|
|
||||||
* @return {Record<K, T>}
|
* @return {Record<K, T>}
|
||||||
*/
|
*/
|
||||||
map(): Record<K, T> {
|
map(): Record<K, T> {
|
||||||
@ -144,7 +138,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Add an item to the cache manually specifying the key
|
* Add an item to the cache manually specifying the key
|
||||||
*
|
|
||||||
* @param {K} key Key item will be cached under
|
* @param {K} key Key item will be cached under
|
||||||
* @param {T} value Item to cache
|
* @param {T} value Item to cache
|
||||||
* @param {number | undefined} ttl Override default expiry in seconds
|
* @param {number | undefined} ttl Override default expiry in seconds
|
||||||
@ -163,7 +156,6 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all cached items
|
* Get all cached items
|
||||||
*
|
|
||||||
* @return {T[]} Array of items
|
* @return {T[]} Array of items
|
||||||
*/
|
*/
|
||||||
values = this.all();
|
values = this.all();
|
||||||
|
84
src/csv.ts
84
src/csv.ts
@ -1,32 +1,59 @@
|
|||||||
|
import {makeArray} from './array.ts';
|
||||||
import {ASet} from './aset.ts';
|
import {ASet} from './aset.ts';
|
||||||
import {dotNotation, flattenObj, JSONSanitize} from './objects.ts';
|
import {dotNotation, flattenObj, JSONSanitize} from './objects.ts';
|
||||||
import {LETTER_LIST} from './string.ts';
|
import {LETTER_LIST} from './string.ts';
|
||||||
|
|
||||||
export function fromCsv<T = any>(csv: string, hasHeaders=true): T[] {
|
/**
|
||||||
const row = csv.split('\n');
|
* Parse a CSV string into an array of objects
|
||||||
let headers: any = hasHeaders ? row.splice(0, 1)[0] : null;
|
*
|
||||||
if(headers) headers = headers.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g);
|
* @param csv String with CSV
|
||||||
return <T[]>row.map(r => {
|
* @param hasHeaders First line of CSV contains headers
|
||||||
function parseLine(line: string): (string | null)[] {
|
* @return {T[]} Array of parsed objects
|
||||||
const parts = line.split(','), columns: string[] = [];
|
*/
|
||||||
let quoted = false;
|
export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
|
||||||
for(const p of parts) {
|
function parseLine(line: string): (string | null)[] {
|
||||||
if(quoted) columns[columns.length - 1] = columns.at(-1) + ',' + p;
|
const columns: string[] = [];
|
||||||
else columns.push(p);
|
let current = '', inQuotes = false;
|
||||||
if(/[^"]"$/g.test(p)) {
|
for (let i = 0; i < line.length; i++) {
|
||||||
quoted = false;
|
const char = line[i];
|
||||||
} else if(/^"[^"]/g.test(p)) {
|
const nextChar = line[i + 1];
|
||||||
quoted = true;
|
if (char === '"') {
|
||||||
}
|
if (inQuotes && nextChar === '"') {
|
||||||
}
|
current += '"'; // Handle escaped quotes
|
||||||
return columns;
|
i++;
|
||||||
|
} else inQuotes = !inQuotes;
|
||||||
|
} else if (char === ',' && !inQuotes) {
|
||||||
|
columns.push(current.trim()); // Trim column values
|
||||||
|
current = '';
|
||||||
|
} else current += char;
|
||||||
}
|
}
|
||||||
|
columns.push(current.trim()); // Trim last column value
|
||||||
|
return columns.map(col => col.replace(/^"|"$/g, '').replace(/""/g, '"'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize line endings and split rows
|
||||||
|
const rows = [];
|
||||||
|
let currentRow = '', inQuotes = false;
|
||||||
|
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.trim()); // Trim row
|
||||||
|
currentRow = '';
|
||||||
|
} else currentRow += char;
|
||||||
|
}
|
||||||
|
if (currentRow) rows.push(currentRow.trim()); // Trim last row
|
||||||
|
|
||||||
|
// Extract headers
|
||||||
|
let headers: any = hasHeaders ? rows.splice(0, 1)[0] : null;
|
||||||
|
if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g)?.map((h: any) => h.trim());
|
||||||
|
|
||||||
|
// Parse rows
|
||||||
|
return <T[]>rows.map(r => {
|
||||||
const props = parseLine(r);
|
const props = parseLine(r);
|
||||||
const h = headers || (Array(props.length).fill(null).map((r, i) => {
|
const h = headers || (Array(props.length).fill(null).map((_, i) => {
|
||||||
let letter = '';
|
let letter = '';
|
||||||
const first = i / 26;
|
const first = i / 26;
|
||||||
if(first > 1) letter += LETTER_LIST[Math.floor(first - 1)];
|
if (first > 1) letter += LETTER_LIST[Math.floor(first - 1)];
|
||||||
letter += LETTER_LIST[i % 26];
|
letter += LETTER_LIST[i % 26];
|
||||||
return letter;
|
return letter;
|
||||||
}));
|
}));
|
||||||
@ -34,23 +61,28 @@ export function fromCsv<T = any>(csv: string, hasHeaders=true): T[] {
|
|||||||
dotNotation(acc, h, props[i]);
|
dotNotation(acc, h, props[i]);
|
||||||
return acc;
|
return acc;
|
||||||
}, {});
|
}, {});
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert an object to a CSV string
|
* Convert an array of objects to a CSV string
|
||||||
*
|
*
|
||||||
* @param {any[]} target Array of objects to create CSV from
|
* @param {any[]} target Array of objects to create CSV from
|
||||||
* @param {boolean} flatten Should nested object be flattened or treated as values
|
* @param {boolean} flatten Should nested object be flattened or treated as values
|
||||||
* @return {string} CSV string
|
* @return {string} CSV string
|
||||||
*/
|
*/
|
||||||
export function toCsv(target: any[], flatten=true) {
|
export function toCsv(target: any, flatten=true) {
|
||||||
const headers = new ASet(target.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], []));
|
const t = makeArray(target);
|
||||||
|
const headers = new ASet(t.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], []));
|
||||||
return [
|
return [
|
||||||
headers.join(','),
|
headers.join(','),
|
||||||
...target.map(row => headers.map((h: string) => {
|
...t.map(row => headers.map((h: string) => {
|
||||||
const value = dotNotation<any>(row, h);
|
const value = dotNotation<any>(row, h);
|
||||||
return (typeof value == 'object' && value != null) ? '"' + JSONSanitize(value).replaceAll('"', '""') + '"' : value;
|
if(value == null) return '';
|
||||||
|
if(typeof value == 'object') return `"${JSONSanitize(value).replaceAll('"', '""')}"`;
|
||||||
|
if(typeof value == 'string' && /[\n",]/g.test(value)) return `"${value.replaceAll('"', '""')}"`;
|
||||||
|
return value;
|
||||||
}).join(','))
|
}).join(','))
|
||||||
].join('\n');
|
].join('\n');
|
||||||
}
|
}
|
||||||
|
13
src/http.ts
13
src/http.ts
@ -30,7 +30,13 @@ class HttpResponse<T = any> extends Response {
|
|||||||
url!: string;
|
url!: string;
|
||||||
|
|
||||||
constructor(resp: Response, stream: ReadableStream) {
|
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.ok = resp.ok;
|
||||||
this.redirected = resp.redirected;
|
this.redirected = resp.redirected;
|
||||||
this.type = resp.type;
|
this.type = resp.type;
|
||||||
@ -70,8 +76,9 @@ export class Http {
|
|||||||
|
|
||||||
request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> {
|
request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> {
|
||||||
if(!this.url && !opts.url) throw new Error('URL needs to be set');
|
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');
|
let url = opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '');
|
||||||
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += '#' + opts.fragment;
|
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) {
|
if(opts.query) {
|
||||||
const q = Array.isArray(opts.query) ? opts.query :
|
const q = Array.isArray(opts.query) ? opts.query :
|
||||||
Object.keys(opts.query).map(k => ({key: k, value: (<any>opts.query)[k]}))
|
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 './string';
|
||||||
export * from './time';
|
export * from './time';
|
||||||
export * from './types';
|
export * from './types';
|
||||||
|
export * from 'var-persist';
|
||||||
|
@ -6,7 +6,7 @@ import {JSONAttemptParse} from './objects.ts';
|
|||||||
* @param {string} token JWT to decode
|
* @param {string} token JWT to decode
|
||||||
* @return {unknown} JWT payload
|
* @return {unknown} JWT payload
|
||||||
*/
|
*/
|
||||||
export function jwtDecode<T>(token: string): T {
|
export function decodeJwt<T>(token: string): T {
|
||||||
const base64 = token.split('.')[1]
|
const base64 = token.split('.')[1]
|
||||||
.replace(/-/g, '+').replace(/_/g, '/');
|
.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
return <T>JSONAttemptParse(decodeURIComponent(atob(base64).split('').map(function(c) {
|
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 {PathEvent} from './path-events.ts';
|
||||||
import {md5} from './string';
|
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
|
* Get profile image from Gravatar
|
||||||
*
|
*
|
||||||
|
@ -109,7 +109,6 @@ export function encodeQuery(data: any): string {
|
|||||||
).join('&');
|
).join('&');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recursively flatten a nested object, while maintaining key structure
|
* 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(str[i]) combined.push(str[i]);
|
||||||
if(args[i]) combined.push(args[i]);
|
if(args[i]) combined.push(args[i]);
|
||||||
}
|
}
|
||||||
return new PathEvent(combined.join(''));
|
return new PathEvent(combined.join('/'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -79,16 +79,16 @@ export class PathEvent {
|
|||||||
set none(v: boolean) { v ? this.methods = new ASet<Method>(['n']) : this.methods.delete('n'); }
|
set none(v: boolean) { v ? this.methods = new ASet<Method>(['n']) : this.methods.delete('n'); }
|
||||||
/** Create method specified */
|
/** Create method specified */
|
||||||
get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) }
|
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 */
|
/** Read method specified */
|
||||||
get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) }
|
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 */
|
/** Update method specified */
|
||||||
get update(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('u')) }
|
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 */
|
/** Delete method specified */
|
||||||
get delete(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('d')) }
|
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) {
|
constructor(Event: string | PathEvent) {
|
||||||
if(typeof Event == 'object') return Object.assign(this, Event);
|
if(typeof Event == 'object') return Object.assign(this, Event);
|
||||||
|
@ -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) {
|
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
|
||||||
if(!rows) return [];
|
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()); }
|
try { return RegExp(search, 'gm').test(v.toString()); }
|
||||||
catch { return false; }
|
catch { return false; }
|
||||||
}).length
|
}).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);
|
* Test an object against a logic condition. By default values are checked
|
||||||
return and.filter(p => {
|
* @param {string} condition
|
||||||
// Boolean operator
|
* @param {object} target
|
||||||
const prop = /(\w+)\s*(==?|!=|>=|>|<=|<)\s*(\w+)/g.exec(p);
|
* @return {boolean}
|
||||||
if(prop) {
|
*/
|
||||||
const a = JSON.stringify(JSONAttemptParse(dotNotation<any>(value, prop[1])));
|
export function logicTest(target: object, condition: string): boolean {
|
||||||
const operator = prop[2] == '=' ? '==' : prop[2];
|
const evalBoolean = (a: any, op: string, b: any): boolean => {
|
||||||
const b = JSON.stringify(JSONAttemptParse(prop[3]));
|
switch(op) {
|
||||||
return eval(`${a} ${operator} ${b}`);
|
case '=':
|
||||||
}
|
case '==': return a == b;
|
||||||
// Case-sensitive
|
case '!=': return a != b;
|
||||||
const v = Object.values(value).join('');
|
case '>': return a > b;
|
||||||
if(/[A-Z]/g.test(search)) return v.includes(p);
|
case '>=': return a >= b;
|
||||||
// Case-insensitive
|
case '<': return a < b;
|
||||||
return v.toLowerCase().includes(p);
|
case '<=': return a <= b;
|
||||||
}).length == and.length;
|
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;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -18,6 +18,14 @@ export const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/';
|
|||||||
*/
|
*/
|
||||||
export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST;
|
export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts text to camelCase
|
||||||
|
*/
|
||||||
|
export function camelCase(str?: string) {
|
||||||
|
const text = pascalCase(str);
|
||||||
|
return text[0].toLowerCase() + text.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert number of bytes into a human-readable size
|
* Convert number of bytes into a human-readable size
|
||||||
*
|
*
|
||||||
@ -64,6 +72,17 @@ export function insertAt(target: string, str: string, index: number): String {
|
|||||||
return `${target.slice(0, index)}${str}${target.slice(index + 1)}`;
|
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
|
* Add padding to string
|
||||||
*
|
*
|
||||||
@ -86,6 +105,18 @@ export function pad(text: any, length: number, char: string = ' ', start = true)
|
|||||||
return text.toString().padEnd(length, char);
|
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
|
* Generate a random hexadecimal value
|
||||||
*
|
*
|
||||||
@ -149,6 +180,17 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
|
|||||||
}).join('');
|
}).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)
|
* 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')}`;
|
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
|
// Handle timezones
|
||||||
let t!: [string, number];
|
let t!: [string, number];
|
||||||
|
@ -1,36 +1,18 @@
|
|||||||
import {sleep, parseUrl} from '../src';
|
import {fn} from '../src';
|
||||||
|
|
||||||
describe('Miscellanies Utilities', () => {
|
describe('Miscellanies Utilities', () => {
|
||||||
describe('sleep', () => {
|
describe('fn', () => {
|
||||||
test('wait until', async () => {
|
test('async', async () => {
|
||||||
const wait = ~~(Math.random() * 500);
|
const test = {a: Math.random()};
|
||||||
const time = new Date().getTime();
|
const resp = fn(test, 'return a;', true);
|
||||||
await sleep(wait);
|
expect(resp instanceof Promise).toBeTruthy();
|
||||||
expect(new Date().getTime()).toBeGreaterThanOrEqual(time + wait);
|
expect(await resp).toEqual(test['a']);
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
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');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('advanced URL', () => {
|
test('sync', async () => {
|
||||||
const parsed = parseUrl('https://sub.domain.example.com/some/path?q1=test1&q2=test2#frag');
|
const test = {a: Math.random()};
|
||||||
expect(parsed.protocol).toStrictEqual('https');
|
const resp = fn(test, 'return a;3');
|
||||||
expect(parsed.host).toStrictEqual('sub.domain.example.com');
|
expect(resp).toEqual(test['a']);
|
||||||
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');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import {matchAll, randomString, randomStringBuilder} from "../src";
|
import {matchAll, parseUrl, randomString, randomStringBuilder} from "../src";
|
||||||
|
|
||||||
|
|
||||||
describe('String Utilities', () => {
|
describe('String Utilities', () => {
|
||||||
describe('randomString', () => {
|
describe('randomString', () => {
|
||||||
@ -47,4 +48,28 @@ describe('String Utilities', () => {
|
|||||||
test('using regex', () => expect(matchAll('fooBar fooBar FooBar', /fooBar/g).length).toBe(2));
|
test('using regex', () => expect(matchAll('fooBar fooBar FooBar', /fooBar/g).length).toBe(2));
|
||||||
test('using malformed regex', () => expect(() => matchAll('fooBar fooBar FooBar', /fooBar/)).toThrow());
|
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