Fabio Mannelli
Fabio Mannelli

Reputation: 17

How I create an enum from an array?

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.

Upvotes: 0

Views: 176

Answers (2)

VLAZ
VLAZ

Reputation: 29010

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)

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

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)

Upvotes: 2

Related Questions