diff --git a/src/utils/arrayHelpers.ts b/src/utils/arrayHelpers.ts deleted file mode 100644 index fc583e2..0000000 --- a/src/utils/arrayHelpers.ts +++ /dev/null @@ -1,29 +0,0 @@ -declare global { - interface Array { - get(index: number): T; - last(): T - first(): T - } -} - -if (!Array.prototype.get) { - Array.prototype.get = function (this: T[], index: number): T { - const value = this.at(index); - if (value === undefined) { - throw new Error(`Element at index ${index} is undefined. Array: ${this}`) - } - return value - } -} - -if (!Array.prototype.last) { - Array.prototype.last = function (this: T[]): T { - return this.get(this.length - 1) - } -} - -if (!Array.prototype.first) { - Array.prototype.first = function (this: T[]): T { - return this.get(0) - } -} \ No newline at end of file diff --git a/src/utils/safeGetters.ts b/src/utils/safeGetters.ts new file mode 100644 index 0000000..944f498 --- /dev/null +++ b/src/utils/safeGetters.ts @@ -0,0 +1,47 @@ +export class SafeArray extends Array { + + public static override from(array: T[]): SafeArray { + return new SafeArray(array); + } + + constructor(array: T[]) { + super(array.length); + array.forEach((element, index) => { + this[index] = element; + }) + } + + public toArray(): T[] { + return [...this]; + } + + public override map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): SafeArray { + return new SafeArray(super.map(callbackfn, thisArg)); + } + + public override filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): SafeArray { + return new SafeArray(super.filter(callbackfn, thisArg)); + } + + public get(this: SafeArray, index: number): T { + const value = this.at(index); + if (value === undefined) { + throw new Error(`Element at index ${index} is undefined. Array: ${this}`) + } + return value + } + + public last(this: SafeArray): T { + return this.get(this.length - 1) + } + + public first(this: SafeArray): T { + return this.get(0) + } +} + +export function safeGet(obj: Partial>, key: string, errorMessage?: string) { + const value = obj[key]; + if (value === undefined) throw new Error(`Key '${key.toString()}' not found in object. Available keys: ${Object.keys(obj).join(', ')}.${errorMessage ? ` ${errorMessage}` : ''}`); + return value; +} \ No newline at end of file