Compare commits

..

5 Commits

Author SHA1 Message Date
c06538a725 Fixed word formatters
All checks were successful
Build / Build NPM Project (push) Successful in 45s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 35s
2025-06-11 18:41:46 -04:00
a08b0c4eea Fixed database init loop
All checks were successful
Build / Build NPM Project (push) Successful in 40s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-05-27 15:42:00 -04:00
1b03ae875b Fixed database includes
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 35s
2025-05-27 15:13:53 -04:00
af1da75a82 Removed console.log statments
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-05-27 14:56:24 -04:00
e19768688d Fixed using numbers as database table name
All checks were successful
Build / Build NPM Project (push) Successful in 1m16s
Build / Tag Version (push) Successful in 15s
Build / Publish Documentation (push) Successful in 53s
2025-05-27 14:51:04 -04:00
5 changed files with 57 additions and 56 deletions

View File

@ -3,27 +3,8 @@
<script type="module">
import {Cache, Database} from './dist/index.mjs';
const db = new Database('test', ['test', 'test2', 'test3']);
const cache = new Cache('id', {
ttl: 60,
storage: db.table('test'),
expiryPolicy: 'delete'
});
const cache2 = new Cache('id', {
ttl: 60,
storage: db.table('test2'),
expiryPolicy: 'delete'
});
const cache3 = new Cache('id', {
ttl: 60,
storage: db.table('test3'),
expiryPolicy: 'delete'
});
console.log(cache3.all());
const db = new Database('test', [123]);
window['table'] = db.table(123);
</script>
</body>
</html>

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.25.3",
"version": "0.25.8",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@ -1,3 +1,5 @@
import {ASet} from './aset.ts';
export type TableOptions = {
name: string;
key?: string;
@ -5,16 +7,22 @@ export type TableOptions = {
export class Database {
connection!: Promise<IDBDatabase>;
tables!: TableOptions[];
constructor(public readonly database: string, public readonly tables: (string | TableOptions)[], public version?: number) {
constructor(public readonly database: string, tables: (string | TableOptions)[], public version?: number) {
this.connection = new Promise((resolve, reject) => {
const req = indexedDB.open(this.database, this.version);
this.tables = tables.map(t => {
t = typeof t == 'object' ? t : {name: t};
return {...t, name: t.name.toString()};
});
const tableNames = new ASet(this.tables.map(t => t.name));
req.onerror = () => reject(req.error);
req.onsuccess = () => {
const db = req.result;
if(tables.find(s => !db.objectStoreNames.contains(typeof s === 'string' ? s : s.name))) {
if(tableNames.symmetricDifference(new ASet(Array.from(db.objectStoreNames))).length) {
db.close();
Object.assign(this, new Database(this.database, this.tables, db.version + 1));
} else {
@ -25,34 +33,29 @@ export class Database {
req.onupgradeneeded = () => {
const db = req.result;
Array.from(db.objectStoreNames)
.filter(s => !this.tables.find(t => typeof t === 'string' ? t : t.name == s))
.forEach(name => db.deleteObjectStore(name));
tables.filter(t => !db.objectStoreNames.contains(typeof t === 'string' ? t : t.name))
.forEach(t => {db.createObjectStore(typeof t === 'string' ? t : t.name, {
keyPath: typeof t === 'string' ? undefined : t.key
});
});
const existingTables = new ASet(Array.from(db.objectStoreNames));
existingTables.difference(tableNames).forEach(name => db.deleteObjectStore(name));
tableNames.difference(existingTables).forEach(name => db.createObjectStore(name));
};
});
}
includes(name: string): boolean {
return this.tables.some(t => (typeof t === 'string' ? name === t : name === t.name));
includes(name: any): boolean {
return !!this.tables.find(t => t.name == name.toString());
}
table<K extends IDBValidKey = any, T = any>(name: string): Table<K, T> {
return new Table<K, T>(this, name);
table<K extends IDBValidKey = any, T = any>(name: any): Table<K, T> {
return new Table<K, T>(this, name.toString());
}
}
export class Table<K extends IDBValidKey = any, T = any> {
constructor(private readonly database: Database, public readonly name: string) {}
async tx<R>(schema: string, fn: (store: IDBObjectStore) => IDBRequest, readonly = false): Promise<R> {
async tx<R>(table: string, fn: (store: IDBObjectStore) => IDBRequest, readonly = false): Promise<R> {
const db = await this.database.connection;
const tx = db.transaction(schema, readonly ? 'readonly' : 'readwrite');
const store = tx.objectStore(schema);
const tx = db.transaction(table, readonly ? 'readonly' : 'readwrite');
const store = tx.objectStore(table);
return new Promise<R>((resolve, reject) => {
const request = fn(store);
request.onsuccess = () => resolve(request.result as R); // ✅ explicit cast

View File

@ -21,11 +21,13 @@ export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST +
/**
* Converts text to camelCase
*/
export function camelCase(str?: string) {
const text = pascalCase(str);
return !text ? '' : text[0].toLowerCase() + text.slice(1);
export function camelCase(str?: string): string {
if(!str) return '';
const pascal = pascalCase(str);
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
}
/**
* Convert number of bytes into a human-readable size
*
@ -75,14 +77,12 @@ export function insertAt(target: string, str: string, index: number): String {
/**
* Converts text to kebab-case
*/
export function kebabCase(str: string) {
export function kebabCase(str?: string): 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();
return wordSegments(str).map(w => w.toLowerCase()).join("-");
}
/**
* Add padding to string
*
@ -112,12 +112,13 @@ export function pad(text: any, length: number, char: string = ' ', start = true)
*/
export function pascalCase(str?: string): string {
if(!str) return '';
return str.match(/[a-zA-Z0-9]+/g)
?.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join('') ?? '';
return wordSegments(str)
.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join('');
}
/**
* Generate a random hexadecimal value
*
@ -184,14 +185,12 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
/**
* Converts text to snake_case
*/
export function snakeCase(str?: string) {
export function snakeCase(str?: string): 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();
return wordSegments(str).map(w => w.toLowerCase()).join("_");
}
/**
* Splice a string together (Similar to Array.splice)
*
@ -298,6 +297,23 @@ export function md5(d: string) {
function bit_rol(d:any,_:any){return d<<_|d>>>32-_
}
/**
* Splits a string into logical word segments
*/
export function wordSegments(str?: string): string[] {
if (!str) return [];
return str
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
.replace(/([0-9]+)([a-zA-Z])/g, "$1 $2")
.replace(/([a-zA-Z])([0-9]+)/g, "$1 $2")
.replace(/[_\-\s]+/g, " ")
.trim()
.split(/\s+/)
.filter(Boolean);
}
/**
* Check if email is valid
*

View File

@ -59,7 +59,8 @@ describe('String Utilities', () => {
describe('kebabCase', () => {
it('converts to kebab-case', () => {
expect(kebabCase('HelloWorldTest')).toContain('-hello');
expect(kebabCase('hello world')).toBe('hello-world');
expect(kebabCase('HelloWorld')).toContain('hello-world');
expect(kebabCase('')).toBe('');
});
});