Skip to content

Instantly share code, notes, and snippets.

@metanomial
Last active December 4, 2019 22:37
Show Gist options
  • Save metanomial/5cda898056970287b8b85424934bbddf to your computer and use it in GitHub Desktop.
Save metanomial/5cda898056970287b8b85424934bbddf to your computer and use it in GitHub Desktop.
ECMAScript Class Enum Block
class Color {
enum {
RED(0xff0000),
GREEN(0x00ff00),
BLUE(0x0000ff)
}
constructor(hex) {
hex %= 0x1000000;
this.red = hex >> 0x10;
this.green = (hex >> 0x8) % 0x100;
this.blue = hex % 0x100;
}
toString() {
return (this.red * 0x10000 + this.green * 0x100 + this.blue).toString(16);
}
}
// Without enum syntax...
class Color {
static RED = new Color(0xff0000);
static GREEN = new Color(0x00ff00);
static BLUE = new Color(0x0000ff);
constructor(hex) {
hex %= 0x1000000;
this.red = hex >> 0x10;
this.green = (hex >> 0x8) % 0x100;
this.blue = hex % 0x100;
}
toString() {
return (this.red * 0x10000 + this.green * 0x100 + this.blue).toString(16);
}
}
// Roughly equivalent to...
function Color(hex) {
hex %= 0x1000000;
this.red = hex >> 0x10;
this.green = (hex >> 0x8) % 0x100;
this.blue = hex % 0x100;
}
Color.prototype.toString = function() {
return (this.red * 0x10000 + this.green * 0x100 + this.blue).toString(16);
}
Color.RED = new Color(0xff0000);
Color.GREEN = new Color(0x00ff00);
Color.BLUE = new Color(0x0000ff);
class Day {
enum {
Mon('Monday'),
Tue('Tuesday),
Wed('Wednesday'),
Thu('Thursday'),
Fri('Friday'),
Sat('Saturday'),
Sun('Sunday')
}
static _days = [];
static byIndex(index) {
return Day._days[index];
}
constructor(name) {
this.name = name;
Day._days.push(this);
}
}
function isWeekend(day) {
switch(day) {
case Day.Sat:
case Day.Sun:
return true;
default:
return false;
}
}
function logTheDay() {
const today = (new Date).getDay();
console.log(`Today is a ${Day.byIndex(today).name}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment