Created array subclass with safeGetter

This commit is contained in:
lomonoshka
2023-08-05 16:42:51 +03:00
parent 232fae6631
commit 98bac7f86d
2 changed files with 47 additions and 29 deletions

View File

@@ -1,29 +0,0 @@
declare global {
interface Array<T> {
get(index: number): T;
last(): T
first(): T
}
}
if (!Array.prototype.get) {
Array.prototype.get = function <T>(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 <T>(this: T[]): T {
return this.get(this.length - 1)
}
}
if (!Array.prototype.first) {
Array.prototype.first = function <T>(this: T[]): T {
return this.get(0)
}
}

47
src/utils/safeGetters.ts Normal file
View File

@@ -0,0 +1,47 @@
export class SafeArray<T> extends Array<T> {
public static override from<T>(array: T[]): SafeArray<T> {
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<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): SafeArray<U> {
return new SafeArray(super.map(callbackfn, thisArg));
}
public override filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): SafeArray<T> {
return new SafeArray(super.filter(callbackfn, thisArg));
}
public get<T>(this: SafeArray<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
}
public last<T>(this: SafeArray<T>): T {
return this.get(this.length - 1)
}
public first<T>(this: SafeArray<T>): T {
return this.get(0)
}
}
export function safeGet<V>(obj: Partial<Record<string, V>>, 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;
}