@aappddeevv/dynamics-client-ui
Version:
## What is it? A library to help you create great dynamics applications.
39 lines (33 loc) • 1.26 kB
text/typescript
/** Misc data management utilities. */
/** Decent string hash. */
export function hash(str: string): number {
var hash = 5381;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
}
return hash;
}
/** Clean the id of brackets and lowercase everything. */
export function cleanId(id: string): string {
if (typeof id === "undefined" || id === null) throw Error(`Unable to clean nil id ${id}`)
return id.toString().replace(/[{}]/g, "").toLowerCase()
}
/** Wrap an id with {} and cap it, if needed. */
export function wrapId(id: string): string {
return `${cleanId(id).toUpperCase()}`
}
/** Simple normalization of data using a function to obtain the key. */
export function normalize<T,U>(id: (t:T) => string,
data: Array<T>,
tx: (t:T) => U) : { [id: string]: U}
{
return data.reduce((accum, t) => {
accum[id(t)] = tx(t)
return accum
}, {})
}
/** Normalize with a key that accessed via a simple key lookup. */
export function normalizeWith<T>(key: string, data: Array<T>): { [id: string]: T} {
return normalize<T,T>(t => t[key], data, (t:T) => t)
}