0

With ES2018 is there a more robust way to create this topic list, (What I want is the numbers to be auto-generated).

const Topics = {
    NullTopic: 0,
    simActorStateTest: 1,
    navActorStateTest: 2,
    simTelemetryVenom11: 3,
    navTelemetryVenom11: 4,
    simTelemetryVenom12: 5,
    navTelemetryVenom12: 6,
    scenarioStart: 7,
    scenarioEnd: 8,
}
Dr.YSG
  • 7,171
  • 22
  • 81
  • 139
  • 1
    i would write a function that accepts an array of choices and populates an object for you. – dandavis Sep 13 '18 at 21:09
  • Have a look at [this](https://stackoverflow.com/a/6672823/1048572) – Bergi Sep 13 '18 at 21:25
  • Or don't use integers when you can just [use symbols](https://stackoverflow.com/a/30058506/1048572) (also [here](https://stackoverflow.com/q/44447847/1048572)) – Bergi Sep 13 '18 at 21:26
  • It is communicating with a C++ program that is sending ints in a Google FlatBuffer. – Dr.YSG Sep 13 '18 at 22:07
  • `["string1", "string2", "string3"].reduce((r, s, i) => (r[s] = i, r), {})` – pishpish Sep 13 '18 at 23:14

1 Answers1

1
var i =0;
const Topics = {
    NullTopic: i++,
    simActorStateTest: i++,
    navActorStateTest: i++,
    simTelemetryVenom11: i++,
    navTelemetryVenom11: i++,
    simTelemetryVenom12: i++,
    navTelemetryVenom12: i++,
    scenarioStart: i++,
    scenarioEnd: i++
}
dustytrash
  • 1,568
  • 1
  • 10
  • 17
  • Well I was sure I tried this before, and got some sort of an error with NodeJS (10.4) but anyway this is working fine for me now @dustytrash – Dr.YSG Sep 14 '18 at 14:14
  • This could create problems if you serialize it and then deserialize it in a modified structure. For example if you switch two of keys around, the deserialized object would have the values switched as well. The version of the OP has the same problem however and I don't see an easy solution. Java handles this using serialVersionUID. – Konrad Höffner Sep 28 '18 at 09:14