From 6166c894639e2679c8cd5c480911c8009bcd99d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me> Date: Wed, 5 Jul 2023 16:34:00 +0200 Subject: [PATCH] Add TypeScript extension file (extensions TypeScript types) --- helpers/TypeScriptExtensions.ts | 61 +++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 helpers/TypeScriptExtensions.ts diff --git a/helpers/TypeScriptExtensions.ts b/helpers/TypeScriptExtensions.ts new file mode 100644 index 0000000..1995420 --- /dev/null +++ b/helpers/TypeScriptExtensions.ts @@ -0,0 +1,61 @@ +declare global { + interface Array<T> { + removeObjectDuplicates: (getProperty: (item: T) => any) => Array<T>; + } + + + interface String { + toBoolean: () => boolean; + capitalizingFirstLetter: () => string; + capitalizeName: () => string; + } +} + +function registerAll() { + registerBigIntJson(); + registerArrayRemoveObjectDuplicates(); + registerStringToBoolean(); + registerStringCapitalizingFirstLetter(); + registerStringCapitalizeName(); +} + +function registerBigIntJson() { + (BigInt.prototype as any).toJSON = function () { + return this.toString(); + }; +} + +function registerArrayRemoveObjectDuplicates() { + Array.prototype.removeObjectDuplicates = function <T>(this: Array<T>, getProperty: (item: T) => any): Array<T> { + return this.reduce((accumulator: Array<T>, current: T) => { + if ( !accumulator.find((item: any) => getProperty(item) === getProperty(current)) ) { + accumulator.push(current); + } + return accumulator; + }, Array<T>()); + }; +} + +function registerStringToBoolean() { + String.prototype.toBoolean = function (this: string): boolean { + const tmp = this.toLowerCase().trim(); + return tmp === 'true' || tmp === '1'; + }; +} + +function registerStringCapitalizingFirstLetter() { + String.prototype.capitalizingFirstLetter = function (this: string): string { + return this.charAt(0).toUpperCase() + this.slice(1); + }; +} + +function registerStringCapitalizeName() { + String.prototype.capitalizeName = function (this: string): string { + return this.trim().replace(/(?:^|\s|-)\S/g, s => s.toUpperCase()); + }; +} + +registerAll(); + + +export default null; \ No newline at end of file -- GitLab