I have a logic that accepts a configuration and returns a value. However, I'd like to retrieve from the cache for the further tries of same configuration. The order of keys may be varied within the config but must be treated as the same configuration.
Comments explain what I try to achieve. I expect only two openings as there are only two different config in the sample code. Only first and second attempts of open()
goes as expected because of the same object passing to the map as a key.
If I try to keep the keys as a JSON string then the order of the keys can be problematic.
Here is what I have tried so far. I appreciate any idea or alternative solution.
var m = new Map();
function opening(config) {
// ...
return "foo";
}
function open(config = {}) {
if (!m.has(config)) {
m.set(config, opening(config));
console.log("open and set: ", config);
} else {
console.log("get from the map: ", config);
}
return m.get(config);
}
var c1 = { a: 1, b: 2 };
open(c1); // open and set [OK]
open(c1); // get from the map [OK]
open({ a: 1, b: 2 }); // get from the map
open({ b: 2, a: 1 }); // get from the map, even in different orders
open({ a: 1, b: 2, c: 3 }); // open and set
open({ a: 1, c: 3, b: 2 }); // get from the map