0

I need to transpile a key is some situation. Right now i'm using this:

  transpileKey = key => {
    if (key === 'smsCode') key = 'code';
    if (key === 'phoneMobile') key = 'phoneNumber';
    if (key === 'passport') key = 'ssn';
    if (key === 'comment') key = 'notes';

    return key;
  };

And the function who calls it:

validate = (key) => {
    key = transpileKey(key)
    console.log(key)
}
validate('smsCode')

I wrote this switch to make it nicer, but it's not returning the proper value (I get the last one, 'notes' in the log).

  transpileKey = key => {
    switch (key) {
      case 'smsCode':
        key = 'code';
      case 'phoneMobile':
        key = 'phoneNumber';
      case 'passport':
        key = 'ssn';
      case 'comment':
        key = 'notes';
    }

    return key;
  };

What is wrong?

flow24
  • 793
  • 2
  • 5
  • 17
  • 3
    No `break;` statements. – VLAZ Oct 10 '21 at 09:17
  • 1
    Also, a better way would be to not override the parameter's value, and simply return instantly. – Eldar B. Oct 10 '21 at 09:24
  • @EldarB. even better would be to just use a map for this. Since that's exactly what the `switch` does except it's non-reusable. `{ 'smsCode': 'code', 'phoneMobile': 'phoneNumber', /* ... */ }` – VLAZ Oct 10 '21 at 10:31
  • @VLAZ can u write an example to what u meant? – flow24 Oct 10 '21 at 11:01
  • @flow24 `const obj = { 'smsCode': 'code', 'phoneMobile': 'phoneNumber', /* ... */ }; transpileKey = key => obj[key];` – VLAZ Oct 10 '21 at 11:10
  • @VLAZ cool. is there a way to give it a default value which be the parameter it gets (the value of 'key') – flow24 Oct 10 '21 at 11:43
  • 1
    Something like this: https://stackoverflow.com/a/61120044 – VLAZ Oct 10 '21 at 12:26

0 Answers0