Porting the Gallery Formatter
You ported Mina’s Python reading formatter to JavaScript: the Reading class, a subclass with a
conversion hook, and one formatted line for the 21-degree reading. The port keeps the number
and the label apart, and converts on purpose.
constructordoes__init__’s job, andthisstands in forself.__str__becomestoString(), with a template literal in place of the F string.__float__becomesvalueOf(). Python’s arithmetic operators never call__float__, soReading(21) * 2raises aTypeError. JavaScript callsvalueOf()by itself whenever an operator needs a number, so a plain reading of 21 times 2 gives42.- Plain
Readingkeeps ordinary conversion. The subclassLoggedReadingdecides each hint on purpose: it extendsReadingand adds one method whose computed key is the predefined symbolSymbol.toPrimitive, not a string. JavaScript calls it first and passes a hint. - For
"string", the hook returns the label. For"number"and"default", it returns the plain number. Plus passes"default", so a hook that returned the label there would makereading + 1glue21 C1. - In Python,
__str__covers the string hint and__float__the number hint, with no direct equivalent of default. - With the hook present, JavaScript uses it and doesn’t call the inherited
toString()orvalueOf().String(reading)and`${reading}`give"21 C",reading + 1gives22, andreading * 2gives42. A plainReadinggives the same four values the ordinary way: the hook doesn’t change them, it puts each decision in one place. - Python’s
float()becomesNumber(), which passes the number hint. In Python, adding one to the reading itself raises aTypeError, sofloat()had to be there. Plus would also give22here, through default, butNumber()keeps the conversion on purpose.
Here’s the port, gallery.js:
class Reading {
constructor(celsius) {
this.celsius = celsius;
}
toString() {
return `${this.celsius} C`;
}
valueOf() {
return this.celsius;
}
}
class LoggedReading extends Reading {
[Symbol.toPrimitive](hint) {
if (hint === "string") return `${this.celsius} C`;
return this.celsius;
}
}
const reading = new LoggedReading(21);
const nextCelsius = Number(reading) + 1;
console.log(`Reading: ${reading}; next: ${nextCelsius} C`);