Giter Club home page Giter Club logo

js-quantities's People

Contributors

adridavid avatar benasradzeviciusdevbridge avatar beradrian avatar bombledmonk avatar bryant1410 avatar cheung31 avatar chris-cunningham avatar christianp avatar cjroth avatar dubejf avatar flyorboom avatar gentooboontoo avatar glepretre avatar jan-san avatar joshrickert avatar librilex avatar limrv avatar lukelaws avatar maasencioh avatar mickeyreiss avatar n8th8n8el avatar nayar avatar nickoveracker avatar nwesterman avatar rjanicek avatar robinovitch61 avatar sheam avatar trodi avatar vsmalladi avatar zbjornson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-quantities's Issues

Incompatibility exception doesn't report units

I get a QtyError about incompatible units in an addition operation, but it doesn't say what units are incompatible! I must deduce what units the operands have. Debugging would be faster if the exception object recorded and displayed this information.

Display in baseScalar units without changing to SI units

This may be easy, but I haven't quite teased out if this is possible yet.

Goal: I have data that comes in various magnitudes and I would like to normalize the the string output to the baseScalar while retuning the baseScalar's original label with the appropriate prefix change. The units are not known ahead of time so a simple someqty.to() seems to be out.

Example :
input = [1 mW, 1 W, 433 mW, 8 W]
desired output = [0.001 W, 1 W, 0.433 W, 8 W]

someqty.toBase() offers the baseScalar number, but it changes the units to SI representation. This works well for seconds and meters, but the representation of 100mW ends up being 0.1 kg*m2/s3.

One can just call someqty.baseScalar for the value, but how does one get the baseScalar's unit without transforming the label into something that is purely si units?

Am I think about this wrong? Is there a decent method converting the base scalar with only a simple prefix change on the output.

Provide a way to know the currently running version

This is an enhancement suggestion 😉

As I don't always remember all our dependencies versions,
I like libraries that provide a way to get it, for example:

angular.version
Object {full: "1.3.0", major: 1, minor: 3, dot: 0, codeName: "superluminal-nudge"}

Then this information can be useful to know if a recent feature or fix is available.

Throw better errors

Adding a placeholder for updating errors thrown by js-quantities.

Preferably, an instance of Error should be thrown so users can handle them as they usually would other errors.

Additionally, it would be nice to have the args passed to the function printed as part of the message so that there is enough information in the message to be able to debug the issue.

If you agree, I'll send a pull request.

Thanks for the port, the library is great!

Cheers,
Jaap

Incorrect tablespoon conversion

Why does this conversion output 44 g?

var qtyunit = '3 tb';
qtyunit = Qty(qtyunit);
qtyunit = qtyunit.to('ml').toPrec('ml').toString();

Suggestion: toJSON() transport option

To persist a Qty object to a JSON store or pass to a JSON REST service it looks like you can rely on Qty#toString() roundtripping. However, it might be useful to have a Qty#toJSON() method (and a constructor/factory to match) that can serialize a richer data structure and potentially avoid some of the string generation and parsing steps.

Publish new version to NPM (current v1.5.0)

Can new version be published to NPM?

There are new functions that we would like to use that are not in current (1.5.0) NPM package (e.g. Qty.getUnits()). Thanks! Great work!

Conversions for temp (degress C<->F<->K) wrong

The code:

"<kelvin>" : [["degK","kelvin"], 1.0, "temperature", ["<kelvin>"]],
 "<celsius>" : [["degC","celsius","celsius","centigrade"], 1.0, "temperature", ["<kelvin>"]],
 "<fahrenheit>" : [["degF","fahrenheit"], 1/1.8, "temperature", ["<kelvin>"]],

TempC = TempK - 273.15

E.g., 20 degC = 293.15 degK. Currently js-quantities converts 20degC to 20degK.

Same issue with degC to degF.... js-quantities converts 20degC to 36degF ..... it should be 68degF.

From firebug console:

