Skip to content

Instantly share code, notes, and snippets.

@jaloplo
Created August 4, 2019 16:12
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 jaloplo/28a954ef407cc8303a980e00b7eab561 to your computer and use it in GitHub Desktop.
Save jaloplo/28a954ef407cc8303a980e00b7eab561 to your computer and use it in GitHub Desktop.
const CELSIUS_SCALE = 'Celsius';
const FAHRENHEIT_SCALE = 'Fahrenheit';
const KELVIN_SCALE = 'Kelvin';
const TransformationMethodsHandler = function() {
let collection = {};
return {
// Returns the transformation method by getting the source and target types
get: function(source, target) {
if(!collection[source] || !collection[source][target]) {
return null;
}
return collection[source][target];
},
// Registers a new tranformation method using source and target as keys
register: function(source, target, formula) {
if(!collection[source]) {
collection[source] = {};
}
if(!collection[source][target]) {
collection[source][target] = {};
}
// Added transform property to make it more usable and readable from code
collection[source][target].transform = formula;
// Makes easier to keep on registering new methods
return this;
}
};
}
let transformationHandler = new TransformationMethodsHandler()
.register(CELSIUS_SCALE, KELVIN_SCALE, (degree) => degree + 273.15)
.register(KELVIN_SCALE, CELSIUS_SCALE, (degree) => degree - 273.15)
.register(CELSIUS_SCALE, FAHRENHEIT_SCALE, (degree) => (9*degree/5) + 32)
.register(FAHRENHEIT_SCALE, CELSIUS_SCALE, (degree) => (5*(degree-32)) / 9)
.register(FAHRENHEIT_SCALE, KELVIN_SCALE, (degree) => (5*(degree-32)) / 9 + parseFloat(273.15))
.register(KELVIN_SCALE, FAHRENHEIT_SCALE, (degree) => (9*(degree - 273.15)/5) + 32);
let celsius = 24;
let fahrenheit = transformationHandler.get(CELSIUS_SCALE, FAHRENHEIT_SCALE).transform(celsius);
let kelvin = transformationHandler.get(FAHRENHEIT_SCALE, KELVIN_SCALE).transform(fahrenheit);
console.log(celsius, fahrenheit, kelvin); // 24, 75,.2, 297.15
// Singleton object to be used always in the same way
// Higher order functions to create the Parser object
// Currying technique to make code more readable
const Transformer = (function(engine) {
return function(value) {
return {
from: function(source) {
return {
to: function(target) {
return engine.get(source, target).transform(value);
}
};
}
};
};
})(transformationHandler);
celsius = 24;
fahrenheit = Transformer(celsius).from(CELSIUS_SCALE).to(FAHRENHEIT_SCALE);
kelvin = Transformer(fahrenheit).from(FAHRENHEIT_SCALE).to(KELVIN_SCALE);
console.log(celsius, fahrenheit, kelvin); // 24, 75,.2, 297.15
let parserFromCelsius = Transformer(celsius).from(CELSIUS_SCALE);
fahrenheit = parserFromCelsius.to(FAHRENHEIT_SCALE);
kelvin = parserFromCelsius.to(KELVIN_SCALE);
console.log(celsius, fahrenheit, kelvin); // 24, 75,.2, 297.15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment