Immutable.js Map: Find key from value

Viewed 406

I have an ImmutableJS map created like this:

const seatMap = Immutable.fromJS({
  seatOne: 'Martin',
  seatTwo: 'Emelie',
  seatThree: 'Erik'
});

I want to find out which seat a specific person is using. It can be assumed that the values will be unique.

I have come up with one solution so far:

const getSeatFromPerson = (seatMap, person) => {
  const [ ...keys ] = seatMap.keys();

  for (let i = 0; i < keys.length; i++ {
    if (seatMap.get(keys[i]) === person) {
      return keys[i];
    }
  }

  return null;
};

console.log(getSeatFromPerson(seatMap, 'Martin')); // Should be "seatOne"
console.log(getSeatFromPerson(seatMap, 'Erik')); // Should be "seatThree"
console.log(getSeatFromPerson(seatMap, 'Christopher')); // Should be null

But this solution feels very "clunky" and not very neat or fast. Is there a built in method for this or a better way to do it?

1 Answers

You can use this one line function that uses Array.prototype.find :

const getSeatFromPerson = (seatMap, person) => [...seatMap.keys()].find(seat => seatMap.get(seat) === person) || null;
Related