Skip to content

Instantly share code, notes, and snippets.

@mvolkmann
Created February 22, 2018 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvolkmann/f07471a486d38f88589c776a4881fe9e to your computer and use it in GitHub Desktop.
Save mvolkmann/f07471a486d38f88589c776a4881fe9e to your computer and use it in GitHub Desktop.
JavaScript version of what I'm trying to do in Haskell
const colorNameToHexMap = {
red: 'FF0000',
green: '00FF00',
blue: '0000FF'
};
const colorHexToNameMap = {
FF0000: 'red',
'00FF00': 'green',
'0000FF': 'blue'
};
function hexToRgb(hex) {
if (hex.length !== 6) throw new Error('invalid hex value: ' + hex);
const red = hex.substr(0, 2);
const green = hex.substr(2, 2);
const blue = hex.substr(4, 2);
return [red, green, blue].map(hex => parseInt(hex, 16));
}
function rgbToHex(rgb) {
return rgb
.map(value => Number(value).toString(16).toUpperCase().padStart(2, '0'))
.join('');
}
const validColorKinds = ['hex', 'name', 'rgb'];
class Color {
constructor(kind, value) {
if (!validColorKinds.includes(kind)) {
throw new Error(`invalid Color kind "${kind}"`);
}
this.kind = kind;
this.value = kind === 'hex' ? value.toUpperCase() : value;
}
getHex() {
const {kind, value} = this;
if (kind === 'hex') return value;
if (kind === 'name') return colorNameToHexMap[value];
return rgbToHex(value);
}
getName() {
const {kind, value} = this;
if (kind === 'name') return value;
return colorHexToNameMap[kind === 'rgb' ? rgbToHex(value) : value];
}
getRgb() {
const {kind, value} = this;
if (kind === 'rgb') return value;
if (kind === 'name') return hexToRgb(colorNameToHexMap[value]);
return hexToRgb(value);
}
}
class Wagon {
constructor(length, width, color) {
this.length = length;
this.width = width;
this.color = color;
}
getHex() {
return this.color.getHex();
}
getName() {
return this.color.getName();
}
getRgb() {
return this.color.getRgb();
}
}
const wagon = new Wagon(36, 20, new Color('name', 'red'));
console.log(wagon.getHex());
console.log(wagon.getName());
console.log(wagon.getRgb());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment