Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 92f36fdb5b | |||
| 721fe2dcf8 | |||
| 4dfd70f6a7 | |||
| af5054192e | |||
| b7df327cd5 | |||
| aa652bd7e0 | |||
| e815126807 | |||
| 6319f810b5 | |||
| 91f4abf1f1 | |||
| f9971d7ce1 |
92
package.json
92
package.json
@@ -1,46 +1,46 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.30.0",
|
"version": "0.30.7",
|
||||||
"description": "Utility library",
|
"description": "Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"private": false,
|
"private": false,
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://git.zakscode.com/ztimson/js-utilities"
|
"url": "https://git.zakscode.com/ztimson/js-utilities"
|
||||||
},
|
},
|
||||||
"main": "./dist/index.cjs",
|
"main": "./dist/index.cjs",
|
||||||
"module": "./dist/index.mjs",
|
"module": "./dist/index.mjs",
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
"import": "./dist/index.mjs",
|
"import": "./dist/index.mjs",
|
||||||
"require": "./dist/index.cjs"
|
"require": "./dist/index.cjs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "npx tsc && npx vite build",
|
"build": "npx tsc && npx vite build",
|
||||||
"docs": "typedoc --cleanOutputDir false --out ./docs --entryPoints src/**/*.ts --readme none",
|
"docs": "typedoc --cleanOutputDir false --out ./docs --entryPoints src/**/*.ts --readme none",
|
||||||
"test": "npx jest",
|
"test": "npx jest",
|
||||||
"test:coverage": "npx jest --coverage",
|
"test:coverage": "npx jest --coverage",
|
||||||
"watch": "npx vite build --watch"
|
"watch": "npx vite build --watch"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"var-persist": "^1.0.1"
|
"var-persist": "^1.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"fake-indexeddb": "^6.2.5",
|
"fake-indexeddb": "^6.2.5",
|
||||||
"jest": "^30.2.0",
|
"jest": "^30.2.0",
|
||||||
"jest-junit": "^16.0.0",
|
"jest-junit": "^16.0.0",
|
||||||
"ts-jest": "^29.4.5",
|
"ts-jest": "^29.4.5",
|
||||||
"typedoc": "^0.28.15",
|
"typedoc": "^0.28.15",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^7.2.4",
|
"vite": "^7.2.4",
|
||||||
"vite-plugin-dts": "^4.5.4"
|
"vite-plugin-dts": "^4.5.4"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist"
|
"dist"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export class Cache<K extends string | number | symbol, T> {
|
|||||||
/** Await initial loading */
|
/** Await initial loading */
|
||||||
loading = new Promise<void>(r => this._loading = r);
|
loading = new Promise<void>(r => this._loading = r);
|
||||||
|
|
||||||
|
get size() { return this.store.keys().toArray().length }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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
|
||||||
|
|||||||
65
src/html.ts
Normal file
65
src/html.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
/**
|
||||||
|
* Decode HTML escaped characters
|
||||||
|
* @param html HTML to clean up
|
||||||
|
* @returns {any}
|
||||||
|
*/
|
||||||
|
export function decodeHtml(html: string) {
|
||||||
|
return html
|
||||||
|
.replace(/ /g, '\u00A0')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/¢/g, '¢')
|
||||||
|
.replace(/£/g, '£')
|
||||||
|
.replace(/¥/g, '¥')
|
||||||
|
.replace(/€/g, '€')
|
||||||
|
.replace(/©/g, '©')
|
||||||
|
.replace(/®/g, '®')
|
||||||
|
.replace(/™/g, '™')
|
||||||
|
.replace(/×/g, '×')
|
||||||
|
.replace(/÷/g, '÷')
|
||||||
|
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
|
||||||
|
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
|
||||||
|
.replace(/&/g, '&'); // Always last!
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse markdown headers
|
||||||
|
*
|
||||||
|
* **NOTE: frontmatter parsing only works 2 layers deep**
|
||||||
|
*
|
||||||
|
* @param {string} content
|
||||||
|
* @returns {{meta: any, content: string} | {meta: {}, content: string}}
|
||||||
|
*/
|
||||||
|
export function parseMarkdown(content: string) {
|
||||||
|
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
||||||
|
if (!match) return {meta: {}, content};
|
||||||
|
|
||||||
|
const meta: any = {};
|
||||||
|
let currentParent: string | null = null;
|
||||||
|
|
||||||
|
for (const rawLine of match[1].split('\n')) {
|
||||||
|
if (!rawLine.trim()) continue;
|
||||||
|
const indented = /^\s+/.test(rawLine);
|
||||||
|
const line = rawLine.trim();
|
||||||
|
const colonIdx = line.indexOf(':');
|
||||||
|
if (colonIdx === -1) continue;
|
||||||
|
|
||||||
|
const key = line.slice(0, colonIdx).trim();
|
||||||
|
const value = line.slice(colonIdx + 1).trim();
|
||||||
|
|
||||||
|
let parsed: any = value;
|
||||||
|
try { parsed = JSON.parse(value); } catch {}
|
||||||
|
|
||||||
|
if (!indented) {
|
||||||
|
currentParent = value === '' ? key : null;
|
||||||
|
if (value === '') meta[key] = {};
|
||||||
|
else meta[key] = parsed;
|
||||||
|
} else if (currentParent) {
|
||||||
|
meta[currentParent][key] = parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {meta, content: match[2].trim()};
|
||||||
|
}
|
||||||
@@ -7,10 +7,12 @@ export * from './cache';
|
|||||||
export * from './color';
|
export * from './color';
|
||||||
export * from './csv';
|
export * from './csv';
|
||||||
export * from './database';
|
export * from './database';
|
||||||
export * from './files';
|
|
||||||
export * from './emitter';
|
export * from './emitter';
|
||||||
export * from './errors';
|
export * from './errors';
|
||||||
|
export * from './files';
|
||||||
|
export * from './html';
|
||||||
export * from './http';
|
export * from './http';
|
||||||
|
export * from './ip';
|
||||||
export * from './json';
|
export * from './json';
|
||||||
export * from './jwt';
|
export * from './jwt';
|
||||||
export * from './logger';
|
export * from './logger';
|
||||||
|
|||||||
77
src/ip.ts
Normal file
77
src/ip.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
/**
|
||||||
|
* Check if IP address falls within any of the given CIDR ranges
|
||||||
|
* @param {string} ip IPV4 to check (192.168.0.12)
|
||||||
|
* @param {...string} cidrs IP ranges to check against (example: 192.168.0.0/24)
|
||||||
|
* @returns {boolean} Whether IP address is within any range
|
||||||
|
*/
|
||||||
|
export function matchesCidr(ip: string, ...cidrs: string[]): boolean {
|
||||||
|
if (!ip) return false;
|
||||||
|
if (!cidrs.length) return true;
|
||||||
|
const ipToInt = (str: string) => str.split('.')
|
||||||
|
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
|
||||||
|
return cidrs.some(cidr => {
|
||||||
|
if (!cidr) return true;
|
||||||
|
if (!cidr.includes('/')) return ip === cidr; // Single IP
|
||||||
|
const [range, bits] = cidr.split('/');
|
||||||
|
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
|
||||||
|
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert IPv6 to v4 because who uses that, NAT4Life
|
||||||
|
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
|
||||||
|
* @returns {string | null} IPv4 address, e.g. 172.16.58.3
|
||||||
|
*/
|
||||||
|
export function ipV6ToV4(ip: string) {
|
||||||
|
if(!ip) return null;
|
||||||
|
const ipv4 = ip.split(':').splice(-1)[0];
|
||||||
|
if(ipv4 == '1') return '127.0.0.1';
|
||||||
|
return ipv4;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use isReserved
|
||||||
|
*
|
||||||
|
* Check if IP is reserved, e.g. localhost, private IPs, etc.
|
||||||
|
* @param {string} ip
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function reservedIp(ip: string): boolean {
|
||||||
|
if(ip == 'localhost' || ip == '127.0.0.1') return true;
|
||||||
|
return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if IP is within a reserved range
|
||||||
|
* @param {string} ip
|
||||||
|
* @returns {null | 'Invalid' | 'Host' | 'Loopback' | 'Private (Class A)' | 'Private (Class B)' | 'Link-Local' | 'IETF Protocol Assignments' | 'Documentation (TEST-NET-1)' | 'Benchmarking' | 'Documentation (TEST-NET-2)' | 'Documentation (TEST-NET-3)' | 'Multicast' | 'Reserved (Class E)'} null if public, class name if reserved
|
||||||
|
*/
|
||||||
|
export function isReserved(ip: string): null | 'Invalid' | 'Host' | 'Loopback' | 'Private (Class A)' | 'Private (Class B)' | 'Link-Local' | 'IETF Protocol Assignments' | 'Documentation (TEST-NET-1)' | 'Benchmarking' | 'Documentation (TEST-NET-2)' | 'Documentation (TEST-NET-3)' | 'Multicast' | 'Reserved (Class E)' {
|
||||||
|
const ipToNumber = (ip: string) => {
|
||||||
|
return ip.split('.').reduce((acc: number, octet: string) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ipNum = ipToNumber(ip);
|
||||||
|
if (ipNum === null) return 'Invalid';
|
||||||
|
|
||||||
|
const reserved = [
|
||||||
|
{ name: "Host", start: ipToNumber("0.0.0.0"), end: ipToNumber("0.255.255.255") },
|
||||||
|
{ name: "Loopback", start: ipToNumber("127.0.0.0"), end: ipToNumber("127.255.255.255") },
|
||||||
|
{ name: "Private (Class A)", start: ipToNumber("10.0.0.0"), end: ipToNumber("10.255.255.255") },
|
||||||
|
{ name: "CGNAT", start: ipToNumber("100.64.0.0"), end: ipToNumber("100.127.255.255") },
|
||||||
|
{ name: "Private (Class B)", start: ipToNumber("172.16.0.0"), end: ipToNumber("172.31.255.255") },
|
||||||
|
{ name: "Private (Class C)", start: ipToNumber("192.168.0.0"), end: ipToNumber("192.168.255.255") },
|
||||||
|
{ name: "Link-Local", start: ipToNumber("169.254.0.0"), end: ipToNumber("169.254.255.255") },
|
||||||
|
{ name: "IETF Protocol Assignments", start: ipToNumber("192.0.0.0"), end: ipToNumber("192.0.0.255") },
|
||||||
|
{ name: "Documentation (TEST-NET-1)", start: ipToNumber("192.0.2.0"), end: ipToNumber("192.0.2.255") },
|
||||||
|
{ name: "Benchmarking", start: ipToNumber("198.18.0.0"), end: ipToNumber("198.19.255.255") },
|
||||||
|
{ name: "Documentation (TEST-NET-2)", start: ipToNumber("198.51.100.0"), end: ipToNumber("198.51.100.255") },
|
||||||
|
{ name: "Documentation (TEST-NET-3)", start: ipToNumber("203.0.113.0"), end: ipToNumber("203.0.113.255") },
|
||||||
|
{ name: "Multicast", start: ipToNumber("224.0.0.0"), end: ipToNumber("239.255.255.255") },
|
||||||
|
{ name: "Reserved (Class E)", start: ipToNumber("240.0.0.0"), end: ipToNumber("255.255.255.255") }
|
||||||
|
];
|
||||||
|
|
||||||
|
const match = reserved.find(r => ipNum >= r.start && ipNum <= r.end);
|
||||||
|
return match ? <any>match.name : null;
|
||||||
|
}
|
||||||
40
src/misc.ts
40
src/misc.ts
@@ -76,46 +76,6 @@ export function gravatar(email: string, def='mp') {
|
|||||||
return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
|
return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if IP address falls within CIDR range
|
|
||||||
* @param {string} ip IPV4 to check (192.168.0.12)
|
|
||||||
* @param {string} cidr IP range to check against (example: 192.168.0.0/24)
|
|
||||||
* @returns {boolean} Whether IP address is within range
|
|
||||||
*/
|
|
||||||
export function matchesCidr(ip: string, cidr: string): boolean {
|
|
||||||
if(!cidr) return true;
|
|
||||||
if(!ip) return false;
|
|
||||||
if(!cidr?.includes('/')) return ip === cidr; // Single IP
|
|
||||||
const [range, bits] = cidr.split('/');
|
|
||||||
const mask = ~(2 ** (32 - parseInt(bits)) - 1);
|
|
||||||
const ipToInt = (str: string) => str.split('.')
|
|
||||||
.reduce((int, octet) => (int << 8) + parseInt(octet), 0) >>> 0;
|
|
||||||
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert IPv6 to v4 because who uses that, NAT4Life
|
|
||||||
* @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
|
|
||||||
* @returns {string | null} IPv4 address, e.g. 172.16.58.3
|
|
||||||
*/
|
|
||||||
export function ipV6ToV4(ip: string) {
|
|
||||||
if(!ip) return null;
|
|
||||||
const ipv4 = ip.split(':').splice(-1)[0];
|
|
||||||
if(ipv4 == '1') return '127.0.0.1';
|
|
||||||
return ipv4;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if IP is reserved, e.g. localhost, private IPs, etc.
|
|
||||||
* @param {string} ip
|
|
||||||
* @returns {boolean}
|
|
||||||
*/
|
|
||||||
export function reservedIp(ip: string): boolean {
|
|
||||||
if(ip == 'localhost' || ip == '127.0.0.1') return true;
|
|
||||||
return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a function that listens for events and handles them accordingly.
|
* Represents a function that listens for events and handles them accordingly.
|
||||||
*
|
*
|
||||||
|
|||||||
620
src/objects.ts
620
src/objects.ts
@@ -1,309 +1,311 @@
|
|||||||
import {JSONSanitize} from './json.ts';
|
import {JSONSanitize} from './json.ts';
|
||||||
|
|
||||||
export type Delta = { [key: string]: any | Delta | null };
|
export type Delta = { [key: string]: any | Delta | null };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Applies deltas to `target`.
|
* Applies deltas to `target`.
|
||||||
* @param base starting point
|
* @param base starting point
|
||||||
* @param deltas List of deltas to apply
|
* @param deltas List of deltas to apply
|
||||||
* @returns Mutated target
|
* @returns Mutated target
|
||||||
*/
|
*/
|
||||||
export function applyDeltas(base: any, ...deltas: any[]): any {
|
export function applyDeltas(base: any, ...deltas: any[]): any {
|
||||||
function applyDelta(base: any, delta: any): any {
|
function applyDelta(base: any, delta: any): any {
|
||||||
if(delta === null) return null;
|
if(delta === null) return null;
|
||||||
if(typeof base !== 'object' || base === null) return delta === undefined ? base : delta;
|
if(typeof base !== 'object' || base === null) return delta === undefined ? base : delta;
|
||||||
const result = Array.isArray(base) ? [...base] : { ...base };
|
const result = Array.isArray(base) ? [...base] : { ...base };
|
||||||
for(const key in delta) {
|
for(const key in delta) {
|
||||||
const val = delta[key];
|
const val = delta[key];
|
||||||
if(val === undefined) delete result[key];
|
if(val === undefined) delete result[key];
|
||||||
else if(typeof val === 'object' && val !== null && !Array.isArray(val)) result[key] = applyDelta(result[key], val);
|
else if(typeof val === 'object' && val !== null && !Array.isArray(val)) result[key] = applyDelta(result[key], val);
|
||||||
else result[key] = val;
|
else result[key] = val;
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
for(const d of deltas.flat()) base = applyDelta(base, d?.delta ?? d);
|
for(const d of deltas.flat()) base = applyDelta(base, d?.delta ?? d);
|
||||||
return base;
|
return base;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a nested delta that reverts `target` back to `old`.
|
* Creates a nested delta that reverts `target` back to `old`.
|
||||||
* @param old - Original object
|
* @param old - Original object
|
||||||
* @param updated - Modified object
|
* @param updated - Modified object
|
||||||
* @returns New changes
|
* @returns New changes
|
||||||
*/
|
*/
|
||||||
export function calcDelta(old: any, updated: any): any {
|
export function calcDelta(old: any, updated: any): any {
|
||||||
if(updated == null) return null; // full delete
|
if(updated == null) return null; // full delete
|
||||||
const delta: any = {};
|
const delta: any = {};
|
||||||
const isObj = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
|
const isObj = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
|
||||||
for (const key of new Set([...(old ? Object.keys(old) : []), ...(updated ? Object.keys(updated) : [])])) {
|
for (const key of new Set([...(old ? Object.keys(old) : []), ...(updated ? Object.keys(updated) : [])])) {
|
||||||
const oldVal = old?.[key];
|
const oldVal = old?.[key];
|
||||||
const newVal = updated?.[key];
|
const newVal = updated?.[key];
|
||||||
if(isObj(oldVal) && isObj(newVal)) {
|
if(isObj(oldVal) && isObj(newVal)) {
|
||||||
const nested = calcDelta(oldVal, newVal);
|
const nested = calcDelta(oldVal, newVal);
|
||||||
if(nested !== null && Object.keys(nested).length > 0) delta[key] = nested;
|
if(nested !== null && Object.keys(nested).length > 0) delta[key] = nested;
|
||||||
} else if(JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
|
} else if(JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
|
||||||
delta[key] = newVal;
|
delta[key] = newVal;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Object.keys(delta).length === 0 ? {} : delta;
|
return Object.keys(delta).length === 0 ? {} : delta;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes any null values from an object in-place
|
* Removes any null values from an object in-place
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* ```ts
|
* ```ts
|
||||||
* let test = {a: 0, b: false, c: null, d: 'abc'}
|
* let test = {a: 0, b: false, c: null, d: 'abc'}
|
||||||
* console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
|
* console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* @param {T} obj Object reference that will be cleaned
|
* @param {T} obj Object reference that will be cleaned
|
||||||
* @param undefinedOnly Ignore null values
|
* @param undefinedOnly Ignore null values
|
||||||
* @returns {Partial<T>} Cleaned object
|
* @returns {Partial<T>} Cleaned object
|
||||||
*/
|
*/
|
||||||
export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
|
export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
|
||||||
if(obj == null) throw new Error("Cannot clean a NULL value");
|
if(obj == null) throw new Error("Cannot clean a NULL value");
|
||||||
if(Array.isArray(obj)) {
|
if(Array.isArray(obj)) {
|
||||||
obj = <any>obj.filter(o => undefinedOnly ? o !== undefined : o != null);
|
obj = <any>obj.filter(o => undefinedOnly ? o !== undefined : o != null);
|
||||||
} else {
|
} else {
|
||||||
Object.entries(obj).forEach(([key, value]) => {
|
Object.entries(obj).forEach(([key, value]) => {
|
||||||
if((undefinedOnly && value === undefined) || (!undefinedOnly && value == null)) delete (<any>obj)[key];
|
if((undefinedOnly && value === undefined) || (!undefinedOnly && value == null)) delete (<any>obj)[key];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return <any>obj;
|
return <any>obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a deep copy of an object (vs. a shallow copy of references)
|
* Create a deep copy of an object (vs. a shallow copy of references)
|
||||||
*
|
*
|
||||||
* Should be replaced by `structuredClone` once released.
|
* Should be replaced by `structuredClone` once released.
|
||||||
* @param {T} value Object to copy
|
* @param {T} value Object to copy
|
||||||
* @returns {T} Type
|
* @returns {T} Type
|
||||||
*/
|
*/
|
||||||
export function deepCopy<T>(value: T): T {
|
export function deepCopy<T>(value: T): T {
|
||||||
if(value == null) return value;
|
if(value == null) return value;
|
||||||
const t = typeof value;
|
const t = typeof value;
|
||||||
if(t === 'string' || t === 'number' || t === 'boolean' || t === 'function') return value;
|
if(t === 'string' || t === 'number' || t === 'boolean' || t === 'function') return value;
|
||||||
try {return structuredClone(value); }
|
try {return structuredClone(value); }
|
||||||
catch { return JSON.parse(JSONSanitize(value)); }
|
catch { return JSON.parse(JSONSanitize(value)); }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Merge any number of objects into the target
|
* Merge any number of objects into the target
|
||||||
*
|
*
|
||||||
* @param target Destination of all properties
|
* @param target Destination of all properties
|
||||||
* @param sources Objects that will copied into target
|
* @param sources Objects that will copied into target
|
||||||
* @return {any} The des
|
* @return {any} The des
|
||||||
*/
|
*/
|
||||||
export function deepMerge<T>(target: any, ...sources: any[]): T {
|
export function deepMerge<T>(target: any, ...sources: any[]): T {
|
||||||
sources.forEach(s => {
|
const BLOCKED = new Set(['__proto__', 'constructor', 'prototype']);
|
||||||
for(const key in s) {
|
sources.forEach(s => {
|
||||||
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
|
for(const key in s) {
|
||||||
if(!target[key]) target[key] = {};
|
if(BLOCKED.has(key) || !Object.prototype.hasOwnProperty.call(s, key)) continue;
|
||||||
deepMerge(target[key], s[key]);
|
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
|
||||||
} else {
|
if(!target[key]) target[key] = {};
|
||||||
target[key] = s[key];
|
deepMerge(target[key], s[key]);
|
||||||
}
|
} else {
|
||||||
}
|
target[key] = s[key];
|
||||||
});
|
}
|
||||||
return target;
|
}
|
||||||
}
|
});
|
||||||
|
return target;
|
||||||
/**
|
}
|
||||||
* Get/set a property of an object using dot notation
|
|
||||||
*
|
/**
|
||||||
* @example
|
* Get/set a property of an object using dot notation
|
||||||
* ```ts
|
*
|
||||||
* // Get a value
|
* @example
|
||||||
* const name = dotNotation<string>(person, 'firstName');
|
* ```ts
|
||||||
* const familyCarMake = dotNotation(family, 'cars[0].make');
|
* // Get a value
|
||||||
* // Set a value
|
* const name = dotNotation<string>(person, 'firstName');
|
||||||
* dotNotation(family, 'cars[0].make', 'toyota');
|
* const familyCarMake = dotNotation(family, 'cars[0].make');
|
||||||
* ```
|
* // Set a value
|
||||||
*
|
* dotNotation(family, 'cars[0].make', 'toyota');
|
||||||
* @type T Return type
|
* ```
|
||||||
* @param {Object} obj source object to search
|
*
|
||||||
* @param {string} prop property name (Dot notation & indexing allowed)
|
* @type T Return type
|
||||||
* @param {any} set Set object property to value, omit to fetch value instead
|
* @param {Object} obj source object to search
|
||||||
* @return {T} property value
|
* @param {string} prop property name (Dot notation & indexing allowed)
|
||||||
*/
|
* @param {any} set Set object property to value, omit to fetch value instead
|
||||||
export function dotNotation<T>(obj: any, prop: string, set: T): T;
|
* @return {T} property value
|
||||||
export function dotNotation<T>(obj: any, prop: string): T | undefined;
|
*/
|
||||||
export function dotNotation<T>(obj: any, prop: string, set?: T): T | undefined {
|
export function dotNotation<T>(obj: any, prop: string, set: T): T;
|
||||||
if(obj == null || !prop) return undefined;
|
export function dotNotation<T>(obj: any, prop: string): T | undefined;
|
||||||
// Split property string by '.' or [index]
|
export function dotNotation<T>(obj: any, prop: string, set?: T): T | undefined {
|
||||||
return <T>prop.split(/[.[\]]/g).filter(prop => prop.length).reduce((obj, prop, i, arr) => {
|
if(obj == null || !prop) return undefined;
|
||||||
if(prop[0] == '"' || prop[0] == "'") prop = prop.slice(1, -1); // Take quotes out
|
// Split property string by '.' or [index]
|
||||||
if(!obj?.hasOwnProperty(prop)) {
|
return <T>prop.split(/[.[\]]/g).filter(prop => prop.length).reduce((obj, prop, i, arr) => {
|
||||||
if(set == undefined) return undefined;
|
if(prop[0] == '"' || prop[0] == "'") prop = prop.slice(1, -1); // Take quotes out
|
||||||
obj[prop] = {};
|
if(!obj?.hasOwnProperty(prop)) {
|
||||||
}
|
if(set == undefined) return undefined;
|
||||||
if(set !== undefined && i == arr.length - 1)
|
obj[prop] = {};
|
||||||
return obj[prop] = set;
|
}
|
||||||
return obj[prop];
|
if(set !== undefined && i == arr.length - 1)
|
||||||
}, obj);
|
return obj[prop] = set;
|
||||||
}
|
return obj[prop];
|
||||||
|
}, obj);
|
||||||
/**
|
}
|
||||||
* Convert object into URL encoded query string
|
|
||||||
*
|
/**
|
||||||
* @example
|
* Convert object into URL encoded query string
|
||||||
* ```js
|
*
|
||||||
* const query = encodeQuery({page: 1, size: 20});
|
* @example
|
||||||
* console.log(query); // Output: "page=1&size=20"
|
* ```js
|
||||||
* ```
|
* const query = encodeQuery({page: 1, size: 20});
|
||||||
*
|
* console.log(query); // Output: "page=1&size=20"
|
||||||
* @param {any} data - data to convert
|
* ```
|
||||||
* @returns {string} - Encoded form data
|
*
|
||||||
*/
|
* @param {any} data - data to convert
|
||||||
export function encodeQuery(data: any): string {
|
* @returns {string} - Encoded form data
|
||||||
return Object.entries(data).map(([key, value]) =>
|
*/
|
||||||
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
|
export function encodeQuery(data: any): string {
|
||||||
).join('&');
|
return Object.entries(data).map(([key, value]) =>
|
||||||
}
|
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
|
||||||
|
).join('&');
|
||||||
/**
|
}
|
||||||
* Recursively flatten a nested object, while maintaining key structure
|
|
||||||
*
|
/**
|
||||||
* @example
|
* Recursively flatten a nested object, while maintaining key structure
|
||||||
* ```ts
|
*
|
||||||
* const car = {honda: {model: "Civic"}};
|
* @example
|
||||||
* console.log(flattenObj(car)); //Output {honda.model: "Civic"}
|
* ```ts
|
||||||
* ```
|
* const car = {honda: {model: "Civic"}};
|
||||||
*
|
* console.log(flattenObj(car)); //Output {honda.model: "Civic"}
|
||||||
* @param obj - Object to flatten
|
* ```
|
||||||
* @param parent - Recursively check if key is a parent key or not
|
*
|
||||||
* @param result - Result
|
* @param obj - Object to flatten
|
||||||
* @returns {object} - Flattened object
|
* @param parent - Recursively check if key is a parent key or not
|
||||||
*/
|
* @param result - Result
|
||||||
export function flattenObj(obj: any, parent?: any, result: any = {}) {
|
* @returns {object} - Flattened object
|
||||||
if(typeof obj === "object" && !Array.isArray(obj)) {
|
*/
|
||||||
for(const key of Object.keys(obj)) {
|
export function flattenObj(obj: any, parent?: any, result: any = {}) {
|
||||||
const propName = parent ? `${parent}.${key}` : key;
|
if(typeof obj === "object" && !Array.isArray(obj)) {
|
||||||
if(typeof obj[key] === 'object' && obj[key] != null && !Array.isArray(obj[key])) {
|
for(const key of Object.keys(obj)) {
|
||||||
flattenObj(obj[key], propName, result);
|
const propName = parent ? `${parent}.${key}` : key;
|
||||||
} else {
|
if(typeof obj[key] === 'object' && obj[key] != null && !Array.isArray(obj[key])) {
|
||||||
result[propName] = obj[key];
|
flattenObj(obj[key], propName, result);
|
||||||
}
|
} else {
|
||||||
}
|
result[propName] = obj[key];
|
||||||
return result;
|
}
|
||||||
}
|
}
|
||||||
}
|
return result;
|
||||||
|
}
|
||||||
/**
|
}
|
||||||
* Convert object to FormData
|
|
||||||
*
|
/**
|
||||||
* @param target - Object to convert
|
* Convert object to FormData
|
||||||
* @return {FormData} - Form object
|
*
|
||||||
*/
|
* @param target - Object to convert
|
||||||
export function formData(target: any): FormData {
|
* @return {FormData} - Form object
|
||||||
const data = new FormData();
|
*/
|
||||||
Object.entries(target).forEach(([key, value]) => data.append(key, <any>value));
|
export function formData(target: any): FormData {
|
||||||
return data;
|
const data = new FormData();
|
||||||
}
|
Object.entries(target).forEach(([key, value]) => data.append(key, <any>value));
|
||||||
|
return data;
|
||||||
/**
|
}
|
||||||
* Check that an object has the following values
|
|
||||||
*
|
/**
|
||||||
* @example
|
* Check that an object has the following values
|
||||||
* ```ts
|
*
|
||||||
* const test = {a: 2, b: 2};
|
* @example
|
||||||
* includes(test, {a: 1}); // true
|
* ```ts
|
||||||
* includes(test, {b: 1, c: 3}); // false
|
* const test = {a: 2, b: 2};
|
||||||
* ```
|
* includes(test, {a: 1}); // true
|
||||||
*
|
* includes(test, {b: 1, c: 3}); // false
|
||||||
* @param target Object to search
|
* ```
|
||||||
* @param values Criteria to check against
|
*
|
||||||
* @param allowMissing Only check the keys that are available on the target
|
* @param target Object to search
|
||||||
* @returns {boolean} Does target include all the values
|
* @param values Criteria to check against
|
||||||
*/
|
* @param allowMissing Only check the keys that are available on the target
|
||||||
export function includes(target: any, values: any, allowMissing = false): boolean {
|
* @returns {boolean} Does target include all the values
|
||||||
if(target == undefined) return allowMissing;
|
*/
|
||||||
if(Array.isArray(values)) return values.findIndex((e: any, i: number) => !includes(target[i], values[i], allowMissing)) == -1;
|
export function includes(target: any, values: any, allowMissing = false): boolean {
|
||||||
const type = typeof values;
|
if(target == undefined) return allowMissing;
|
||||||
if(type != typeof target) return false;
|
if(Array.isArray(values)) return values.findIndex((e: any, i: number) => !includes(target[i], values[i], allowMissing)) == -1;
|
||||||
if(type == 'object') {
|
const type = typeof values;
|
||||||
return Object.keys(values).find(key => !includes(target[key], values[key], allowMissing)) == null;
|
if(type != typeof target) return false;
|
||||||
}
|
if(type == 'object') {
|
||||||
if(type == 'function') return target.toString() == values.toString();
|
return Object.keys(values).find(key => !includes(target[key], values[key], allowMissing)) == null;
|
||||||
return target == values;
|
}
|
||||||
}
|
if(type == 'function') return target.toString() == values.toString();
|
||||||
|
return target == values;
|
||||||
/**
|
}
|
||||||
* Deep check if two items are equal.
|
|
||||||
* Handles primitives, objects, arrays, functions, Date, RegExp, and circular references.
|
/**
|
||||||
*
|
* Deep check if two items are equal.
|
||||||
* @param {any} a - first item to compare
|
* Handles primitives, objects, arrays, functions, Date, RegExp, and circular references.
|
||||||
* @param {any} b - second item to compare
|
*
|
||||||
* @param {WeakMap<object, object>} [seen] - Internal parameter to track circular references
|
* @param {any} a - first item to compare
|
||||||
* @returns {boolean} True if they match
|
* @param {any} b - second item to compare
|
||||||
*/
|
* @param {WeakMap<object, object>} [seen] - Internal parameter to track circular references
|
||||||
export function isEqual(a: any, b: any, seen = new WeakMap<object, object>()): boolean {
|
* @returns {boolean} True if they match
|
||||||
// Simple cases
|
*/
|
||||||
if(a === b) return true;
|
export function isEqual(a: any, b: any, seen = new WeakMap<object, object>()): boolean {
|
||||||
if(a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
// Simple cases
|
||||||
if(a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
|
if(a === b) return true;
|
||||||
|
if(a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
||||||
// Null checks
|
if(a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
|
||||||
if(typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
|
||||||
if(Number.isNaN(a) && Number.isNaN(b)) return true;
|
// Null checks
|
||||||
if(typeof a === 'function' && typeof b === 'function') return a.toString() === b.toString()
|
if(typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
||||||
return false;
|
if(Number.isNaN(a) && Number.isNaN(b)) return true;
|
||||||
}
|
if(typeof a === 'function' && typeof b === 'function') return a.toString() === b.toString()
|
||||||
|
return false;
|
||||||
// Circular references
|
}
|
||||||
if(seen.has(a)) return seen.get(a) === b;
|
|
||||||
seen.set(a, b);
|
// Circular references
|
||||||
const isArrayA = Array.isArray(a);
|
if(seen.has(a)) return seen.get(a) === b;
|
||||||
const isArrayB = Array.isArray(b);
|
seen.set(a, b);
|
||||||
|
const isArrayA = Array.isArray(a);
|
||||||
// Array checks
|
const isArrayB = Array.isArray(b);
|
||||||
if(isArrayA && isArrayB) {
|
|
||||||
if(a.length !== b.length) return false;
|
// Array checks
|
||||||
for(let i = 0; i < a.length; i++) {
|
if(isArrayA && isArrayB) {
|
||||||
if(!isEqual(a[i], b[i], seen)) return false;
|
if(a.length !== b.length) return false;
|
||||||
}
|
for(let i = 0; i < a.length; i++) {
|
||||||
return true;
|
if(!isEqual(a[i], b[i], seen)) return false;
|
||||||
}
|
}
|
||||||
if(isArrayA !== isArrayB) return false;
|
return true;
|
||||||
|
}
|
||||||
// Key & value deep comparison
|
if(isArrayA !== isArrayB) return false;
|
||||||
const keysA = Object.keys(a);
|
|
||||||
const keysB = Object.keys(b);
|
// Key & value deep comparison
|
||||||
if(keysA.length !== keysB.length) return false;
|
const keysA = Object.keys(a);
|
||||||
for(const key of keysA) {
|
const keysB = Object.keys(b);
|
||||||
if(!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key], seen)) return false;
|
if(keysA.length !== keysB.length) return false;
|
||||||
}
|
for(const key of keysA) {
|
||||||
return true;
|
if(!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key], seen)) return false;
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
/**
|
}
|
||||||
* Experimental: Combine multiple object prototypes into one
|
|
||||||
*
|
/**
|
||||||
* @param target Object that will have prototypes added
|
* Experimental: Combine multiple object prototypes into one
|
||||||
* @param {any[]} constructors Additionally prototypes that should be merged into target
|
*
|
||||||
*/
|
* @param target Object that will have prototypes added
|
||||||
export function mixin(target: any, constructors: any[]) {
|
* @param {any[]} constructors Additionally prototypes that should be merged into target
|
||||||
constructors.forEach(c => {
|
*/
|
||||||
Object.getOwnPropertyNames(c.prototype).forEach((name) => {
|
export function mixin(target: any, constructors: any[]) {
|
||||||
Object.defineProperty(
|
constructors.forEach(c => {
|
||||||
target.prototype,
|
Object.getOwnPropertyNames(c.prototype).forEach((name) => {
|
||||||
name,
|
Object.defineProperty(
|
||||||
Object.getOwnPropertyDescriptor(c.prototype, name) ||
|
target.prototype,
|
||||||
Object.create(null)
|
name,
|
||||||
);
|
Object.getOwnPropertyDescriptor(c.prototype, name) ||
|
||||||
});
|
Object.create(null)
|
||||||
});
|
);
|
||||||
}
|
});
|
||||||
|
});
|
||||||
/**
|
}
|
||||||
* Run a map function on each property
|
|
||||||
* @param obj Object that will be iterated
|
/**
|
||||||
* @param {(key: string, value: any) => any} fn Transformer function - receives key & value
|
* Run a map function on each property
|
||||||
* @returns {{}}
|
* @param obj Object that will be iterated
|
||||||
*/
|
* @param {(key: string, value: any) => any} fn Transformer function - receives key & value
|
||||||
export function objectMap<T>(obj: any, fn: (key: string, value: any) => any): T {
|
* @returns {{}}
|
||||||
return <any>Object.entries(obj).map(([key, value]: [string, any]) => [key, fn(key, value)])
|
*/
|
||||||
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
|
export function objectMap<T>(obj: any, fn: (key: string, value: any) => any): T {
|
||||||
}
|
return <any>Object.entries(obj).map(([key, value]: [string, any]) => [key, fn(key, value)])
|
||||||
|
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
|
||||||
|
}
|
||||||
|
|||||||
@@ -27,32 +27,6 @@ export function camelCase(str?: string): string {
|
|||||||
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
|
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Decode HTML escaped characters
|
|
||||||
* @param html HTML to clean up
|
|
||||||
* @returns {any}
|
|
||||||
*/
|
|
||||||
export function decodeHtml(html: string) {
|
|
||||||
return html
|
|
||||||
.replace(/ /g, '\u00A0')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, "'")
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/¢/g, '¢')
|
|
||||||
.replace(/£/g, '£')
|
|
||||||
.replace(/¥/g, '¥')
|
|
||||||
.replace(/€/g, '€')
|
|
||||||
.replace(/©/g, '©')
|
|
||||||
.replace(/®/g, '®')
|
|
||||||
.replace(/™/g, '™')
|
|
||||||
.replace(/×/g, '×')
|
|
||||||
.replace(/÷/g, '÷')
|
|
||||||
.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
|
|
||||||
.replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)))
|
|
||||||
.replace(/&/g, '&'); // Always last!
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert number of bytes into a human-readable size
|
* Convert number of bytes into a human-readable size
|
||||||
*
|
*
|
||||||
@@ -125,7 +99,6 @@ export function kebabCase(str?: string): string {
|
|||||||
return wordSegments(str).map(w => w.toLowerCase()).join("-");
|
return wordSegments(str).map(w => w.toLowerCase()).join("-");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add padding to string
|
* Add padding to string
|
||||||
*
|
*
|
||||||
@@ -256,18 +229,14 @@ export function strSplice(str: string, start: number, deleteCount: number, inser
|
|||||||
return before + insert + after;
|
return before + insert + after;
|
||||||
}
|
}
|
||||||
|
|
||||||
function titleCase(str: string) {
|
/**
|
||||||
// Normalize separators: replace underscores and hyphens with spaces
|
* Converts text to Title Case
|
||||||
let normalizedStr = str.replace(/(_|-)/g, ' ');
|
*/
|
||||||
// Handle CamelCase/PascalCase boundaries: insert a space before capital letters
|
export function titleCase(str?: string): string {
|
||||||
normalizedStr = normalizedStr.replace(/([a-z])([A-Z])/g, '$1 $2');
|
if(!str) return '';
|
||||||
// Lowercase the whole string, split by any whitespace, and capitalize each word
|
return wordSegments(str)
|
||||||
let words = normalizedStr.toLowerCase().split(/\s+/).filter(Boolean);
|
.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
|
||||||
const titledWords = words.map(word => {
|
.join(' ');
|
||||||
if (word.length === 0) return '';
|
|
||||||
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
|
|
||||||
});
|
|
||||||
return titledWords.join(' ');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -280,19 +249,16 @@ function titleCase(str: string) {
|
|||||||
* @return {RegExpExecArray[]} Found matches.
|
* @return {RegExpExecArray[]} Found matches.
|
||||||
*/
|
*/
|
||||||
export function matchAll(value: string, regex: RegExp | string): RegExpExecArray[] {
|
export function matchAll(value: string, regex: RegExp | string): RegExpExecArray[] {
|
||||||
if(typeof regex === 'string') {
|
if(typeof regex === 'string') regex = new RegExp(regex, 'g');
|
||||||
regex = new RegExp(regex, 'g');
|
if(!regex.global) throw new TypeError('Regular expression must be global.');
|
||||||
}
|
|
||||||
|
|
||||||
// https://stackoverflow.com/a/60290199
|
|
||||||
if(!regex.global) {
|
|
||||||
throw new TypeError('Regular expression must be global.');
|
|
||||||
}
|
|
||||||
|
|
||||||
let ret: RegExpExecArray[] = [];
|
let ret: RegExpExecArray[] = [];
|
||||||
let match: RegExpExecArray | null;
|
let match: RegExpExecArray | null;
|
||||||
while((match = regex.exec(value)) !== null) {
|
while((match = regex.exec(value)) !== null) {
|
||||||
ret.push(match);
|
ret.push(match);
|
||||||
|
if(match[0].length === 0) {
|
||||||
|
regex.lastIndex++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
|
|||||||
Reference in New Issue
Block a user