JSFiddle - React, Tailwind, and code Playground

by jun68ykt

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

JavaScript

class Point {
  constructor(x=0, y=0, z=0) {
    this._x = x;
    this._y = y;
    this._z = z;
  }

  get x() { return this._x; }
  set x(value) { this._x = value; }

  get y() { return this._y; }
  set y(value) { this._y = value; }

  get z() { return this._z; }
  set z(value) { this._z = value; }

  toString() {
    return `(x: ${this.x}, y: ${this.y}, z: ${this.z})`;
  }
}

class RestrictedPoint extends Point {

  static config() {
    return {
      x: { min: 0, max: 99 }, // X座標は0以上99以下
      y: { min: 0, max: 199 }, // Y座標は0以上199以下
      z: { min: 100, max: 399 } // Z座標は100以上399以下
    };
  }

  get(axis) {
    const conf = this.constructor.config()[axis];
    return Math.min(conf.max, Math.max(conf.min, this[`_${axis}`]));
  }

  get x() { return this.get('x'); }
  set x(value) { this._x = value; }

  get y() { return this.get('y'); }
  set y(value) { this._y = value; }

  get z() { return this.get('z'); }
  set z(value) { this._z = value; }

}

const p1 = new Point(-1, 230, 50);
console.log(`${p1}`);  // => (x: -1, y: 230, z: 50)

p1.x = 1000;
console.log(p1.x);  // => 1000

const p2 = new RestrictedPoint(-1, 230, 50);
console.log(`${p2}`);  // => (x: 0, y: 199, z: 100)

p2.x = 1000;
console.log(p2.x);  // => 99