Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
3fd5c5ed57 | |||
2e4559d805 | |||
95f8d5762c | |||
3bc82fab45 | |||
6b15848896 | |||
9a0f32323e | |||
f952abc95a | |||
21fc1378b8 | |||
a03567eba3 | |||
f9fc4fb7ff | |||
ff16f3bf9b | |||
e0085ecb6f | |||
1c2c18b65d | |||
cd5741d6ab | |||
5b9e0714ce | |||
a3b34ef03f | |||
f755d8f5b8 | |||
35c471eef4 |
106
index.html
106
index.html
@ -1,14 +1,104 @@
|
||||
<!Doctype html>
|
||||
|
||||
<html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>@ztimson/utils sandbox</title>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>About Us | OurTrainingRoom</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background-color: #fdfdfd;
|
||||
color: #333;
|
||||
line-height: 1.6;
|
||||
}
|
||||
header {
|
||||
background: #004080;
|
||||
color: #fff;
|
||||
padding: 2rem 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
header h1 {
|
||||
margin: 0;
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
main {
|
||||
max-width: 800px;
|
||||
margin: 2rem auto;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
section {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
h2 {
|
||||
color: #004080;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
ul {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
footer {
|
||||
text-align: center;
|
||||
font-size: 0.9rem;
|
||||
color: #777;
|
||||
padding: 2rem 1rem;
|
||||
background: #f1f1f1;
|
||||
margin-top: 4rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script type="module">
|
||||
import {formatDate} from './dist/index.mjs';
|
||||
<header>
|
||||
<h1>About Us</h1>
|
||||
<p>Empowering Learning Through Innovation</p>
|
||||
</header>
|
||||
|
||||
console.log(formatDate('YYYY-01-01'));
|
||||
</script>
|
||||
<main>
|
||||
<section>
|
||||
<p>
|
||||
E-learning has evolved significantly since its inception. Today, there's a shift towards
|
||||
blended learning services, integrating online activities with practical, real-world applications.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>What We Do</h2>
|
||||
<p>At <strong>OurTrainingRoom.com</strong>, we specialize in content management and professional development training tailored for:</p>
|
||||
<ul>
|
||||
<li>School Boards</li>
|
||||
<li>Municipalities</li>
|
||||
<li>Hospitals</li>
|
||||
<li>Large Corporations</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Our Roots</h2>
|
||||
<p>
|
||||
Our parent company, <strong>The Auxilium Group</strong>, is a leader in online data management.
|
||||
The formation of OurTrainingRoom.com was a natural progression to deliver state-of-the-art front-end e-learning programs.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Our Approach</h2>
|
||||
<p>
|
||||
Built on principles of quality and continuous improvement, our diverse delivery range continues to grow.
|
||||
We set new trends by enhancing our existing products and attentively listening to our clients and their employees.
|
||||
This unique approach has solidified our position in the industry, making a substantial impact for our clients.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Have a Question?</h2>
|
||||
<p>
|
||||
We value your inquiries and are here to assist you. Please reach out with any questions or feedback.
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
© 2025 OurTrainingRoom.com. All rights reserved.
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.23.9",
|
||||
"version": "0.24.2",
|
||||
"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": {
|
||||
@ -34,7 +34,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"
|
||||
|
22
src/cache.ts
22
src/cache.ts
@ -1,3 +1,5 @@
|
||||
import {deepCopy} from './objects.ts';
|
||||
|
||||
export type CacheOptions = {
|
||||
/** Delete keys automatically after x amount of seconds */
|
||||
ttl?: number;
|
||||
@ -20,7 +22,6 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
/**
|
||||
* Create new cache
|
||||
*
|
||||
* @param {keyof T} key Default property to use as primary key
|
||||
* @param options
|
||||
*/
|
||||
@ -37,11 +38,11 @@ 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 target.store[prop as K];
|
||||
return deepCopy(target.store[prop as K]);
|
||||
},
|
||||
set: (target: this, prop: string | symbol, value: any) => {
|
||||
if(prop in target) (target as any)[prop] = value;
|
||||
else target.store[prop as K] = value;
|
||||
else this.set(prop as K, value);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
@ -54,16 +55,14 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
/**
|
||||
* Get all cached items
|
||||
*
|
||||
* @return {T[]} Array of items
|
||||
*/
|
||||
all(): T[] {
|
||||
return Object.values(this.store);
|
||||
return deepCopy(Object.values(this.store));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}
|
||||
@ -76,12 +75,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;
|
||||
@ -96,7 +95,6 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
/**
|
||||
* Delete an item from the cache
|
||||
*
|
||||
* @param {K} key Item's primary key
|
||||
*/
|
||||
delete(key: K) {
|
||||
@ -119,12 +117,11 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
* @return {T} Cached item
|
||||
*/
|
||||
get(key: K): T {
|
||||
return this.store[key];
|
||||
return deepCopy(this.store[key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of cached keys
|
||||
*
|
||||
* @return {K[]} Array of keys
|
||||
*/
|
||||
keys(): K[] {
|
||||
@ -133,16 +130,14 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
/**
|
||||
* Get map of cached items
|
||||
*
|
||||
* @return {Record<K, T>}
|
||||
*/
|
||||
map(): Record<K, T> {
|
||||
return structuredClone(this.store);
|
||||
return deepCopy(this.store);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@ -161,7 +156,6 @@ export class Cache<K extends string | number | symbol, T> {
|
||||
|
||||
/**
|
||||
* Get all cached items
|
||||
*
|
||||
* @return {T[]} Array of items
|
||||
*/
|
||||
values = this.all();
|
||||
|
76
src/csv.ts
76
src/csv.ts
@ -1,29 +1,56 @@
|
||||
import {makeArray} from './array.ts';
|
||||
import {ASet} from './aset.ts';
|
||||
import {dotNotation, flattenObj, JSONSanitize} from './objects.ts';
|
||||
import {LETTER_LIST} from './string.ts';
|
||||
|
||||
/**
|
||||
* Parse a CSV string into an array of objects
|
||||
*
|
||||
* @param csv String with CSV
|
||||
* @param hasHeaders First line of CSV contains headers
|
||||
* @return {T[]} Array of parsed objects
|
||||
*/
|
||||
export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
|
||||
const row = csv.split('\n');
|
||||
let headers: any = hasHeaders ? row.splice(0, 1)[0] : null;
|
||||
if(headers) headers = headers.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g);
|
||||
return <T[]>row.map(r => {
|
||||
function parseLine(line: string): (string | null)[] {
|
||||
const parts = line.split(','), columns: string[] = [];
|
||||
let quoted = false;
|
||||
for(const p of parts) {
|
||||
if(quoted) columns[columns.length - 1] = columns.at(-1) + ',' + p;
|
||||
else columns.push(p);
|
||||
if(/[^"]"$/g.test(p)) {
|
||||
quoted = false;
|
||||
} else if(/^"[^"]/g.test(p)) {
|
||||
quoted = true;
|
||||
const columns: string[] = [];
|
||||
let current = '', inQuotes = false;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const char = line[i];
|
||||
const nextChar = line[i + 1];
|
||||
if (char === '"') {
|
||||
if (inQuotes && nextChar === '"') {
|
||||
current += '"'; // Handle escaped quotes
|
||||
i++;
|
||||
} else inQuotes = !inQuotes;
|
||||
} else if (char === ',' && !inQuotes) {
|
||||
columns.push(current.trim()); // Trim column values
|
||||
current = '';
|
||||
} else current += char;
|
||||
}
|
||||
}
|
||||
return columns;
|
||||
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 h = headers || (Array(props.length).fill(null).map((r, i) => {
|
||||
const h = headers || (Array(props.length).fill(null).map((_, i) => {
|
||||
let letter = '';
|
||||
const first = i / 26;
|
||||
if (first > 1) letter += LETTER_LIST[Math.floor(first - 1)];
|
||||
@ -34,23 +61,28 @@ export function fromCsv<T = any>(csv: string, hasHeaders=true): T[] {
|
||||
dotNotation(acc, h, props[i]);
|
||||
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 {boolean} flatten Should nested object be flattened or treated as values
|
||||
* @return {string} CSV string
|
||||
*/
|
||||
export function toCsv(target: any[], flatten=true) {
|
||||
const headers = new ASet(target.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], []));
|
||||
export function toCsv(target: any, flatten=true) {
|
||||
const t = makeArray(target);
|
||||
const headers = new ASet(t.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], []));
|
||||
return [
|
||||
headers.join(','),
|
||||
...target.map(row => headers.map((h: string) => {
|
||||
...t.map(row => headers.map((h: string) => {
|
||||
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('\n');
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
import {makeArray} from './array.ts';
|
||||
import {JSONAttemptParse} from './objects.ts';
|
||||
import {PromiseProgress} from './promise-progress';
|
||||
import {formatDate} from './time.ts';
|
||||
|
||||
/**
|
||||
* Download blob as a file
|
||||
@ -76,7 +77,7 @@ export function fileText(file: any): Promise<string | null> {
|
||||
*/
|
||||
export function timestampFilename(name?: string, date: Date | number | string = new Date()) {
|
||||
if(typeof date == 'number' || typeof date == 'string') date = new Date(date);
|
||||
const timestamp = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}_${date.getHours().toString().padStart(2, '0')}-${date.getMinutes().toString().padStart(2, '0')}-${date.getSeconds().toString().padStart(2, '0')}`;
|
||||
const timestamp = formatDate('YYYY-MM-DD_HH:mm:ss', date);
|
||||
return name ? name.replace('{{TIMESTAMP}}', timestamp) : timestamp;
|
||||
}
|
||||
|
||||
|
40
src/http.ts
40
src/http.ts
@ -22,6 +22,28 @@ export type HttpDefaults = {
|
||||
url?: string;
|
||||
}
|
||||
|
||||
class HttpResponse<T = any> extends Response {
|
||||
data?: T
|
||||
ok!: boolean;
|
||||
redirected!: boolean;
|
||||
type!: ResponseType;
|
||||
url!: string;
|
||||
|
||||
constructor(resp: Response, stream: ReadableStream) {
|
||||
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;
|
||||
this.url = resp.url;
|
||||
}
|
||||
}
|
||||
|
||||
export class Http {
|
||||
private static interceptors: {[key: string]: HttpInterceptor} = {};
|
||||
|
||||
@ -54,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]}))
|
||||
@ -101,18 +124,17 @@ export class Http {
|
||||
push();
|
||||
}).catch((error: any) => controller.error(error));
|
||||
}
|
||||
|
||||
push();
|
||||
}
|
||||
});
|
||||
|
||||
resp.data = new Response(stream);
|
||||
if(opts.decode == null || opts.decode) {
|
||||
resp = new HttpResponse<T>(resp, stream);
|
||||
if(opts.decode !== false) {
|
||||
const content = resp.headers.get('Content-Type')?.toLowerCase();
|
||||
if(content?.includes('form')) resp.data = <T>await resp.data.formData();
|
||||
else if(content?.includes('json')) resp.data = <T>await resp.data.json();
|
||||
else if(content?.includes('text')) resp.data = <T>await resp.data.text();
|
||||
else if(content?.includes('application')) resp.data = <T>await resp.data.blob();
|
||||
if(content?.includes('form')) resp.data = <T>await resp.formData();
|
||||
else if(content?.includes('json')) resp.data = <T>await resp.json();
|
||||
else if(content?.includes('text')) resp.data = <T>await resp.text();
|
||||
else if(content?.includes('application')) resp.data = <T>await resp.blob();
|
||||
}
|
||||
|
||||
if(resp.ok) res(resp);
|
||||
|
@ -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
|
||||
*
|
||||
|
@ -142,8 +142,9 @@ export class PathEvent {
|
||||
const parsedFind = makeArray(filter).map(pe => new PathEvent(pe));
|
||||
return parsedTarget.filter(t => {
|
||||
if(!t.fullPath && t.all) return true;
|
||||
return !!parsedFind.find(f => f.fullPath.startsWith(t.fullPath)
|
||||
&& (f.all || t.all || t.methods.intersection(f.methods).length));
|
||||
return !!parsedFind.find(f =>
|
||||
(t.fullPath.startsWith(f.fullPath) || f.fullPath.startsWith(t.fullPath)) &&
|
||||
(f.all || t.all || t.methods.intersection(f.methods).length));
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
import {dotNotation, JSONAttemptParse} from './objects';
|
||||
import {dotNotation, JSONAttemptParse} from './objects.ts';
|
||||
|
||||
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
|
||||
if(!rows) return [];
|
||||
@ -12,27 +12,42 @@ export function search(rows: any[], search: string, regex?: boolean, transform:
|
||||
try { return RegExp(search, 'gm').test(v.toString()); }
|
||||
catch { return false; }
|
||||
}).length
|
||||
} else {
|
||||
return testCondition(search, r);
|
||||
}
|
||||
// Make sure at least one OR passes
|
||||
const or = search.split('||').map(p => p.trim()).filter(p => !!p);
|
||||
});
|
||||
}
|
||||
|
||||
export function testCondition(condition: string, row: any) {
|
||||
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 = /(\w+)\s*(==?|!=|>=|>|<=|<)\s*(\w+)/g.exec(p);
|
||||
const prop = /(\S+)\s*(==?|!=|>=|>|<=|<)\s*(\S+)/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}`);
|
||||
const key = Object.keys(row).find(k => k.toLowerCase() == prop[1].toLowerCase());
|
||||
return evalBoolean(dotNotation<any>(row, key || prop[1]), prop[2], JSONAttemptParse(prop[3]));
|
||||
}
|
||||
// Case-sensitive
|
||||
const v = Object.values(value).join('');
|
||||
if(/[A-Z]/g.test(search)) return v.includes(p);
|
||||
const v = Object.values(row).map(v => typeof v == 'object' && v != null ? JSON.stringify(v) : v).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;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
@ -64,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
|
||||
*
|
||||
@ -86,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
|
||||
*
|
||||
@ -149,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];
|
||||
|
Reference in New Issue
Block a user