As I embark on my transition from object-oriented programming to functional programming in TypeScript, I am encountering challenges. I am trying to convert imperative TypeScript code into a more functional style, but I'm struggling with the following snippet:
const foos: Map<
string,
Bar[]
> = new Map();
export const addBar = (
key: string,
bar: Bar
) => {
const foo = foos.get(key);
if (foo) {
foo.push(bar);
} else {
foos.set(key, [bar]);
}
};
While I grasp how to use methods like .map, .filter, and .concat on arrays, handling a Map that contains arrays is proving to be a challenge.
I am questioning whether the foos Map should be made read-only, along with the arrays of Bars inside it, which would mean that methods like .set and .push are not viable options. If modifying a read-only Map is not permissible, perhaps using an object instead of a Map would be more appropriate?
Without relying on mutability, I am unsure of how to add an element to an array within the values of the Map, or create a new map with an array if the specified key does not already exist. How can this be achieved in a functional manner?
Furthermore, I am concerned about performance. Given that I need to frequently add new elements to various arrays, will copying the entire map each time a change occurs have a significant impact on performance compared to traditional mutation methods?