Fawar
Fawar

Reputation: 735

Efficient way to convert units from one system to another

I'm having an hard time figuring an efficient way to converts differents types of unit to various other types.

Switch cases would work, but IMO that's not an efficient way has I will have 3 different Systems (SI, Imperial and US).

My converter (inside my app) will always convert from SI to something or from something to SI. It kinds of lower the complexity, but yet I still need advice on how to make clean code.

I had defined that my input parameters for conversion would be Value(number) and Unit(string).
I would have 2 functions. SIToSomething(value, unit) and SOmethingToSi(value, unit).

Unit is defined because I would be converting length, weight, qty etc..

What would you suggest ?

Upvotes: 1

Views: 602

Answers (3)

bfavaretto
bfavaretto

Reputation: 71918

How about this:

var converters = {
    'SIToImperial' : {
        'cm' : function(val) {
            // implementation, return something
        },
        'kg' : function(val) {
            // implementation, return something
        } //, etc.
    },
    'SIToUS' : {
        'cm' : function(val) {
            // implementation, return something
        },
        'kg' : function(val) {
            // implementation, return something
        } //, etc.
    },
    'USToSI' : {
        'cm' : function(val) { /* ... */ } // etc
    } // , etc
}

SIToSomething(value, unit, system) {
    return converters["SITo" + system][unit](value);
}

var meterInImperial = SIToSomething(100, 'cm', 'Imperial');
var fiftyKilosInUS = SIToSomething(50, 'kg', 'US');

Upvotes: 3

ninjagecko
ninjagecko

Reputation: 91094

Do all conversions to/from SI. For example if converting Imperial->US, you'd go Imperial->SI->US.

This is minimal effort you can put in. It also gets you SI "for free".

Upvotes: 0

Jacob
Jacob

Reputation: 78848

What you can do is have a base unit, and for each target unit, define conversion functions to/from this base unit. Then, to convert from A to B, for example, you'd have this:

A -> base -> B

This way, you only need two conversion functions per unit (not counting the base unit):

var units = {
    a: {
        toBase: function(value) { return value * 2; },
        fromBase: function(value) { return value / 2; }
    },
    b: {
        toBase: function(value) { return 1.734 * value + 48; },
        fromBase: function(value) { return (value / 1.734) - 48; }
    }
}

function convertFromTo(unitA, unitB, value) {
    return unitB.fromBase(unitA.toBase(value));
}

convertFromTo(units.a, units.b, 36489);

Upvotes: 2

Related Questions