JSPM

  • Created
  • Published
  • Downloads 9
  • Score
    100M100P100Q61536F
  • License MIT

Flexible linear converter with built in conversions for common units

Package Exports

  • linear-converter

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (linear-converter) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

linear-converter

Build Status Coverage Status Code Climate

Flexible linear converter with built in conversions for common units

Install

npm i linear-converter

Basic usage

var lc = require('linear-converter');

lc.convert(25, lc.PRESETS.temperature.celsiusToFahrenheit); // => 77

Preset inversion

The provided presets go in one direction only; to invert the direction, use invertPreset:

lc.convert(77, lc.invertPreset(lc.PRESETS.temperature.celsiusToFahrenheit)); // => 25

Presets composition

The provided presets have a base unit from which to convert. Any to any conversions are straightforward using inversion and composition with composePresets:

var kelvinToFahrenheit = lc.composePresets([
  lc.invertPreset(lc.PRESETS.temperature.celsiusToKelvin),
  lc.PRESETS.temperature.celsiusToFahrenheit
]);

lc.convert(293.15, kelvinToFahrenheit); // => 68

Custom conversions

Custom conversions are easily achieved by passing an array with 2 scales, each of those an array with 2 values. For example, [[0, 1], [0, 2]] means that 0 and 1 in the first scale map to 0 and 2 in the second scale respectively; in short, it multiplies by 2. Any linear function can be described that way:

// f(x) = ax + b
lc.convert(x, [[0, 1], [b, a+b]]); // => ax + b
lc.convert(x, [[1/a, -b/a], [b+1, 0]]); // => ax + b

For an arbitrary f(x) = ax + b, any [[x1, x2], [f(x1), f(x2)]] is a valid preset.

More examples:

// degrees to radians
lc.convert(240, [[0, 180], [0, Math.PI]]); // => 4 * Math.PI / 3

// f(x) = 3x
lc.convert(5, [[0, 1/3], [0, 1]]); // => 15

// f(x) = -2x - 46
lc.convert(-23, [[0, 1], [-46, -48]]); // => 0

Coefficients

Creating presets from a given function is trivial; to find the function from a given preset, two methods are provided: getCoefficientA and getCoefficientB.

// f(x) = 2x + 1
lc.getCoefficientA([[0, 1], [1, 3]]); // => 2
lc.getCoefficientB([[0, 1], [1, 3]]); // => 1

// f(x) = ax + b
lc.getCoefficientA([[x1, x2], [f(x1), f(x2)]]); // => a
lc.getCoefficientB([[x1, x2], [f(x1), f(x2)]]); // => b

See more