I am creating a simple hash table in Typescript and I have two functions, one that return all keys and another one that return all values, and I got something like this:
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;
}
What I am trying to do know is to condense this two functions into one as much of the code is repetition, I would only have to pass the type to the functions (for the array) what is easy however for one I need to push innerElement.value and for the other innerElement.key so hopefully I would have 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;
}
class CustomMap extends Map<string, T> { /*...*/ }?