Within a library, there exists a helper function designed to work with arrays of any type. The next step is to expand its functionality to also accommodate typed arrays. However, the challenge lies in the absence of a common base class for typed arrays or generic options. Below is the current code snippet tailored for generic arrays and one specific typed array:
public static copyOf(original: Int32Array, newLength: number): Int32Array;
public static copyOf<T>(original: T[], newLength: number): T[];
public static copyOf<T>(original: T[] | Int32Array, newLength: number): T[] | Int32Array {
if (original instanceof Int32Array) {
if (newLength < original.length) {
return original.slice(0, newLength);
}
if (newLength === original.length) {
return original.slice();
}
const result = new Int32Array(newLength);
result.set(original);
return result;
} else {
if (newLength < original.length) {
return original.slice(0, newLength);
}
if (newLength === original.length) {
return original.slice();
}
const result = new Array<T>(newLength);
result.splice(0, 0, ...original);
return result;
}
}
The above approach necessitates individual branches for each type of typed array, which deviates from the concept of generics. Is there a more succinct way to implement this without branching out for every typed array type?