/** 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(id: (t:T) => string, data: Array, 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(key: string, data: Array): { [id: string]: T} { return normalize(t => t[key], data, (t:T) => t) }