Skip to content

Instantly share code, notes, and snippets.

@Madhuka
Created December 12, 2013 07:34
Show Gist options
  • Save Madhuka/7924419 to your computer and use it in GitHub Desktop.
Save Madhuka/7924419 to your computer and use it in GitHub Desktop.
Convert sample
function Convert(number, fromUnit) {
console.log('Starting....');
var conversions = {
distance: {
meters: 1,
cm: 0.01,
feet: 0.3048,
inches: 0.0254,
yards: 0.9144
},
volume: {
liters: 1,
gallons: 3.785411784,
cups: 0.236588236
},
mass: {
kilogram: 1,
metricton: 0.001,
stone: 0.15747,
pound: 2.2046,
ounce: 35.274
}
},
betweenUnit = false,
type, unit;
console.log('Starting looping conversions....');
for (type in conversions) {
if (conversions[type]) {
if ((unit = conversions[type][fromUnit])) {
console.log('in side - for -Found unit');
betweenUnit = number * unit * 1000;
console.log(betweenUnit);
}
}
}
var convertTo = function (toUnit) {
console.log('function is called convertTo....'); // will be only hit when it call to()
if (betweenUnit) {
for (type in conversions) {
if (conversions.hasOwnProperty(type)) {
if ((unit = conversions[type][toUnit])) {
return fix(betweenUnit / (unit * 1000));
}
}
}
throw new Error("unrecognized to-unit");
} else {
throw new Error("unrecognized from-unit");
}
function fix(num) {
console.log('fix innerfunction called....'); // only hit from convertTo()
return parseFloat(num.toFixed(2));
}
console.log('End of conver to'); //do not coming here since it was return in top in convertTo()
};
console.log('End...'); // will be hit as end point of the Convert
return {
to: convertTo
};
console.log('End after retrun'); // never hit here sine it after return
}
function Convert(number, fromUnit) {
//Starting convert
var conversions = {
distance: {
meters: 1,
cm: 0.01,
feet: 0.3048,
inches: 0.0254,
yards: 0.9144
},
volume: {
liters: 1,
gallons: 3.785411784,
cups: 0.236588236
},
mass: {
kilogram: 1,
metricton: 0.001,
stone: 0.15747,
pound: 2.2046,
ounce: 35.274
}
},
betweenUnit = false,
type, unit;
//Starting looping conversions
for (type in conversions) {
if (conversions[type]) {
if ((unit = conversions[type][fromUnit])) {
//unit found some math logic for converstion using above json
betweenUnit = number * unit * 1000;
}
}
}
var convertTo = function (toUnit) {
// will be only hit when it call to()
if (betweenUnit) {
for (type in conversions) {
if (conversions.hasOwnProperty(type)) {
if ((unit = conversions[type][toUnit])) {
return fix(betweenUnit / (unit * 1000));
}
}
}
throw new Error("unrecognized to-unit");
} else {
throw new Error("unrecognized from-unit");
}
function fix(num) {
// only hit from convertTo()
return parseFloat(num.toFixed(2));
}
//do not coming here since it was return in top in convertTo()
};
// will be hit as end point of the Convert
return {
to: convertTo
};
// never hit here sine it after return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment