0

Can I create a class that creates objects who have special context? (like string or number contexts).

class Unit extends Number {
  constructor(value, symbol) {
    super(value)
    this.symbol = symbol
  }

  valueOf() {
    return parseFloat(this.toPrecision(2))
  }

  toString() {
    return `${this.valueOf()} ${this.symbol}`
  }
}

let meter = new Unit(1, 'm')

console.log('example of number context that uses valueOf()')
console.log(Number(meter)) // Number(1)
console.log(1 + meter) // Number(2)
console.log(2 * meter) // Number(2)

console.log('example of string context that uses toString()')
console.log(String(meter)) // String('1 m')
console.log(`string: ${meter}`) // String('string: 1 m')

console.log(`and what I'm trying to do (Unit context), but instead it works like number context`)
console.log(meter + 1) // Unit(2, 'm')
const square_meter = meter * meter
console.log(square_meter) // Unit(1, 'm2')
console.log(square_meter / meter) // Unit(1, 'm')

So, what I'm trying to do is check if object of class Unit is used with an operator (and which operator) against another Unit, Number or String and produce different result depending on that.

My question is, if something like that is possible with JavaScript?

Crow
  • 4,635
  • 3
  • 14
  • 21
  • `check if object of class Unit is used with an operator (and which operator) `. It's possible, but you will have to capture the formula as a string and parse in order to find out which operators are used. – Abana Clara Jul 24 '19 at 12:06
  • @AbanaClara you mean to create a function that accepts `Unit`, `Operator` and `Unit`? i.e. `unitMath(meter, "*", meter) // Unit(1, 'm')`. Or do you mean that there is a way to `capture the formula as a string` for i.e. `meter * meter` syntax. – Crow Jul 24 '19 at 12:14
  • both, but I think the former is much better overall – Abana Clara Jul 24 '19 at 12:17
  • 1
    No, overloading operators is not possible, `*` always returns a number. Use methods like `meter.multiply(meter)` – Bergi Jul 24 '19 at 12:35

0 Answers0