I have the following JS function:
let mapFunc = (key) => {
let map = {
a: 'first',
b: 'first',
c: 'first',
d: 'second',
e: 'second',
f: 'second'
}
return map[key];
}
console.log(mapFunc('b'))
Is there a way that I can write this function so that instead of having 6 different properties, I have only 2 properties, like this?
{
first: ['a', 'b', 'c']
second: ['d', 'e', 'f']
}
3
Answers
Maybe use different approach with regex and ternary operator?
mapFunc
will always be faster using your current 6 properties map.Using your second data structure, you are forced to iterate over each entry to find if it contains the given value:
You can optimize this a little by using a
Set
instead of an array for each properties but it will still be slower than your original code:You could consider transforming your desired format into your original format and using it as you do now:
Just a note: this is probably only a good idea in a situation where you could arrange things such that you only need to do the map conversion once. If you can do that then you have an efficient data structure in terms of the developer populating / updating it and a computationally efficient method in terms of the
mapFunc
function.