Created
February 22, 2018 16:44
-
-
Save mvolkmann/f07471a486d38f88589c776a4881fe9e to your computer and use it in GitHub Desktop.
JavaScript version of what I'm trying to do in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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