Skip to content

Instantly share code, notes, and snippets.

@pixelgrid
Last active August 29, 2015 14:27
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 pixelgrid/a6ea00263a6df79e8cc4 to your computer and use it in GitHub Desktop.
Save pixelgrid/a6ea00263a6df79e8cc4 to your computer and use it in GitHub Desktop.
Small converter utility for converting between provided values. Its parameters must be the type names and the type values association
function Converter(types, values) {
var associations = {},
values = values,
types = types;
return function(baseValue){
types.forEach(function(type){
associations[type] = {
to : types.reduce(function(current, previous){
if(type == previous){
return current;
}
var index1 = types.indexOf(type) + 1,
index2 = types.indexOf(previous) + 1;
if(index1 > index2){
var reversed = true;
index2 = [index1, index1 = index2][0];
}
current[previous] = values
.slice(index1, index2)
.reduce(function(current, previous){
return current * previous;
}, 1) * baseValue;
if(reversed){
current[previous] = (1 / current[previous]) * baseValue;
}
return current;
}, {})
}
});
return associations;
}
}
@pixelgrid
Copy link
Author

Example usage

var lengthConverter = new Converter(['mile', 'yard', 'foot', 'inch', 'cm'], [1, 1760, 3, 12, 2.54])
lengthConverter(10).mile.to.yard; // prints 17600
lengthConverter(10).cm.to.inch; //prints 3.93700787

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment