forked from bombledmonk/advancedsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quantities.js
1776 lines (1566 loc) · 58.1 KB
/
quantities.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
Copyright © 2006-2007 Kevin C. Olbrich
Copyright © 2010-2013 LIM SAS (http://lim.eu) - Julien Sanchez
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jshint eqeqeq:true, immed:true, undef:true */
/*global module:false, define:false */
(function (root, factory) {
"use strict";
if (typeof exports === "object") {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals
root.Qty = factory();
}
}(this, function() {
"use strict";
var UNITS = {
/* prefixes */
"<googol>" : [["googol"], 1e100, "prefix"],
"<kibi>" : [["Ki","Kibi","kibi"], Math.pow(2,10), "prefix"],
"<mebi>" : [["Mi","Mebi","mebi"], Math.pow(2,20), "prefix"],
"<gibi>" : [["Gi","Gibi","gibi"], Math.pow(2,30), "prefix"],
"<tebi>" : [["Ti","Tebi","tebi"], Math.pow(2,40), "prefix"],
"<pebi>" : [["Pi","Pebi","pebi"], Math.pow(2,50), "prefix"],
"<exi>" : [["Ei","Exi","exi"], Math.pow(2,60), "prefix"],
"<zebi>" : [["Zi","Zebi","zebi"], Math.pow(2,70), "prefix"],
"<yebi>" : [["Yi","Yebi","yebi"], Math.pow(2,80), "prefix"],
"<yotta>" : [["Y","Yotta","yotta"], 1e24, "prefix"],
"<zetta>" : [["Z","Zetta","zetta"], 1e21, "prefix"],
"<exa>" : [["E","Exa","exa"], 1e18, "prefix"],
"<peta>" : [["P","Peta","peta"], 1e15, "prefix"],
"<tera>" : [["T","Tera","tera"], 1e12, "prefix"],
"<giga>" : [["G","Giga","giga"], 1e9, "prefix"],
"<mega>" : [["M","Mega","mega"], 1e6, "prefix"],
"<kilo>" : [["k","kilo"], 1e3, "prefix"],
"<hecto>" : [["h","Hecto","hecto"], 1e2, "prefix"],
"<deca>" : [["da","Deca","deca","deka"], 1e1, "prefix"],
"<deci>" : [["d","Deci","deci"], 1e-1, "prefix"],
"<centi>" : [["c","Centi","centi"], 1e-2, "prefix"],
"<milli>" : [["m","Milli","milli"], 1e-3, "prefix"],
"<micro>" : [["u","µ","Micro","mc","micro"], 1e-6, "prefix"],
"<nano>" : [["n","Nano","nano"], 1e-9, "prefix"],
"<pico>" : [["p","Pico","pico"], 1e-12, "prefix"],
"<femto>" : [["f","Femto","femto"], 1e-15, "prefix"],
"<atto>" : [["a","Atto","atto"], 1e-18, "prefix"],
"<zepto>" : [["z","Zepto","zepto"], 1e-21, "prefix"],
"<yocto>" : [["y","Yocto","yocto"], 1e-24, "prefix"],
"<1>" : [["1", "<1>"], 1, ""],
/* length units */
"<meter>" : [["m","meter","meters","metre","metres"], 1.0, "length", ["<meter>"] ],
"<inch>" : [["in","inch","inches","\""], 0.0254, "length", ["<meter>"]],
"<foot>" : [["ft","foot","feet","'"], 0.3048, "length", ["<meter>"]],
"<yard>" : [["yd","yard","yards"], 0.9144, "length", ["<meter>"]],
"<mile>" : [["mi","mile","miles"], 1609.344, "length", ["<meter>"]],
"<naut-mile>" : [["nmi"], 1852, "length", ["<meter>"]],
"<league>": [["league","leagues"], 4828, "length", ["<meter>"]],
"<furlong>": [["furlong","furlongs"], 201.2, "length", ["<meter>"]],
"<rod>" : [["rd","rod","rods"], 5.029, "length", ["<meter>"]],
"<mil>" : [["mil","mils"], 0.0000254, "length", ["<meter>"]],
"<angstrom>" :[["ang","angstrom","angstroms"], 1e-10, "length", ["<meter>"]],
"<fathom>" : [["fathom","fathoms"], 1.829, "length", ["<meter>"]],
"<pica>" : [["pica","picas"], 0.00423333333, "length", ["<meter>"]],
"<point>" : [["pt","point","points"], 0.000352777778, "length", ["<meter>"]],
"<redshift>" : [["z","red-shift"], 1.302773e26, "length", ["<meter>"]],
"<AU>" : [["AU","astronomical-unit"], 149597900000, "length", ["<meter>"]],
"<light-second>":[["ls","light-second"], 299792500, "length", ["<meter>"]],
"<light-minute>":[["lmin","light-minute"], 17987550000, "length", ["<meter>"]],
"<light-year>" : [["ly","light-year"], 9460528000000000, "length", ["<meter>"]],
"<parsec>" : [["pc","parsec","parsecs"], 30856780000000000, "length", ["<meter>"]],
/* mass */
"<kilogram>" : [["kg","kilogram","kilograms"], 1.0, "mass", ["<kilogram>"]],
"<AMU>" : [["u","AMU","amu"], 6.0221415e26, "mass", ["<kilogram>"]],
"<dalton>" : [["Da","Dalton","Daltons","dalton","daltons"], 6.0221415e26, "mass", ["<kilogram>"]],
"<slug>" : [["slug","slugs"], 14.5939029, "mass", ["<kilogram>"]],
"<short-ton>" : [["tn","ton"], 907.18474, "mass", ["<kilogram>"]],
"<metric-ton>":[["tonne"], 1000, "mass", ["<kilogram>"]],
"<carat>" : [["ct","carat","carats"], 0.0002, "mass", ["<kilogram>"]],
"<pound>" : [["lbs","lb","pound","pounds","#"], 0.45359237, "mass", ["<kilogram>"]],
"<ounce>" : [["oz","ounce","ounces"], 0.0283495231, "mass", ["<kilogram>"]],
"<gram>" : [["g","gram","grams","gramme","grammes"], 1e-3, "mass", ["<kilogram>"]],
"<grain>" : [["grain","grains","gr"], 6.479891e-5, "mass", ["<kilogram>"]],
"<dram>" : [["dram","drams","dr"], 0.0017718452, "mass",["<kilogram>"]],
"<stone>" : [["stone","stones","st"],6.35029318, "mass",["<kilogram>"]],
/* area */
"<hectare>":[["hectare"], 10000, "area", ["<meter>","<meter>"]],
"<acre>":[["acre","acres"], 4046.85642, "area", ["<meter>","<meter>"]],
"<sqft>":[["sqft"], 1, "area", ["<feet>","<feet>"]],
/* volume */
"<liter>" : [["l","L","liter","liters","litre","litres"], 0.001, "volume", ["<meter>","<meter>","<meter>"]],
"<gallon>": [["gal","gallon","gallons"], 0.0037854118, "volume", ["<meter>","<meter>","<meter>"]],
"<quart>": [["qt","quart","quarts"], 0.00094635295, "volume", ["<meter>","<meter>","<meter>"]],
"<pint>": [["pt","pint","pints"], 0.000473176475, "volume", ["<meter>","<meter>","<meter>"]],
"<cup>": [["cu","cup","cups"], 0.000236588238, "volume", ["<meter>","<meter>","<meter>"]],
"<fluid-ounce>": [["floz","fluid-ounce"], 2.95735297e-5, "volume", ["<meter>","<meter>","<meter>"]],
"<tablespoon>": [["tbs","tablespoon","tablespoons"], 1.47867648e-5, "volume", ["<meter>","<meter>","<meter>"]],
"<teaspoon>": [["tsp","teaspoon","teaspoons"], 4.92892161e-6, "volume", ["<meter>","<meter>","<meter>"]],
"<bushel>": [["bu","bsh","bushel","bushels"], 0.035239072, "volume", ["<meter>","<meter>","<meter>"]],
/* speed */
"<kph>" : [["kph"], 0.277777778, "speed", ["<meter>"], ["<second>"]],
"<mph>" : [["mph"], 0.44704, "speed", ["<meter>"], ["<second>"]],
"<knot>" : [["kt","kn","kts","knot","knots"], 0.514444444, "speed", ["<meter>"], ["<second>"]],
"<fps>" : [["fps"], 0.3048, "speed", ["<meter>"], ["<second>"]],
/* acceleration */
"<gee>" : [["gee"], 9.80665, "acceleration", ["<meter>"], ["<second>","<second>"]],
/* temperature_difference */
"<kelvin>" : [["degK","kelvin"], 1.0, "temperature", ["<kelvin>"]],
"<celsius>" : [["degC","celsius","celsius","centigrade"], 1.0, "temperature", ["<kelvin>"]],
"<fahrenheit>" : [["degF","fahrenheit"], 5/9, "temperature", ["<kelvin>"]],
"<rankine>" : [["degR","rankine"], 5/9, "temperature", ["<kelvin>"]],
"<temp-K>" : [["tempK"], 1.0, "temperature", ["<temp-K>"]],
"<temp-C>" : [["tempC"], 1.0, "temperature", ["<temp-K>"]],
"<temp-F>" : [["tempF"], 5/9, "temperature", ["<temp-K>"]],
"<temp-R>" : [["tempR"], 5/9, "temperature", ["<temp-K>"]],
/* time */
"<second>": [["s","sec","secs","second","seconds"], 1.0, "time", ["<second>"]],
"<minute>": [["min","mins","minute","minutes"], 60.0, "time", ["<second>"]],
"<hour>": [["h","hr","hrs","hour","hours"], 3600.0, "time", ["<second>"]],
"<day>": [["d","day","days"], 3600*24, "time", ["<second>"]],
"<week>": [["wk","week","weeks"], 7*3600*24, "time", ["<second>"]],
"<fortnight>": [["fortnight","fortnights"], 1209600, "time", ["<second>"]],
"<year>": [["y","yr","year","years","annum"], 31556926, "time", ["<second>"]],
"<decade>":[["decade","decades"], 315569260, "time", ["<second>"]],
"<century>":[["century","centuries"], 3155692600, "time", ["<second>"]],
/* pressure */
"<pascal>" : [["Pa","pascal","Pascal"], 1.0, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<bar>" : [["bar","bars"], 100000, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<mmHg>" : [["mmHg"], 133.322368, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<inHg>" : [["inHg"], 3386.3881472, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<torr>" : [["torr"], 133.322368, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<atm>" : [["atm","ATM","atmosphere","atmospheres"], 101325, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<psi>" : [["psi"], 6894.76, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<cmh2o>" : [["cmH2O"], 98.0638, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
"<inh2o>" : [["inH2O"], 249.082052, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]],
/* viscosity */
"<poise>" : [["P","poise"], 0.1, "viscosity", ["<kilogram>"],["<meter>","<second>"] ],
"<stokes>" : [["St","stokes"], 1e-4, "viscosity", ["<meter>","<meter>"], ["<second>"]],
/* substance */
"<mole>" : [["mol","mole"], 1.0, "substance", ["<mole>"]],
/* concentration */
"<molar>" : [["M","molar"], 1000, "concentration", ["<mole>"], ["<meter>","<meter>","<meter>"]],
"<wtpercent>" : [["wt%","wtpercent"], 10, "concentration", ["<kilogram>"], ["<meter>","<meter>","<meter>"]],
/* activity */
"<katal>" : [["kat","katal","Katal"], 1.0, "activity", ["<mole>"], ["<second>"]],
"<unit>" : [["U","enzUnit"], 16.667e-16, "activity", ["<mole>"], ["<second>"]],
/* capacitance */
"<farad>" : [["F","farad","Farad"], 1.0, "capacitance", ["<farad>"]],
/* charge */
"<coulomb>" : [["C","coulomb","Coulomb"], 1.0, "charge", ["<ampere>","<second>"]],
/* current */
"<ampere>" : [["A","Ampere","ampere","amp","amps"], 1.0, "current", ["<ampere>"]],
/* conductance */
"<siemens>" : [["S","Siemens","siemens"], 1.0, "conductance", ["<second>","<second>","<second>","<ampere>","<ampere>"], ["<kilogram>","<meter>","<meter>"]],
/* inductance */
"<henry>" : [["H","Henry","henry"], 1.0, "inductance", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>","<ampere>","<ampere>"]],
/* potential */
"<volt>" : [["V","Volt","volt","volts"], 1.0, "potential", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>","<second>","<ampere>"]],
/* resistance */
"<ohm>" : [["Ohm","ohm"], 1.0, "resistance", ["<meter>","<meter>","<kilogram>"],["<second>","<second>","<second>","<ampere>","<ampere>"]],
/* magnetism */
"<weber>" : [["Wb","weber","webers"], 1.0, "magnetism", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>","<ampere>"]],
"<tesla>" : [["T","tesla","teslas"], 1.0, "magnetism", ["<kilogram>"], ["<second>","<second>","<ampere>"]],
"<gauss>" : [["G","gauss"], 1e-4, "magnetism", ["<kilogram>"], ["<second>","<second>","<ampere>"]],
"<maxwell>" : [["Mx","maxwell","maxwells"], 1e-8, "magnetism", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>","<ampere>"]],
"<oersted>" : [["Oe","oersted","oersteds"], 250.0/Math.PI, "magnetism", ["<ampere>"], ["<meter>"]],
/* energy */
"<joule>" : [["J","joule","Joule","joules"], 1.0, "energy", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]],
"<erg>" : [["erg","ergs"], 1e-7, "energy", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]],
"<btu>" : [["BTU","btu","BTUs"], 1055.056, "energy", ["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]],
"<calorie>" : [["cal","calorie","calories"], 4.18400, "energy",["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]],
"<Calorie>" : [["Cal","Calorie","Calories"], 4184.00, "energy",["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]],
"<therm-US>" : [["th","therm","therms","Therm"], 105480400, "energy",["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]],
/* force */
"<newton>" : [["N","Newton","newton"], 1.0, "force", ["<kilogram>","<meter>"], ["<second>","<second>"]],
"<dyne>" : [["dyn","dyne"], 1e-5, "force", ["<kilogram>","<meter>"], ["<second>","<second>"]],
"<pound-force>" : [["lbf","pound-force"], 4.448222, "force", ["<kilogram>","<meter>"], ["<second>","<second>"]],
/* frequency */
"<hertz>" : [["Hz","hertz","Hertz"], 1.0, "frequency", ["<1>"], ["<second>"]],
/* angle */
"<radian>" :[["rad","radian","radians"], 1.0, "angle", ["<radian>"]],
"<degree>" :[["deg","degree","degrees"], Math.PI / 180.0, "angle", ["<radian>"]],
"<gradian>" :[["gon","grad","gradian","grads"], Math.PI / 200.0, "angle", ["<radian>"]],
"<steradian>" : [["sr","steradian","steradians"], 1.0, "solid_angle", ["<steradian>"]],
/* rotation */
"<rotation>" : [["rotation"], 2.0*Math.PI, "angle", ["<radian>"]],
"<rpm>" :[["rpm"], 2.0*Math.PI / 60.0, "angular_velocity", ["<radian>"], ["<second>"]],
/* memory */
"<byte>" :[["B","byte"], 1.0, "memory", ["<byte>"]],
"<bit>" :[["b","bit"], 0.125, "memory", ["<byte>"]],
/* currency */
"<dollar>":[["USD","dollar"], 1.0, "currency", ["<dollar>"]],
"<cents>" :[["cents"], 0.01, "currency", ["<dollar>"]],
/* luminosity */
"<candela>" : [["cd","candela"], 1.0, "luminosity", ["<candela>"]],
"<lumen>" : [["lm","lumen"], 1.0, "luminous_power", ["<candela>","<steradian>"]],
"<lux>" :[["lux"], 1.0, "illuminance", ["<candela>","<steradian>"], ["<meter>","<meter>"]],
/* power */
"<watt>" : [["W","watt","watts"], 1.0, "power", ["<kilogram>","<meter>","<meter>"], ["<second>","<second>","<second>"]],
"<horsepower>" : [["hp","horsepower"], 745.699872, "power", ["<kilogram>","<meter>","<meter>"], ["<second>","<second>","<second>"]],
/* radiation */
"<gray>" : [["Gy","gray","grays"], 1.0, "radiation", ["<meter>","<meter>"], ["<second>","<second>"]],
"<roentgen>" : [["R","roentgen"], 0.009330, "radiation", ["<meter>","<meter>"], ["<second>","<second>"]],
"<sievert>" : [["Sv","sievert","sieverts"], 1.0, "radiation", ["<meter>","<meter>"], ["<second>","<second>"]],
"<becquerel>" : [["Bq","bequerel","bequerels"], 1.0, "radiation", ["<1>"],["<second>"]],
"<curie>" : [["Ci","curie","curies"], 3.7e10, "radiation", ["<1>"],["<second>"]],
/* rate */
"<cpm>" : [["cpm"], 1.0/60.0, "rate", ["<count>"],["<second>"]],
"<dpm>" : [["dpm"], 1.0/60.0, "rate", ["<count>"],["<second>"]],
"<bpm>" : [["bpm"], 1.0/60.0, "rate", ["<count>"],["<second>"]],
/* resolution / typography */
"<dot>" : [["dot","dots"], 1, "resolution", ["<each>"]],
"<pixel>" : [["pixel","px"], 1, "resolution", ["<each>"]],
"<ppi>" : [["ppi"], 1, "resolution", ["<pixel>"], ["<inch>"]],
"<dpi>" : [["dpi"], 1, "typography", ["<dot>"], ["<inch>"]],
/* other */
"<cell>" : [["cells","cell"], 1, "counting", ["<each>"]],
"<each>" : [["each"], 1.0, "counting", ["<each>"]],
"<count>" : [["count"], 1.0, "counting", ["<each>"]],
"<base-pair>" : [["bp"], 1.0, "counting", ["<each>"]],
"<nucleotide>" : [["nt"], 1.0, "counting", ["<each>"]],
"<molecule>" : [["molecule","molecules"], 1.0, "counting", ["<1>"]],
"<dozen>" : [["doz","dz","dozen"],12.0,"prefix_only", ["<each>"]],
"<percent>": [["%","percent"], 0.01, "prefix_only", ["<1>"]],
"<ppm>" : [["ppm"],1e-6, "prefix_only", ["<1>"]],
"<ppt>" : [["ppt"],1e-9, "prefix_only", ["<1>"]],
"<gross>" : [["gr","gross"],144.0, "prefix_only", ["<dozen>","<dozen>"]],
"<decibel>" : [["dB","decibel","decibels"], 1.0, "logarithmic", ["<decibel>"]]
};
var BASE_UNITS = ["<meter>","<kilogram>","<second>","<mole>", "<farad>", "<ampere>","<radian>","<kelvin>","<temp-K>","<byte>","<dollar>","<candela>","<each>","<steradian>","<decibel>"];
var UNITY = "<1>";
var UNITY_ARRAY= [UNITY];
var SIGN = "[+-]";
var INTEGER = "\\d+";
var SIGNED_INTEGER = SIGN + "?" + INTEGER;
var FRACTION = "\\." + INTEGER;
var FLOAT = "(?:" + INTEGER + "(?:" + FRACTION + ")?" + ")" +
"|" +
"(?:" + FRACTION + ")";
var EXPONENT = "[Ee]" + SIGNED_INTEGER;
var SCI_NUMBER = "(?:" + FLOAT + ")(?:" + EXPONENT + ")?";
var SIGNED_NUMBER = SIGN + "?\\s*" + SCI_NUMBER;
var QTY_STRING = "(" + SIGNED_NUMBER + ")?" + "\\s*([^/]*)(?:\/(.+))?";
var QTY_STRING_REGEX = new RegExp("^" + QTY_STRING + "$");
var POWER_OP = "\\^|\\*{2}";
var TOP_REGEX = new RegExp ("([^ \\*]+?)(?:" + POWER_OP + ")?(-?\\d+)");
var BOTTOM_REGEX = new RegExp("([^ \\*]+?)(?:" + POWER_OP + ")?(\\d+)");
var SIGNATURE_VECTOR = ["length", "time", "temperature", "mass", "current", "substance", "luminosity", "currency", "memory", "angle", "capacitance"];
var KINDS = {
"-312058": "resistance",
"-312038": "inductance",
"-152040": "magnetism",
"-152038": "magnetism",
"-152058": "potential",
"-39": "acceleration",
"-38": "radiation",
"-20": "frequency",
"-19": "speed",
"-18": "viscosity",
"0": "unitless",
"1": "length",
"2": "area",
"3": "volume",
"20": "time",
"400": "temperature",
"7942": "power",
"7959": "pressure",
"7962": "energy",
"7979": "viscosity",
"7961": "force",
"7997": "mass_concentration",
"8000": "mass",
"159999": "magnetism",
"160000": "current",
"160020": "charge",
"312058": "conductance",
"3199980": "activity",
"3199997": "molar_concentration",
"3200000": "substance",
"63999998": "illuminance",
"64000000": "luminous_power",
"1280000000": "currency",
"25600000000": "memory",
"511999999980": "angular_velocity",
"512000000000": "angle",
"10240000000000": "capacitance"
};
var baseUnitCache = {};
function Qty(initValue) {
assertValidInitializationValueType(initValue);
if(!(isQty(this))) {
return new Qty(initValue);
}
this.scalar = null;
this.baseScalar = null;
this.signature = null;
this._conversionCache = {};
this.numerator = UNITY_ARRAY;
this.denominator = UNITY_ARRAY;
if (isDefinitionObject(initValue)) {
this.scalar = initValue.scalar;
this.numerator = (initValue.numerator && initValue.numerator.length !== 0)? initValue.numerator : UNITY_ARRAY;
this.denominator = (initValue.denominator && initValue.denominator.length !== 0)? initValue.denominator : UNITY_ARRAY;
}
else {
parse.call(this, initValue);
}
// math with temperatures is very limited
if(this.denominator.join("*").indexOf("temp") >= 0) {
throw new QtyError("Cannot divide with temperatures");
}
if(this.numerator.join("*").indexOf("temp") >= 0) {
if(this.numerator.length > 1) {
throw new QtyError("Cannot multiply by temperatures");
}
if(!compareArray(this.denominator, UNITY_ARRAY)) {
throw new QtyError("Cannot divide with temperatures");
}
}
this.initValue = initValue;
updateBaseScalar.call(this);
if(this.isTemperature() && this.baseScalar < 0) {
throw new QtyError("Temperatures must not be less than absolute zero");
}
}
/**
* Parses a string as a quantity
* @param {string} value - quantity as text
* @throws if value is not a string
* @returns {Qty|null} Parsed quantity or null if unrecognized
*/
Qty.parse = function parse(value) {
if(!isString(value)) {
throw new QtyError("Argument should be a string");
}
try {
return Qty(value);
}
catch(e) {
return null;
}
};
/**
* Configures and returns a fast function to convert
* Number values from units to others.
* Useful to efficiently convert large array of values
* with same units into others with iterative methods.
* Does not take care of rounding issues.
*
* @param {string} srcUnits Units of values to convert
* @param {string} dstUnits Units to convert to
*
* @returns {Function} Converting function accepting Number value
* and returning converted value
*
* @throws "Incompatible units" if units are incompatible
*
* @example
* // Converting large array of numbers with the same units
* // into other units
* var converter = Qty.swiftConverter("m/h", "ft/s");
* var convertedSerie = largeSerie.map(converter);
*
*/
Qty.swiftConverter = function swiftConverter(srcUnits, dstUnits) {
var srcQty = Qty(srcUnits);
var dstQty = Qty(dstUnits);
if(srcQty.eq(dstQty)) {
return identity;
}
var convert;
if(!srcQty.isTemperature()) {
convert = function(value) {
return value * srcQty.baseScalar / dstQty.baseScalar;
};
}
else {
convert = function(value) {
// TODO Not optimized
return srcQty.mul(value).to(dstQty).scalar;
};
}
return function converter(value) {
var i,
length,
result;
if(!Array.isArray(value)) {
return convert(value);
}
else {
length = value.length;
result = [];
for(i = 0; i < length; i++) {
result.push(convert(value[i]));
}
return result;
}
};
};
/**
* Default formatter
*
* @param {number} scalar
* @param {string} units
*
* @returns {string} formatted result
*/
function defaultFormatter(scalar, units) {
return (scalar + " " + units).trim();
}
/**
*
* Configurable Qty default formatter
*
* @type {function}
*
* @param {number} scalar
* @param {string} units
*
* @returns {string} formatted result
*/
Qty.formatter = defaultFormatter;
var updateBaseScalar = function () {
if(this.baseScalar) {
return this.baseScalar;
}
if(this.isBase()) {
this.baseScalar = this.scalar;
this.signature = unitSignature.call(this);
}
else {
var base = this.toBase();
this.baseScalar = base.scalar;
this.signature = base.signature;
}
};
/*
calculates the unit signature id for use in comparing compatible units and simplification
the signature is based on a simple classification of units and is based on the following publication
Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering,
21(8), Aug 1995, pp.651-661
doi://10.1109/32.403789
http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel1/32/9079/00403789.pdf?isnumber=9079&prod=JNL&arnumber=403789&arSt=651&ared=661&arAuthor=Novak%2C+G.S.%2C+Jr.
*/
var unitSignature = function () {
if(this.signature) {
return this.signature;
}
var vector = unitSignatureVector.call(this);
for(var i = 0; i < vector.length; i++) {
vector[i] *= Math.pow(20, i);
}
return vector.reduce(function(previous, current) {return previous + current;}, 0);
};
// calculates the unit signature vector used by unit_signature
var unitSignatureVector = function () {
if(!this.isBase()) {
return unitSignatureVector.call(this.toBase());
}
var vector = new Array(SIGNATURE_VECTOR.length);
for(var i = 0; i < vector.length; i++) {
vector[i] = 0;
}
var r, n;
for(var j = 0; j < this.numerator.length; j++) {
if((r = UNITS[this.numerator[j]])) {
n = SIGNATURE_VECTOR.indexOf(r[2]);
if(n >= 0) {
vector[n] = vector[n] + 1;
}
}
}
for(var k = 0; k < this.denominator.length; k++) {
if((r = UNITS[this.denominator[k]])) {
n = SIGNATURE_VECTOR.indexOf(r[2]);
if(n >= 0) {
vector[n] = vector[n] - 1;
}
}
}
return vector;
};
/* parse a string into a unit object.
* Typical formats like :
* "5.6 kg*m/s^2"
* "5.6 kg*m*s^-2"
* "5.6 kilogram*meter*second^-2"
* "2.2 kPa"
* "37 degC"
* "1" -- creates a unitless constant with value 1
* "GPa" -- creates a unit with scalar 1 with units 'GPa'
* 6'4" -- recognized as 6 feet + 4 inches
* 8 lbs 8 oz -- recognized as 8 lbs + 8 ounces
*/
var parse = function (val) {
if (!isString(val)) {
val = val.toString();
}
val = val.trim();
if (val.length === 0) {
throw new QtyError("Unit not recognized");
}
var result = QTY_STRING_REGEX.exec(val);
if(!result) {
throw new QtyError(val + ": Quantity not recognized");
}
var scalarMatch = result[1];
if(scalarMatch) {
// Allow whitespaces between sign and scalar for loose parsing
scalarMatch = scalarMatch.replace(/\s/g, "");
this.scalar = parseFloat(scalarMatch);
}
else {
this.scalar = 1;
}
var top = result[2];
var bottom = result[3];
var n, x, nx;
// TODO DRY me
while((result = TOP_REGEX.exec(top))) {
n = parseFloat(result[2]);
if(isNaN(n)) {
// Prevents infinite loops
throw new QtyError("Unit exponent is not a number");
}
// Disallow unrecognized unit even if exponent is 0
if(n === 0 && !UNIT_TEST_REGEX.test(result[1])) {
throw new QtyError("Unit not recognized");
}
x = result[1] + " ";
nx = "";
for(var i = 0; i < Math.abs(n) ; i++) {
nx += x;
}
if(n >= 0) {
top = top.replace(result[0], nx);
}
else {
bottom = bottom ? bottom + nx : nx;
top = top.replace(result[0], "");
}
}
while((result = BOTTOM_REGEX.exec(bottom))) {
n = parseFloat(result[2]);
if(isNaN(n)) {
// Prevents infinite loops
throw new QtyError("Unit exponent is not a number");
}
// Disallow unrecognized unit even if exponent is 0
if(n === 0 && !UNIT_TEST_REGEX.test(result[1])) {
throw new QtyError("Unit not recognized");
}
x = result[1] + " ";
nx = "";
for(var j = 0; j < n ; j++) {
nx += x;
}
bottom = bottom.replace(result[0], nx, "g");
}
if(top) {
this.numerator = parseUnits(top.trim());
}
if(bottom) {
this.denominator = parseUnits(bottom.trim());
}
};
/*
* Throws incompatible units error
*
* @throws "Incompatible units" error
*/
function throwIncompatibleUnits() {
throw new QtyError("Incompatible units");
}
Qty.prototype = {
// Properly set up constructor
constructor: Qty,
// Converts the unit back to a float if it is unitless. Otherwise raises an exception
toFloat: function() {
if(this.isUnitless()) {
return this.scalar;
}
throw new QtyError("Can't convert to Float unless unitless. Use Unit#scalar");
},
// returns true if no associated units
// false, even if the units are "unitless" like 'radians, each, etc'
isUnitless: function() {
return compareArray(this.numerator, UNITY_ARRAY) && compareArray(this.denominator, UNITY_ARRAY);
},
/*
check to see if units are compatible, but not the scalar part
this check is done by comparing signatures for performance reasons
if passed a string, it will create a unit object with the string and then do the comparison
this permits a syntax like:
unit =~ "mm"
if you want to do a regexp on the unit string do this ...
unit.units =~ /regexp/
*/
isCompatible: function(other) {
if(isString(other)) {
return this.isCompatible(Qty(other));
}
if(!(isQty(other))) {
return false;
}
if(other.signature !== undefined) {
return this.signature === other.signature;
}
else {
return false;
}
},
/*
check to see if units are inverse of each other, but not the scalar part
this check is done by comparing signatures for performance reasons
if passed a string, it will create a unit object with the string and then do the comparison
this permits a syntax like:
unit =~ "mm"
if you want to do a regexp on the unit string do this ...
unit.units =~ /regexp/
*/
isInverse: function(other) {
return this.inverse().isCompatible(other);
},
kind: function() {
return KINDS[this.signature.toString()];
},
// Returns 'true' if the Unit is represented in base units
isBase: function() {
if(this._isBase !== undefined) {
return this._isBase;
}
if(this.isDegrees() && this.numerator[0].match(/<(kelvin|temp-K)>/)) {
this._isBase = true;
return this._isBase;
}
this.numerator.concat(this.denominator).forEach(function(item) {
if(item !== UNITY && BASE_UNITS.indexOf(item) === -1 ) {
this._isBase = false;
}
}, this);
if(this._isBase === false) {
return this._isBase;
}
this._isBase = true;
return this._isBase;
},
// convert to base SI units
// results of the conversion are cached so subsequent calls to this will be fast
toBase: function() {
if(this.isBase()) {
return this;
}
if(this.isTemperature()) {
return toTempK(this);
}
var cached = baseUnitCache[this.units()];
if(!cached) {
cached = toBaseUnits(this.numerator,this.denominator);
baseUnitCache[this.units()] = cached;
}
return cached.mul(this.scalar);
},
// returns the 'unit' part of the Unit object without the scalar
units: function() {
if(this._units !== undefined) {
return this._units;
}
var numIsUnity = compareArray(this.numerator, UNITY_ARRAY),
denIsUnity = compareArray(this.denominator, UNITY_ARRAY);
if(numIsUnity && denIsUnity) {
this._units = "";
return this._units;
}
var numUnits = stringifyUnits(this.numerator),
denUnits = stringifyUnits(this.denominator);
this._units = numUnits + (denIsUnity ? "":("/" + denUnits));
return this._units;
},
eq: function(other) {
return this.compareTo(other) === 0;
},
lt: function(other) {
return this.compareTo(other) === -1;
},
lte: function(other) {
return this.eq(other) || this.lt(other);
},
gt: function(other) {
return this.compareTo(other) === 1;
},
gte: function(other) {
return this.eq(other) || this.gt(other);
},
/**
* Returns the nearest multiple of quantity passed as
* precision
*
* @param {(Qty|string|number)} prec-quantity - Quantity, string formated
* quantity or number as expected precision
*
* @returns {Qty} Nearest multiple of precQuantity
*
* @example
* Qty('5.5 ft').toPrec('2 ft'); // returns 6 ft
* Qty('0.8 cu').toPrec('0.25 cu'); // returns 0.75 cu
* Qty('6.3782 m').toPrec('cm'); // returns 6.38 m
* Qty('1.146 MPa').toPrec('0.1 bar'); // returns 1.15 MPa
*
*/
toPrec: function(precQuantity) {
if(isString(precQuantity)) {
precQuantity = Qty(precQuantity);
}
if(isNumber(precQuantity)) {
precQuantity = Qty(precQuantity + " " + this.units());
}
if(!this.isUnitless()) {
precQuantity = precQuantity.to(this.units());
}
else if(!precQuantity.isUnitless()) {
throwIncompatibleUnits();
}
if(precQuantity.scalar === 0) {
throw new QtyError("Divide by zero");
}
var precRoundedResult = mulSafe(Math.round(this.scalar/precQuantity.scalar),
precQuantity.scalar);
return Qty(precRoundedResult + this.units());
},
/**
* Stringifies the quantity
* Deprecation notice: only units parameter is supported.
*
* @param {(number|string|Qty)} targetUnitsOrMaxDecimalsOrPrec -
* target units if string,
* max number of decimals if number,
* passed to #toPrec before converting if Qty
*
* @param {number=} maxDecimals - Maximum number of decimals of
* formatted output
*
* @returns {string} reparseable quantity as string
*/
toString: function(targetUnitsOrMaxDecimalsOrPrec, maxDecimals) {
var targetUnits;
if(isNumber(targetUnitsOrMaxDecimalsOrPrec)) {
targetUnits = this.units();
maxDecimals = targetUnitsOrMaxDecimalsOrPrec;
}
else if(isString(targetUnitsOrMaxDecimalsOrPrec)) {
targetUnits = targetUnitsOrMaxDecimalsOrPrec;
}
else if(isQty(targetUnitsOrMaxDecimalsOrPrec)) {
return this.toPrec(targetUnitsOrMaxDecimalsOrPrec).toString(maxDecimals);
}
var out = this.to(targetUnits);
var outScalar = maxDecimals !== undefined ? round(out.scalar, maxDecimals) : out.scalar;
out = (outScalar + " " + out.units()).trim();
return out;
},
/**
* Format the quantity according to optional passed target units
* and formatter
*
* @param {string} [targetUnits=current units] -
* optional units to convert to before formatting
*
* @param {function} [formatter=Qty.formatter] -
* delegates formatting to formatter callback.
* formatter is called back with two parameters (scalar, units)
* and should return formatted result.
* If unspecified, formatting is delegated to default formatter
* set to Qty.formatter
*
* @example
* var roundingAndLocalizingFormatter = function(scalar, units) {
* // localize or limit scalar to n max decimals for instance
* // return formatted result
* };
* var qty = Qty('1.1234 m');
* qty.format(); // same units, default formatter => "1.234 m"
* qty.format("cm"); // converted to "cm", default formatter => "123.45 cm"
* qty.format(roundingAndLocalizingFormatter); // same units, custom formatter => "1,2 m"
* qty.format("cm", roundingAndLocalizingFormatter); // convert to "cm", custom formatter => "123,4 cm"
*
* @returns {string} quantity as string
*/
format: function(targetUnits, formatter) {
if(arguments.length === 1) {
if(typeof targetUnits === "function") {
formatter = targetUnits;
targetUnits = undefined;
}
}
formatter = formatter || Qty.formatter;
var targetQty = this.to(targetUnits);
return formatter.call(this, targetQty.scalar, targetQty.units());
},
// Compare two Qty objects. Throws an exception if they are not of compatible types.
// Comparisons are done based on the value of the quantity in base SI units.
//
// NOTE: We cannot compare inverses as that breaks the general compareTo contract:
// if a.compareTo(b) < 0 then b.compareTo(a) > 0
// if a.compareTo(b) == 0 then b.compareTo(a) == 0
//
// Since "10S" == ".1ohm" (10 > .1) and "10ohm" == ".1S" (10 > .1)
// Qty("10S").inverse().compareTo("10ohm") == -1
// Qty("10ohm").inverse().compareTo("10S") == -1
//
// If including inverses in the sort is needed, I suggest writing: Qty.sort(qtyArray,units)
compareTo: function(other) {
if(isString(other)) {
return this.compareTo(Qty(other));
}
if(!this.isCompatible(other)) {
throwIncompatibleUnits();
}
if(this.baseScalar < other.baseScalar) {
return -1;
}
else if(this.baseScalar === other.baseScalar) {
return 0;
}
else if(this.baseScalar > other.baseScalar) {
return 1;
}
},
// Return true if quantities and units match
// Unit("100 cm").same(Unit("100 cm")) # => true
// Unit("100 cm").same(Unit("1 m")) # => false
same: function(other) {
return (this.scalar === other.scalar) && (this.units() === other.units());
},
// Returns a Qty that is the inverse of this Qty,
inverse: function() {
if(this.isTemperature()) {
throw new QtyError("Cannot divide with temperatures");
}
if(this.scalar === 0) {
throw new QtyError("Divide by zero");
}
return Qty({"scalar": 1/this.scalar, "numerator": this.denominator, "denominator": this.numerator});
},
isDegrees: function() {
// signature may not have been calculated yet
return (this.signature === null || this.signature === 400) &&
this.numerator.length === 1 &&
compareArray(this.denominator, UNITY_ARRAY) &&
(this.numerator[0].match(/<temp-[CFRK]>/) || this.numerator[0].match(/<(kelvin|celsius|rankine|fahrenheit)>/));
},
isTemperature: function() {
return this.isDegrees() && this.numerator[0].match(/<temp-[CFRK]>/);
},
/**
* Converts to other compatible units.
* Instance's converted quantities are cached for faster subsequent calls.
*
* @param {(string|Qty)} other - Target units as string or retrieved from
* other Qty instance (scalar is ignored)
*
* @returns {Qty} New converted Qty instance with target units
*
* @throws {QtyError} if target units are incompatible
*
* @example
* var weight = Qty("25 kg");
* weight.to("lb"); // => Qty("55.11556554621939 lbs");
* weight.to(Qty("3 g")); // => Qty("25000 g"); // scalar of passed Qty is ignored
*/
to: function(other) {
var cached, target;
if(!other) {
return this;
}
if(!isString(other)) {
return this.to(other.units());
}
cached = this._conversionCache[other];
if(cached) {
return cached;
}