gentooboontoo / js-quantities Goto Github PK
View Code? Open in Web Editor NEWJavaScript library for quantity calculation and unit conversion
Home Page: http://gentooboontoo.github.io/js-quantities/
License: MIT License
JavaScript library for quantity calculation and unit conversion
Home Page: http://gentooboontoo.github.io/js-quantities/
License: MIT License
In the source, there's a comment about parsing USA/Imperial style values, like 8lbs 6oz
or 6'4"
However, if we try new Qty('6\' 6"')
, it fails with the errorQtyError {name: "QtyError", message: "Unit not recognized"}
So, is this a bug? or, a intended feature of js-quantities
? Or, just an old/ outdated comment?
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.
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.
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.
For those with a js-quantities
dependency configured to ~1.6.3
this patch release will break builds if transpiling to ES6 is not a part of the build pipeline.
Perhaps v1.6.4 release should be a major release?
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
For some reason Qty.parse('10 lb').kind() is reporting mass. Obviously the 10 is insignificant.
Why does this conversion output 44 g?
var qtyunit = '3 tb';
qtyunit = Qty(qtyunit);
qtyunit = qtyunit.to('ml').toPrec('ml').toString();
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.
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!
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...}
The default for litre is currently small l, should that not be big L?
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?
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?
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.
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?
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
.
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.
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.
Reported in #33
All quantities created with base units and without prefixes do not have the property _units
defined.
Example: Qty('1 A')._units
is undefined
, Qty('1 kg'))._units
as well.
Is this a bug or on purpose?
(tested with v1.6.6)
Is it possible to use unitless values and convert them to their suffixes?
Like, for example: 1000 -> 1K, 1000K -> 1000M?
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
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?
http://en.wikipedia.org/wiki/Standard_Litres_Per_Minute
Can be implemented by adding standard litre as an alias to litre. Basically useful for printing, to indicate it being standard litres.
This may not be necessary, but it would be nice to have a feature that could normalize labels to powers of 10^(3*n) given the prominence of engineering notation.
Example:
Qty('.0001 mA').toEng() // output = 100 uA
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)
Could help with errors like issue #4.
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".
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.
1 US Gallons = 0.832674 Imperial Gallons
MPG and L/100KM
mpg and l/100km
~~Conversion base : 1 l/100km = 235.2145833 mpg ~~
Conversion base : 1 mpg = 235.2145833 l/100km
More information here. https://www.unitjuggler.com/convert-fuelconsumption-from-lper100km-to-mpgimperial.html?val=14
Edit:
More Info here seems to be more complicated than i first thought, http://www.wikihow.com/Convert-MPG-to-Liters-per-100km
It seems that some kind definitions have diverged from ruby-units' ones (lib/ruby_units/unit.rb
).
Reported by @rage-shadowman in #17.
Do you have any plans to create TypeScript type definitions for this package?
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.
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?
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?
Reported by Adam Abrams:
new Qty('0.8 cu').toPrec('0.25 cu') returns 0.8 cu but should return 0.75 cu
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.
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'
.
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
See olbrich/ruby-units@ce2e3c7
Apparently they should be: (12 kg/mol)/(12 * (6.02214129e23/mol))
Or at least that's what ruby-units updated them to be in the above referenced commit (assuming I didn't insert a typo).
Hi, I was testing some all the units of some measurements and found some symbols that didn't work.
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:
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"
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 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"
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.
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()
There is currently no support for units of torque. Newton meters, pound feet, etc.
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
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.