qty1 = new Qty("20degC");
20 degC { scalar=20, base_scalar=20, unit_name="degC", more...}
qty1.to("degK");
20 degK { scalar=20, base_scalar=20, unit_name="degK", more...}
qty2 = new Qty("20degC");
20 degC { scalar=20, base_scalar=20, unit_name="degC", more...}
qty2.to("degF");
36 degF { scalar=36, base_scalar=20, unit_name="degF", more...}

Temperature conversion issue

The conversion between degC and degK or degF takes into account the multiplication factor but not the offset. 0 degC should be 273.15 degK or 32 degF.

Can you add a field to UNITS for offset?

numerator and denominator getters to return a Qty object

Currently it seems .numerator and .denominator are used internally for consistency checking. However it would be useful to easily have access to the units of the numerator or denominator.

My particular use case is dealing with rates (unit/time). Ideally this is what I'd like to do:

var dt = Qty('1 hour');
var rate = Qty('1 kg/day');
var amount = rate.mul(dt).to(q.numeratorUnit);

I want to see how many kg I get in one hour. In general, if I define a rate of any kind, and I want to integrate it over some time interval by multiplying a time unit, I want to get back the units of the numerator. Note that the .to(...) is necessary because otherwise the units in this case will be unreduced: kg * hour / day

The best solution I've come up with came from poking around in the internals:

var dt = Qty('1 hour');
var rate = Qty('1 kg/day');
var numeratorUnit = Qty({scalar: 1, numerator: a.numerator});
var amount = rate.mul(dt).to();

This gets me the units of kg that I want.

Even if there were a getter for numerator that just returned the stringified unit name instead of the array [ '<kg>' ], that would make it much easier to work with. I know it's a nitpicky request but I wonder if there's any way to do this, or any other plans that would make this possible.

BTW, is there a simplify() or reduceUnits() function that would realize that day and hour are of the same dimension and scale the value accordingly?

Break into separate modules

It would be very useful for those of us doing client-side development if js-quantities could be split into a number of smaller CommonJS modules, so if only a few features are used the full library doesn't need to be compiled into an app bundle. As it stands, for the byte counter the library is a bit on the large size and offers many features that any single use case wouldn't need.

Fails to parse mAh (milliamp hours)

The function fails to parse units of amp hours or milliamp hours.
Qty('1 Ah'); //exception QtyError: Unit not recognized
Qty.parse('1 Ah') // null

I haven't quite dissected where it is failing as my experience with the library is minimal. It may be that the units are incompatible as is, but I'm not sure yet, nor as to the reason why.

Qty('1 A h') parses to "1 A*h" which is certainly satisfactory, but can someone with a bit deeper knowledge elaborate on why the title values do not work?

Quantities with 'NaN' scalar

I noticed an unexpected behavior when trying to instantiate quantities directly from user input.

I know the correct way to instantiate a negative quantity is, for example:

var negativeQty = new Qty('-1 m');

This returns a perfectly valid qty:

{
  scalar: -1,
  baseScalar: -1,
  signature: 1,
  _conversionCache: {},
  numerator: [
    "<meter>"
  ],
  denominator: [
    "<1>"
  ],
  initValue": "-1 m",
  _isBase": true
}

But, these strings return qty objects with NaN scalar:

new Qty('- 1 m'); // .toString() --> "NaN *1*1*m"
new Qty('+ 1 m'); // .toString() --> "NaN *1*1*m"
new Qty('- m');   // .toString() --> "NaN m"
new Qty('+ m');   // .toString() --> "NaN m"

This is the object returned by "- 1 m":

{
  scalar: NaN,
  baseScalar: NaN,
  signature: 1,
  _conversionCache: {},
  numerator: [
    "<1>",
    "<meter>"
  ],
  denominator: [
    "<1>"
  ],
  initValue: "- 1 m",
  _isBase: true
}

Use case:
Users with no scientific or programming background are more likely to write "- 1 m" as input.

This is easy to handle in our client apps but the question is: should Qty return quantities with NaN scalar? I would rather expect it to return a valid qty or an Error.

Are the scalar and baseScalar properties public?

Hi,

The scalar and baseScalar properties aren't documented in the README.md, though there's a mention in a toFloat exception:

