skip to Main Content

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


  1. Maybe use different approach with regex and ternary operator?

    const mapFunc = (k) => /b(a|b|c)b/.test(k) ? 'first' : /b(d|e|f)b/.test(k) ? 'second' : null;
    
    console.log(mapFunc('a')); 
    console.log(mapFunc('d'));
    
    console.log(mapFunc('j'));
    console.log(mapFunc('abc'));
    Login or Signup to reply.
  2. 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:

    const mapFunc = (key) => {
      const map = {
    first: ['a', 'b', 'c'],
    second: ['d', 'e', 'f']
      };
      return Object.keys(map).find(aKey => map[aKey].includes(key));
    };
    console.log(mapFunc('b'));

    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:

    // `map` is created outside of `mapFunc` to initialize it only once.
    const map = {
      first: new Set(['a', 'b', 'c']),
      second: new Set(['d', 'e', 'f'])
    };
    
    const mapFunc = (key) => {
      return Object.keys(map).find(aKey => map[aKey].has(key));
    };
    console.log(mapFunc('b'));
    Login or Signup to reply.
  3. You could consider transforming your desired format into your original format and using it as you do now:

    const compact_map = {
        first: ['a', 'b', 'c'],
        second: ['d', 'e', 'f']
    };
    
    const convert_map = (map) =>
      Object.fromEntries(
        Object.entries(map)
          .flatMap(
            ([key, values]) => values.map((value) => [value, key])
          )
      );
    
    const map = convert_map(compact_map);
    
    let mapFunc = (key) => {
        return map[key];
    };
    
    console.log(mapFunc('b'));
    console.log(mapFunc('d'));
    console.log(mapFunc('j'));

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search