I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far:
public values() {
let values = new Array<T>();
this._keyMap.forEach((element) =>
element.forEach((innerElement) => values.push(innerElement.value))
);
return values;
}
public keys() {
let values = new Array<string>();
this._keyMap.forEach((element) =>
element.forEach((innerElement) => values.push(innerElement.key))
);
return values;
}
My goal now is to consolidate these two functions into one to avoid repetition of code. Ideally, I would like to be able to pass the type (for the array) as a parameter to the function. However, since one function requires pushing innerElement.value
and the other innerElement.key
, this presents a challenge. My desired outcome is something like:
public values() {
return getArrayInfo<T>(/*code to return value*/);
}
public keys() {
return getArrayInfo<String>(/*code to return keys*/);
}
public getArrayInfo<I>(/*something*/) {
let values = new Array<I>();
this._keyMap.forEach((element) =>
element.forEach((innerElement) => values.push(/*something*/))
);
return values;
}