> q('10km').toFloat();
Error: Can't convert to Float unless unitless.  Use Unit#scalar`

Are theses properties public? If so the documentation might need to be updated.

Publish to npm

Hey mate,

Thanks for all the work on this module.

Can you please update npm with v1.5.0? The version in npm doesn't contain the Qty.getKinds() method.

Unitless values with prefixes

Is it possible to use unitless values and convert them to their suffixes?
Like, for example: 1000 -> 1K, 1000K -> 1000M?

ml and cc^3 are not being simplified

js-quantities doesn't simplify ml and cm^3 corrently when doing math.

var w = Qty('1 g');
var v = Qty('1 cm^3');
var density = w.div(v);
var sample_v = Qty('100 ml');
var sample_w = sample_v.mul(density);
sample_w.toString() // returns '100 ml*g/cm3', instead of '100 g'

js-quantities does recognize ml and cm^3 as the same unit however...

var q1 = Qty('1 cm^3');
var q2 = Qty('1 ml');
q1.eq(q2); // return true

kWh unit

Hi

While testing I discovered that I cannot parse unit kWh. kW*h works just fine, but nobody is using this format. Is there a way to add this or have some kind of aliases?

Nonlinear units

Is there a plan to support nonlinear units? One example is gauge (AWG), which is a length (diameter) with a conversion: d (mm) = 0.127*92^((36-n)/39)

Return full human readable names

Great library! I'm just not sure if it's possible to get the full name of the unit from looking at the docs and code. e.g. I want to turn "m" into "meters".

Issue with conversion from mmol/L to mg/dL.

mmol/l = mg/dl / 18
mg/dl = 18 × mmol/l

Trying to make a medical calculator with js-quantities. But can't seem to convert between the two frequently used units to measure blood sugar.

Anything I'm missing?

I tried - Qty.swiftConverter('mmol/l', 'mg/dl');

Results in : "QtyError", "Incompatible units"

Thanks in advance.

TypeScript typings

Do you have any plans to create TypeScript type definitions for this package?

"C" as Celsius recognized, but "°C" is not

It would be wonderful if the degree symbol was recognized as part of a temperature unit. Then, there would be no need to strip out the ° symbol when performing calculations or conversions.

Out-of-memory crash

This is a pathological case and it should return null, but this causes a "heap out of memory" error:

Qty.parse("58261da44b642352442b8060")

because this loop attempts to make a string of 64,235,244 repetitions of "4b " (i.e. 192 MB):

      // in var parse = function(val) {
      for (var i = 0; i < Math.abs(n) ; i++) {
        nx += x;
      }

I'm not exactly sure what that loop is supposed to be doing. Should n be clamped to the length of the input, or some hard-coded default?

Access to unit list

Hi, I'm using this awesome library for a project and although there exist a way to get the "well-known kinds" it is useless to me without having a way to obtain the unit list in that category (to put in a select widget or something), the code already has the list, it is just a matter of exposing it and maybe filtering it.

Thoughts?

Fix Qty#toPrec rounding

Reported by Adam Abrams:
new Qty('0.8 cu').toPrec('0.25 cu') returns 0.8 cu but should return 0.75 cu

Infinite loop

