Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Last active January 19, 2019 11:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikvullings/5dc40bc566bf00772355b24e16850cb1 to your computer and use it in GitHub Desktop.
Save erikvullings/5dc40bc566bf00772355b24e16850cb1 to your computer and use it in GitHub Desktop.
TypeScript utilities: GUID and deepCopy (clone)
/**
* Create a GUID
* @see https://stackoverflow.com/a/2117523/319711
*
* @returns RFC4122 version 4 compliant GUID
*/
export const uuid4 = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
// tslint:disable-next-line:no-bitwise
const r = (Math.random() * 16) | 0;
// tslint:disable-next-line:no-bitwise
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
/**
* Create a unique ID
* @see https://stackoverflow.com/a/2117523/319711
*
* @returns id followed by 8 hexadecimal characters.
*/
export const uniqueId = () => {
// tslint:disable-next-line:no-bitwise
return 'idxxxxxxxx'.replace(/[x]/g, () => ((Math.random() * 16) | 0).toString(16));
};
/**
* Pad left, default with a '0'
*
* @see http://stackoverflow.com/a/10073788/319711
* @param {(string | number)} n
* @param {number} width
* @param {string} [z='0']
* @returns
*/
export const padLeft = (n: string | number, width: number, z = '0') => {
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
};
/**
* Deep copy function for TypeScript.
* @param T Generic type of target/copied value.
* @param target Target value to be copied.
* @see Source project, ts-deepcopy https://github.com/ykdr2017/ts-deepcopy
*/
export const deepCopy = <T>(target: T): T => {
if (target === null) {
return target;
}
if (target instanceof Date) {
return new Date(target.getTime()) as any;
}
if (target instanceof Array) {
const cp = [] as any[];
(target as any[]).forEach((v) => { cp.push(v); });
return cp.map((n: any) => deepCopy<any>(n)) as any;
}
if (typeof target === 'object' && target !== {}) {
const cp = { ...(target as { [key: string]: any }) } as { [key: string]: any };
Object.keys(cp).forEach(k => {
cp[k] = deepCopy<any>(cp[k]);
});
return cp as T;
}
return target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment