Short version
Given the following class:
class Foo {
constructor() {
throw new Error("No!")
}
// ... more functions ...
}
How can I get an instance of Foo?
Explanation
The class actually looks like more this:
const KEY = Symbol("BAR")
function validateBarData(input) {
/* throws error if input is not in the format: */
/* {name: "string", bartender: "string", drinks: [ "string" ]} */
}
class Bar {
constructor(name, bartender, drinks) {
this[KEY] = {name: name, bartender: bartender, drinks: drinks}
// now validate to protect against garbage input like
// 'name = 42' or 'drinks = undefined', etc.
validateBarData(this[KEY])
}
encode() {
return this[KEY]
}
static decode(data) {
validateBarData(data)
return new Bar(data.name, data.bartender, data.drinks)
}
// ... more functions ...
}
encode() and Bar.decode(data) are used to serialize state to something JSON.stringifyable so the object can be recreated later. The actual encode/decode logic here may be more complex than just 'dump this[KEY]' (e.g. encoding objects managed by the Bar object).
Problems when decoding:
validateBarDatais called twice- Although we already have a valid internal state to assign to
this[KEY]after the first line ofdecode, it first has to be destructured then recreated.
I'd like to avoid this duplication, but I've not been able to find the right way to do it.
How can I do this please?