When calling Qty.Parse('0.11 180°/sec'), the method never returns (I'm guessing an infinite loop).
I would expect it to return null.
If I change the number or remove the ° symbol it returns null as expected.

Add aliases to fluid ounces

I have a lot of data coming in formatted as 'fl oz', but it's not supported with the space so I have to do some custom parsing before handing it off to this library. Would be handy to support the spaced variants of fluid ounces: 'fl oz', 'fluid ounce', 'fluid ounces'.

Cannot multiply 2 unit-less instances

Trivial example in Chrome dev console:

> var one=new Qty('1'), foot=new Qty('ft')
undefined
> one.toString()
"1"
> foot.toString()
"1 ft"
> (one.mul(foot)).toString()
"1 ft"
> (foot.mul(one)).toString()
"1 ft"
> (foot.mul(foot)).toString()
"1 ft2"
> (one.mul(one)).toString()
ERROR: "Unit not recognized"

The error comes from to() when other is unitless

Unrecognized symbols cmH2O and inH2O

Hi, I was testing some all the units of some measurements and found some symbols that didn't work.

  • the symbols "cmH2O" and "inH2O" (pressure units) are not recognized
  • when using the grain symbol "gr" to any mass unit an incompatible unit exception is thrown

Problems with using js-quantities to parse engineering input

I'm trying to use js-quantities to parse input for an engineering simulation. I want users to enter input in any units by writing both the unit value and name. Ex, for a weight field, all of these would be acceptable:

160 kg
40 lbs
200 pound
14 microgram

This works by doing: (new Qty(element.val())).to("kg").scalar!

However, I have problems with a few other fields in my app:

Torque

While torque is supported, as it has the same dimension as energy, js-quantities will accept units of energy in a torque field. Additionally, while the dimension of lb ft is technically incorrect, torque is often expressed in these units (just look at any american automotive brochure)

new Qty('12 W h').to('N m').scalar;
43200

new Qty('278 lb ft').to('N m').scalar; //copied input string from ford.com
"Incompatible units"

Namespace collisions

The temperature field should naturally support the units C, F and K. Because of namespace collisions with farads and coulombs, temperature units are prepended with "temp", ie "tempC". This is not intuitive. Additionally, js-quantities will convert a temperature difference to an absolute temperature without error:

new Qty('12 degC').to('tempC').scalar;
-261.15

This is problematic, because to a user, "degC" actually sounds more correct than "tempC" because the common phrase is "degrees celsius". Ideally, valid inputs would include:

14.5 C
88 F
321 K

Derived unit parsing

Derived units require spaces between their components. This is not intuitive.

new Qty('12 kWh').to('J').scalar;
"Unit not recognized"

new Qty('12 Ah').to('C').scalar;
"Unit not recognized"

Conclusions

All of these problems stem from js-quantities not accepting any context about what unit it's trying to parse. This seems to suggest I am using this library for something it was not intended to do. I thought I'd post these gripes here because @gentooboontoo recently commented on a stackoverflow question, but I don't expect these to be fixed. I'm now looking at either finding another library or forking this one to make the changes I need.

"force" is defined incorrectly.

Since Force is kg m/s^2, and

mass: 8000
length: 1
time: 20

We should have force: 8000+1-40 = 7961

However, in "kinds", force is incorrectly described with the identifier 7981. So, a N_s will be described as a force if you use Qty('1 N_s').kind()

Torque

There is currently no support for units of torque. Newton meters, pound feet, etc.

'1 Mohm' interpreted as 'molar ohm'

In electronic engineering 1Mohm is typically 1000,000 Ohm.

> Qty = require('js-quantities')
> k = Qty('1kohm')
Qty {
  scalar: 1,
  baseScalar: 1000,
  signature: -312058,
  _conversionCache: {},
  numerator: [ '<kilo>', '<ohm>' ],
  denominator: [ '<1>' ],
  initValue: '1kohm',
  _isBase: false,
  _units: 'kOhm' }
> m = Qty('1Mohm')
Qty {
  scalar: 1,
  baseScalar: 1000,
  signature: 2887939,
  _conversionCache: {},
  numerator: [ '<molar>', '<ohm>' ],
  denominator: [ '<1>' ],
  initValue: '1Mohm',
  _isBase: false,
  _units: 'M*Ohm' }
> k.eq(m)
Error: Incompatible units
    at QtyError.Error (native)
    at new QtyError (./node_modules/js-quantities/src/quantities.js:1954:17)
    at throwIncompatibleUnits (./node_modules/js-quantities/src/quantities.js:764:11)
    at Qty.compareTo (./node_modules/js-quantities/src/quantities.js:1037:9)
    at Qty.eq (./node_modules/js-quantities/src/quantities.js:890:19)
    at repl:1:3
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:313:29)

Additionally it would be great to be able to space things like 1k ohm. Super nice bonus would be to be able to use EE convention of putting the quantifier instead of the decimal e.g. 1k5 ohm.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.