0

I need to generate an enumErrorList like this

Errors={
    none:0,
    subject:1,
    content:2,
    sender:4,
    recipient:8
}

from an array like this

let errors=[
        'none',
        'subject',
        'content',
        'sender',
        'recipient'
]

but I’m sorry I’m not very familiar with enum.

2 Answers 2

2

Use Object.entries and Object.fromEntries as follows

let errors=[
        'none',
        'subject',
        'content',
        'sender',
        'recipient'
]

let Errors = Object.fromEntries(Object.entries(errors).map(([a,b]) => [b, ((1<<a)>>1)]));
console.log(Errors)

Sign up to request clarification or add additional context in comments.

3 Comments

Right, well done with the |0. I was wracking my brain trying to figure out how to make it with bitwise operations only since 1 << index was the correct way...aside from 0. For some reason I completely forgot I ignored I could just use two operations. Your /2 reminded me of that, so it finally clicked 1 << index >> 1 to only set bit n-1 which happens to be no bits for index = 0.
d'oh ... of course << then >> :p - I had a seniors moment :p
Don't worry, I did as well. I know the feeling :D
1

You can take the array then use Array#reduce and Object.assign to generate an object there where:

  • The key is the item from the array.
  • The value grows by a power of 2 starting from zero.

let errors=[
        'none',
        'subject',
        'content',
        'sender',
        'recipient'
]

const Errors = errors.reduce(
  (acc, item, index) => Object
    .assign(
      acc, 
      {[item]: Math.floor(2 ** (index - 1))}
    ), 
  {}
)

console.log(Errors)

Or via bit arithmetic to only produce powers of 2 by setting bit n-1 starting with 0 when n=0:

let errors=[
        'none',
        'subject',
        'content',
        'sender',
        'recipient'
]

const Errors = errors.reduce(
  (acc, item, index) => Object
    .assign(
      acc, 
      {[item]: (1 << index) >> 1}
    ), 
  {}
)

console.log(Errors)

1 Comment

thanks you have been very kind and exhaustive in your reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.