简体   繁体   中英

How to represent set of data in jQuery plug-in?

I am writing my first jQuery plug-in to do unit conversion. It's a fairly straightforward plug-in in that I take the original value, a unit I want to convert from and a unit I want to convert to (as strings, for now).

As part of this library, however, I want to be able to know which units I can convert. When I did this in F#, I could use discriminated unions to represent the types, and then have a "master" discriminated union which held each one of those types. This allowed me to work with units as one type and ensure it was typesafe (for example, I couldn't convert Grams to Meters).

How would I go about doing something like this in JavaScript? I figured I will need to use JSON to represent all the types I can convert between (maybe not?), but I don't know if I entirely understand how to do something like this. I would appreciate a starting point so I can continue researching and learning. Thank you.

You could create an array like this:

var conversions = {
    meters: {
        conversion: 1,
        unit: "length"
    },
    feet: {
        conversion: 1 / 3.28, // 1 foot is about a third of a meter
        unit: "length"
    },
    kilograms: {
        conversion: 1,
        unit: "weight"
    },
    pounds: {
        conversion: 1 / 2.204,
        unit: "weight"
    }
}

Then all you have to do is make sure that what you're converting to has the same unit as what you're converting from. Each type of unit maps onto its value in SI units (eg. all length units will convert to meters), so that you can go from any unit of one type to any other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM