Repository: gentooboontoo/js-quantities Branch: master Commit: 7116174b9995 Files: 42 Total size: 571.5 KB Directory structure: gitextract_9tyqrl1_/ ├── .eslintrc ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── RELEASE ├── SpecRunner.html ├── bench/ │ ├── index.html │ └── main.js ├── bin/ │ ├── bench.rb │ ├── prepare-release.sh │ └── release.sh ├── build/ │ ├── quantities.js │ └── quantities.mjs ├── lib/ │ ├── JSLitmus.js │ ├── jasmine-3.4.0/ │ │ ├── boot.js │ │ ├── jasmine-html.js │ │ ├── jasmine.css │ │ └── jasmine.js │ └── require.js ├── package.json ├── spec/ │ ├── blns.json │ ├── quantitiesSpec.js │ └── support/ │ └── jasmine.json └── src/ ├── quantities/ │ ├── comparators.js │ ├── constructor.js │ ├── conversion.js │ ├── definitions.js │ ├── error.js │ ├── format.js │ ├── global-api.js │ ├── kind.js │ ├── nested-map.js │ ├── operators.js │ ├── parse.js │ ├── predicates.js │ ├── signature.js │ ├── temperature.js │ └── utils.js └── quantities.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintrc ================================================ { "env": { "browser": true, "es6": true }, "globals": { "define": true, "module": true }, parserOptions: { "sourceType": "module" }, "rules": { "brace-style": [ "error", "stroustrup", { "allowSingleLine": true } ], "camelcase": [ "error", { "properties": "never" } ], "curly": [ "error", "all" ], "eqeqeq": "error", "eol-last": "error", "guard-for-in": "error", "indent": [ "error", 2, { "SwitchCase": 1 } ], "keyword-spacing": [ "error", {} ], "new-cap": 0, "no-implicit-coercion": [ "error", { "boolean": false, "string": true, "number": false } ], "no-bitwise": "error", "no-mixed-spaces-and-tabs": "error", "no-multiple-empty-lines": "error", "no-trailing-spaces": "error", "no-undef": "error", "no-unused-vars": "error", "no-with": "error", "quotes": [ "error", "double" ], "semi": [ "error", "always" ], "space-before-function-paren": [ "error", "never" ], "space-infix-ops": "error", "space-unary-ops": [ "error", { "nonwords": false, "words": true } ], "strict": [ "error", "function" ], "valid-jsdoc": "error", "wrap-iife": "error" } } ================================================ FILE: .gitignore ================================================ .envrc shell.nix src/.committed-quantities.js *.swp node_modules/ tags ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - "node" - "lts/*" script: make test ================================================ FILE: CHANGELOG.md ================================================ Unreleased ---------- 1.8.0 / 2023-08-21 ------------------ ### Added * Add "Joules" alias * Add some parts-per notation units * Add metric ton symbol t * Add electronvolt * Add arcminute and arcsecond ### Fixed * Fix wrong quantity name for molar_concentration units 1.7.6 / 2020-12-06 ------------------ ### Added * Unit of acceleration `Gal` ### Fixed * Missing aliases for barrel-related units (#101) 1.7.5 / 2020-04-05 ------------------ * Update development dependencies * Use ESLint as linter 1.7.4 / 2019-06-26 ------------------ * Add Imperial Gallons, and Barrels (US Beer, Imperial Beer, Oil) * Add support for imperial version of fluid ounces and pints 1.7.3 / 2018-12-15 ------------------ * Fix some inconsistent resulting units when multiplying or dividing quantities (#94) 1.7.2 / 2018-03-31 ------------------ * Remove `module` from package definition (Fix #91) 1.7.1 / 2018-03-25 ------------------ * Add missing unit aliases 1.7.0 / 2017-08-23 ------------------ * Fix JS allocation failure for unrealistically large exponents * Add volt-ampere, volt-ampere-reactive and data mile definitions * Add redshift alias 1.6.6 / 2017-02-08 ------------------ * Report incompatible units in error message 1.6.5 / 2017-01-20 ------------------ * Fix main entrypoint in bower.json 1.6.4 / 2017-01-02 ------------------ * Fix infinite regex check 1.6.3 / 2016-09-22 ------------------ * Add missing kinds * Fix conversion from percentage to unitless quantity * Fix capacitance definition * Exclude `farad` from base units * Rename `mass concentration` to `density` 1.6.2 / 2016-04-13 ------------------ * Accept blank string as initialization value 1.6.1 / 2016-03-27 ------------------ * Fix definition of square foot * Add tablespoon `tbsp` alias * Add `Qty.version` property 1.6.0 / 2015-12-26 ------------------ * Add `Qty.getUnits` to return available units of a well-known kind * Add `Qty.getAliases` to return every alias of a specific unit * Allow to initialize a quantity with scalar and units as separate arguments * Rename `memory` kind to `information` * Add `information_rate` kind * Accept Wh and Ah as units * Fix hang when using water height pressure units * Add plural for fluid ounce * Fix `amu` and `dalton` definitions * Add `tb` as tablespoon alias * Add plural for `information` units * Minor fixes or improvements 1.5.0 / 2014-12-08 ------------------ * Add `Qty.getKinds` returning known kinds of units * Add µ symbol as micro prefix alias * Add Ω symbol as ohm unit alias * Minor internal improvements and fixes 1.4.2 / 2014-09-09 ------------------ * Fix plural for radian and add missing ones for time units * Add "gon" international standard symbol as gradian alias * Fix units of force * Allow whitespaces between sign and scalar and do not accept sign without scalar 1.4.1 / 2014-05-14 ------------------ * Use a little more robust to test string type and factorize it 1.4.0 / 2014-04-10 ------------------ * Directly convert array of values when using swiftConverter * Add support for bushel units 1.3.0 / 2014-03-05 ------------------ * Add Qty#format and accept custom formatters * Allow to call Qty() without new to create Qty instances (Qty could be used both as a constructor or as a factory) * Qty#toString only supports to be passed output units as single parameter. Former parameters are now deprecated but still supported to not introduce a breaking change * Add mc as alternate definition for prefix "micro" * Throw error with mmm as unit * Add rounding optimization 1.2.0 / 2013-12-17 ------------------ * Throw QtyError instead of plain string * Cache conversion results from Qty#to instead of Qty#toString * Fix point and pica unit definitions * Fix error when initializing a quantity with an empty string 1.1.2 / 2013-11-04 ------------------ * Fix rounding issue when converting 1 cm3 to mm3 * Do some code cleaning (it should not break public API) 1.1.1 / 2013-10-01 ------------------ * Fix Qty#toPrec() returning wrong result with some precision 1.1.0 / 2013-09-20 ------------------ * Add array converting method * Major speedup by means of some optimizations and refactoring 1.0.0 / 2013-07-30 ------------------ * First stable version ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright © 2006-2007 Kevin C. Olbrich Copyright © 2010-2016 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. ================================================ FILE: Makefile ================================================ SPEC_DIR := spec SPECFILES := $(shell find $(SPEC_DIR) -iname '*.js') SOURCE_DIR := src SOURCES := $(shell find $(SOURCE_DIR) -iname '*.js') LINTEDFILES := $(SOURCES) $(SPECFILES) BUILD_DIR := build ESM_FILE := $(BUILD_DIR)/quantities.mjs UMD_FILE := $(BUILD_DIR)/quantities.js DIST_FILES := $(ESM_FILE) $(UMD_FILE) BANNER := $(shell cat LICENSE) ROLLUP := npx rollup JASMINE := npx jasmine ESLINT := npx eslint build: $(DIST_FILES) $(UMD_FILE): $(SOURCES) $(ROLLUP) --file=$(UMD_FILE) \ --format=umd \ --name=Qty \ --banner="`echo '/*'; cat LICENSE; echo '*/'`" \ src/quantities.js $(ESM_FILE): $(SOURCES) $(ROLLUP) --file=$(ESM_FILE) \ --format=es \ --banner="`echo '/*'; cat LICENSE; echo '*/'`" \ src/quantities.js test: lint build $(JASMINE) lint: $(LINTEDFILES) $(ESLINT) $(LINTEDFILES) bench: bin/bench.rb clean: rm -f $(DIST_FILES) .PHONY: bench build clean lint test ================================================ FILE: README.md ================================================ # JS-quantities [![Build Status](https://travis-ci.org/gentooboontoo/js-quantities.png)](https://travis-ci.org/gentooboontoo/js-quantities) JS-quantities is originally a JavaScript port of Kevin Olbrich's library Ruby Units (http://github.com/olbrich/ruby-units). The library aims to simplify the handling of units for scientific calculations involving quantities. JS-quantities is built as UMD and ES modules and can be used with Node.js and browsers. It has **no dependencies**. ## Installation Install with `npm install js-quantities` or download latest release v1.8.0 as: * [UMD module](https://raw.github.com/gentooboontoo/js-quantities/v1.8.0/build/quantities.js) * [ES module](https://raw.github.com/gentooboontoo/js-quantities/v1.8.0/build/quantities.mjs) ## Usage ### Node.js ```javascript // As CommonJS module const Qty = require('js-quantities'); // As ES module import Qty from 'js-quantities'; ``` ### Browsers * UMD module could be included as is: ```html ``` In this case, it will define a global variable `Qty`. * With an AMD loader like [Require.JS](http://requirejs.org/): ```javascript define(['quantities'], function(Qty) { ... }); ``` * As ES module: ```html ``` ## Synopsis ### Creation Instances of quantities are made by means of `Qty()` method. `Qty` can both be used as a constructor (with new) or as a factory (without new): ```javascript qty = new Qty('23 ft'); // constructor qty = Qty('23 ft'); // factory ``` `Qty` constructor accepts strings, numbers and `Qty` instances as initializing values. If scalars and their respective units are available programmatically, the two argument signature may be useful: ```javascript qty = new Qty(124, 'cm'); // => 1.24 meter qty = Qty(124, 'cm'); // => 1.24 meter ``` For the sake of simplicity, one will use the factory way below but using `new Qty()` is equivalent. ```javascript qty = Qty('1m'); // => 1 meter qty = Qty('m'); // => 1 meter (scalar defaults to 1) qty = Qty('1 N*m'); qty = Qty('1 N m'); // * is optional qty = Qty('1 m/s'); qty = Qty('1 m^2/s^2'); qty = Qty('1 m^2 s^-2'); // negative powers qty = Qty('1 m2 s-2'); // ^ is optional qty = Qty('1 m^2 kg^2 J^2/s^2 A'); qty = Qty('1.5'); // unitless quantity qty = Qty(1.5); // number as initializing value qty = Qty('1 attoparsec/microfortnight'); qtyCopy = Qty(qty); // quantity could be copied when used as // initializing value ``` `Qty.parse` utility method is also provided to parse and create quantities from strings. Unlike the constructor, it will return `null` instead of throwing an error when parsing an invalid quantity. ```javascript Qty.parse('1 m'); // => 1 meter Qty.parse('foo') // => null ``` ### Available well-known kinds ```javascript Qty.getKinds(); // => Array of names of every well-known kind of units ``` ### Available units of a particular kind ```javascript Qty.getUnits('currency'); // => [ 'dollar', 'cents' ] // Or all alphabetically sorted Qty.getUnits(); // => [ 'acre','Ah','ampere','AMU','angstrom'] ``` ### Alternative names of a unit ```javascript Qty.getAliases('m'); // => [ 'm', 'meter', 'meters', 'metre', 'metres' ] ``` ### Quantity compatibility, kind and various queries ```javascript qty1.isCompatible(qty2); // => true or false qty.kind(); // => 'length', 'area', etc... qty.isUnitless(); // => true or false qty.isBase(); // => true if quantity is represented with base units ``` ### Conversion ```javascript qty.toBase(); // converts to SI units (10 cm => 0.1 m) (new instance) qty.toFloat(); // returns scalar of unitless quantity // (otherwise throws error) qty.to('m'); // converts quantity to meter if compatible // or throws an error (new instance) qty1.to(qty2); // converts quantity to same unit of qty2 if compatible // or throws an error (new instance) qty.inverse(); // converts quantity to its inverse // ('100 m/s' => '.01 s/m') // Inverses can be used, but there is no special checking to // rename the units Qty('10ohm').inverse() // '.1/ohm' // (not '.1S', although they are equivalent) // however, the 'to' command will convert between inverses also Qty('10ohm').to('S') // '.1S' ``` `Qty.swiftConverter()` is a fast way to efficiently convert large array of Number values. It configures a function accepting a value or an array of Number values to convert. ```javascript var convert = Qty.swiftConverter('m/h', 'ft/s'); // Configures converter // Converting single value var converted = convert(2500); // => 2.278.. // Converting large array of values var convertedSerie = convert([2500, 5000, ...]); // => [2.278.., 4.556.., ...] ``` The main drawback of this conversion method is that it does not take care of rounding issues. ### Comparison ```javascript qty1.eq(qty2); // => true if both quantities are equal (1m == 100cm => true) qty1.same(qty2); // => true if both quantities are same (1m == 100cm => false) qty1.lt(qty2); // => true if qty1 is stricty less than qty2 qty1.lte(qty2); // => true if qty1 is less than or equal to qty2 qty1.gt(qty2); // => true if qty1 is stricty greater than qty2 qty1.gte(qty2); // => true if qty1 is greater than or equal to qty2 qty1.compareTo(qty2); // => -1 if qty1 < qty2, // => 0 if qty1 == qty2, // => 1 if qty1 > qty2 ``` ### Operators * add(other): Add. other can be string or quantity. other should be unit compatible. * sub(other): Substract. other can be string or quantity. other should be unit compatible. * mul(other): Multiply. other can be string, number or quantity. * div(other): Divide. other can be string, number or quantity. ### Rounding `Qty#toPrec(precision)` : returns the nearest multiple of quantity passed as precision. ```javascript var qty = Qty('5.17 ft'); qty.toPrec('ft'); // => 5 ft qty.toPrec('0.5 ft'); // => 5 ft qty.toPrec('0.25 ft'); // => 5.25 ft qty.toPrec('0.1 ft'); // => 5.2 ft qty.toPrec('0.05 ft'); // => 5.15 ft qty.toPrec('0.01 ft'); // => 5.17 ft qty.toPrec('0.00001 ft'); // => 5.17 ft qty.toPrec('2 ft'); // => 6 ft qty.toPrec('2'); // => 6 ft var qty = Qty('6.3782 m'); qty.toPrec('dm'); // => 6.4 m qty.toPrec('cm'); // => 6.38 m qty.toPrec('mm'); // => 6.378 m qty.toPrec('5 cm'); // => 6.4 m qty.toPrec('10 m'); // => 10 m qty.toPrec(0.1); // => 6.3 m var qty = Qty('1.146 MPa'); qty.toPrec('0.1 bar'); // => 1.15 MPa ``` ### Formatting quantities `Qty#toString` returns a string using the canonical form of the quantity (that is it could be seamlessly reparsed by `Qty`). ```javascript var qty = Qty('1.146 MPa'); qty.toString(); // => '1.146 MPa' ``` As a shorthand, units could be passed to `Qty#toString` and is equivalent to successively call `Qty#to` then `Qty#toString`. ```javascript var qty = Qty('1.146 MPa'); qty.toString('bar'); // => '11.46 bar' qty.to('bar').toString(); // => '11.46 bar' ``` `Qty#toString` could also be used with any method from `Qty` to make some sort of formatting. For instance, one could use `Qty#toPrec` to fix the maximum number of decimals: ```javascript var qty = Qty('1.146 MPa'); qty.toPrec(0.1).toString(); // => '1.1 MPa' qty.to('bar').toPrec(0.1).toString(); // => '11.5 bar' ``` For advanced formatting needs as localization, specific rounding or any other custom customization, quantities can be transformed into strings through `Qty#format` according to optional target units and formatter. If target units are specified, the quantity is converted into them before formatting. Such a string is not intended to be reparsed to construct a new instance of `Qty` (unlike output of `Qty#toString`). If no formatter is specified, quantities are formatted according to default js-quantities' formatter and is equivalent to `Qty#toString`. ```javascript 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` could delegates formatting to a custom formatter if required. A formatter is a callback function accepting scalar and units as parameters and returning a formatted string representing the quantity. ```javascript var configurableRoundingFormatter = function(maxDecimals) { return function(scalar, units) { var pow = Math.pow(10, maxDecimals); var rounded = Math.round(scalar * pow) / pow; return rounded + ' ' + units; }; }; var qty = Qty('1.1234 m'); // same units, custom formatter => '1.12 m' qty.format(configurableRoundingFormatter(2)); // convert to 'cm', custom formatter => '123.4 cm' qty.format('cm', configurableRoundingFormatter(1)); ``` Custom formatter can be configured globally by setting `Qty.formatter`. ```javascript Qty.formatter = configurableRoundingFormatter(2); var qty = Qty('1.1234 m'); qty.format(); // same units, current default formatter => '1.12 m' ``` ### Temperatures Like ruby-units, JS-quantities makes a distinction between a temperature (which technically is a property) and degrees of temperature (which temperatures are measured in). Temperature units (i.e., 'tempK') can be converted back and forth, and will take into account the differences in the zero points of the various scales. Differential temperature (e.g., '100 degC') units behave like most other units. ```javascript Qty('37 tempC').to('tempF') // => 98.6 tempF ``` JS-quantities will throw an error if you attempt to create a temperature unit that would fall below absolute zero. Unit math on temperatures is fairly limited. ```javascript Qty('100 tempC').add('10 degC') // 110 tempC Qty('100 tempC').sub('10 degC') // 90 tempC Qty('100 tempC').add('50 tempC') // throws error Qty('100 tempC').sub('50 tempC') // 50 degC Qty('50 tempC').sub('100 tempC') // -50 degC Qty('100 tempC').mul(scalar) // 100*scalar tempC Qty('100 tempC').div(scalar) // 100/scalar tempC Qty('100 tempC').mul(qty) // throws error Qty('100 tempC').div(qty) // throws error Qty('100 tempC*unit') // throws error Qty('100 tempC/unit') // throws error Qty('100 unit/tempC') // throws error Qty('100 tempC').inverse() // throws error ``` ```javascript Qty('100 tempC').to('degC') // => 100 degC ``` This conversion references the 0 point on the scale of the temperature unit ```javascript Qty('100 degC').to('tempC') // => -173.15 tempC ``` These conversions are always interpreted as being relative to absolute zero. Conversions are probably better done like this... ```javascript Qty('0 tempC').add('100 degC') // => 100 tempC ``` ### Errors Every error thrown by JS-quantities is an instance of `Qty.Error`. ```javascript try { // code triggering an error inside JS-quantities } catch(e) { if(e instanceof Qty.Error) { // ... } else { // ... } } ``` ## Tests Tests are implemented with Jasmine (https://github.com/pivotal/jasmine). You could use both HTML and jasmine-node runners. To execute specs through HTML runner, just open `SpecRunner.html` file in a browser to execute them. To execute specs through `jasmine-node`, launch: make test ### Performance regression test There is a small benchmarking HTML page to spot performance regression between currently checked-out quantities.js and any committed version. Just execute: make bench then open http://0.0.0.0:3000/bench Checked-out version is benchmarked against HEAD by default but it could be changed by passing any commit SHA on the command line. Port (default 3000) is also configurable. make bench COMMIT=e0c7fc468 PORT=5000 ## TypeScript type declarations A TypeScript declaration file is published on [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/js-quantities). It could be installed with `npm install @types/js-quantities`. ## Contribute Feedback and contributions are welcomed. Pull requests must pass tests and linting. Please make sure that `make test` and `make lint` return no errors before submitting. ================================================ FILE: RELEASE ================================================ 1.8.0 ================================================ FILE: SpecRunner.html ================================================ Jasmine Spec Runner ================================================ FILE: bench/index.html ================================================ JS-quantities Benchmarks ================================================ FILE: bench/main.js ================================================ /* global requirejs, JSLitmus */ requirejs.config({ baseUrl: "../lib", paths: { "src": "../src" } }); require([ "src/.committed-quantities", "src/quantities" ], function(previousQty, currentQty) { "use strict"; function bench(name, func) { JSLitmus.test(name, func); } function benchCurrent(name, func) { bench(name + " (current)", func(currentQty)); } function benchPrevious(name, func) { bench(name + " (GIT)", func(previousQty)); } function compare(name, func) { benchPrevious(name, func); benchCurrent(name, func); } compare("Unit conversion", function(Qty) { return function() { new Qty("2500 m/h").to("ft/s"); }; }); compare("Array conversion", function(Qty) { var convert = Qty.swiftConverter("m/h", "ft/s"); var values = []; for(var i = 0; i < 1000; i++) { values.push(i); } return function() { return convert(values); }; }); }); ================================================ FILE: bin/bench.rb ================================================ #!/usr/bin/env ruby Dir.chdir(File.join(File.dirname(__FILE__), '..')) port = ENV['PORT'] || '3000' commit = ENV['COMMIT'] || 'HEAD' pid = fork do exec "adsf -p #{port}" end `git show #{commit}:src/quantities.js > src/.committed-quantities.js` puts "Bench server launched: please open http://0.0.0.0:#{port}/bench" begin Process.wait(pid) rescue Interrupt => e puts "Killing web server..." Process.kill(9, pid) end File.unlink 'src/.committed-quantities.js' ================================================ FILE: bin/prepare-release.sh ================================================ #!/bin/bash if [[ $# != 1 ]]; then echo "Usage: $0 VERSION" exit 1 fi VERSION="$1" LOG_ENTRY="${VERSION} / $(date +%Y-%m-%d)\n\ ------------------\n\ \n\ * ...\n" sed -i "1i $LOG_ENTRY" CHANGELOG.md sed -i "s/\(\"version\"\):.*$/\1: \"${VERSION}\",/" package.json sed -i "s/\(v[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\)/v${VERSION}/g" README.md sed -i "s/Qty.version =.*$/Qty.version = \"${VERSION}\";/" src/quantities.js echo "${VERSION}" > RELEASE make ================================================ FILE: bin/release.sh ================================================ #!/bin/bash set -e VERSION=$(cat RELEASE) TAG=v${VERSION} git add CHANGELOG.md README.md package.json \ RELEASE src/quantities.js build/quantities.js build/quantities.mjs git commit -m "Release ${TAG}" git tag "${TAG}" git push github master "${TAG}" git checkout gh-pages git show master:README.md > index.md git add index.md git commit -m "Update index.md" git push github gh-pages git checkout master npm publish ================================================ FILE: build/quantities.js ================================================ /* The MIT License (MIT) Copyright © 2006-2007 Kevin C. Olbrich Copyright © 2010-2016 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. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Qty = factory()); })(this, (function () { 'use strict'; /** * Tests if a value is a string * * @param {*} value - Value to test * * @returns {boolean} true if value is a string, false otherwise */ function isString(value) { return typeof value === "string" || value instanceof String; } /* * Prefer stricter Number.isFinite if currently supported. * To be dropped when ES6 is finalized. Obsolete browsers will * have to use ES6 polyfills. */ var isFiniteImpl = Number.isFinite || window.isFinite; /** * Tests if a value is a number * * @param {*} value - Value to test * * @returns {boolean} true if value is a number, false otherwise */ function isNumber(value) { // Number.isFinite allows not to consider NaN or '1' as numbers return isFiniteImpl(value); } /* * Identity function */ function identity(value) { return value; } /** * Returns unique strings from list * * @param {string[]} strings - array of strings * * * @returns {string[]} a new array of strings without duplicates */ function uniq(strings) { var seen = {}; return strings.filter(function(item) { return seen.hasOwnProperty(item) ? false : (seen[item] = true); }); } function compareArray(array1, array2) { if (array2.length !== array1.length) { return false; } for (var i = 0; i < array1.length; i++) { if (array2[i].compareArray) { if (!array2[i].compareArray(array1[i])) { return false; } } if (array2[i] !== array1[i]) { return false; } } return true; } function assign(target, properties) { Object.keys(properties).forEach(function(key) { target[key] = properties[key]; }); } /** * Safely multiplies numbers while avoiding floating errors * like 0.1 * 0.1 => 0.010000000000000002 * * @param {...number} numbers - numbers to multiply * * @returns {number} result */ function mulSafe() { var result = 1, decimals = 0; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; decimals = decimals + getFractional(arg); result *= arg; } return decimals !== 0 ? round(result, decimals) : result; } /** * Safely divides two numbers while avoiding floating errors * like 0.3 / 0.05 => 5.999999999999999 * * @returns {number} result * @param {number} num Numerator * @param {number} den Denominator */ function divSafe(num, den) { if (den === 0) { throw new Error("Divide by zero"); } var factor = Math.pow(10, getFractional(den)); var invDen = factor / (factor * den); return mulSafe(num, invDen); } /** * Rounds value at the specified number of decimals * * @param {number} val - value to round * @param {number} decimals - number of decimals * * @returns {number} rounded number */ function round(val, decimals) { return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals); } function getFractional(num) { // Check for NaNs or Infinities if (!isFinite(num)) { return 0; } // Faster than parsing strings // http://jsperf.com/count-decimals/2 var count = 0; while (num % 1 !== 0) { num *= 10; count++; } return count; } /** * Custom error type definition * @constructor */ function QtyError() { var err; if (!this) { // Allows to instantiate QtyError without new() err = Object.create(QtyError.prototype); QtyError.apply(err, arguments); return err; } err = Error.apply(this, arguments); this.name = "QtyError"; this.message = err.message; this.stack = err.stack; } QtyError.prototype = Object.create(Error.prototype, {constructor: { value: QtyError }}); /* * Throws incompatible units error * @param {string} left - units * @param {string} right - units incompatible with first argument * @throws "Incompatible units" error */ function throwIncompatibleUnits(left, right) { throw new QtyError("Incompatible units: " + left + " and " + right); } var UNITS = { /* prefixes */ "" : [["googol"], 1e100, "prefix"], "" : [["Ki","Kibi","kibi"], Math.pow(2,10), "prefix"], "" : [["Mi","Mebi","mebi"], Math.pow(2,20), "prefix"], "" : [["Gi","Gibi","gibi"], Math.pow(2,30), "prefix"], "" : [["Ti","Tebi","tebi"], Math.pow(2,40), "prefix"], "" : [["Pi","Pebi","pebi"], Math.pow(2,50), "prefix"], "" : [["Ei","Exi","exi"], Math.pow(2,60), "prefix"], "" : [["Zi","Zebi","zebi"], Math.pow(2,70), "prefix"], "" : [["Yi","Yebi","yebi"], Math.pow(2,80), "prefix"], "" : [["Y","Yotta","yotta"], 1e24, "prefix"], "" : [["Z","Zetta","zetta"], 1e21, "prefix"], "" : [["E","Exa","exa"], 1e18, "prefix"], "" : [["P","Peta","peta"], 1e15, "prefix"], "" : [["T","Tera","tera"], 1e12, "prefix"], "" : [["G","Giga","giga"], 1e9, "prefix"], "" : [["M","Mega","mega"], 1e6, "prefix"], "" : [["k","kilo"], 1e3, "prefix"], "" : [["h","Hecto","hecto"], 1e2, "prefix"], "" : [["da","Deca","deca","deka"], 1e1, "prefix"], "" : [["d","Deci","deci"], 1e-1, "prefix"], "" : [["c","Centi","centi"], 1e-2, "prefix"], "" : [["m","Milli","milli"], 1e-3, "prefix"], "" : [ ["u","\u03BC"/*µ as greek letter*/,"\u00B5"/*µ as micro sign*/,"Micro","mc","micro"], 1e-6, "prefix" ], "" : [["n","Nano","nano"], 1e-9, "prefix"], "" : [["p","Pico","pico"], 1e-12, "prefix"], "" : [["f","Femto","femto"], 1e-15, "prefix"], "" : [["a","Atto","atto"], 1e-18, "prefix"], "" : [["z","Zepto","zepto"], 1e-21, "prefix"], "" : [["y","Yocto","yocto"], 1e-24, "prefix"], "<1>" : [["1", "<1>"], 1, ""], /* length units */ "" : [["m","meter","meters","metre","metres"], 1.0, "length", [""] ], "" : [["in","inch","inches","\""], 0.0254, "length", [""]], "" : [["ft","foot","feet","'"], 0.3048, "length", [""]], "" : [["yd","yard","yards"], 0.9144, "length", [""]], "" : [["mi","mile","miles"], 1609.344, "length", [""]], "" : [["nmi","naut-mile"], 1852, "length", [""]], "": [["league","leagues"], 4828, "length", [""]], "": [["furlong","furlongs"], 201.2, "length", [""]], "" : [["rd","rod","rods"], 5.029, "length", [""]], "" : [["mil","mils"], 0.0000254, "length", [""]], "" :[["ang","angstrom","angstroms"], 1e-10, "length", [""]], "" : [["fathom","fathoms"], 1.829, "length", [""]], "" : [["pica","picas"], 0.00423333333, "length", [""]], "" : [["pt","point","points"], 0.000352777778, "length", [""]], "" : [["z","red-shift", "redshift"], 1.302773e26, "length", [""]], "" : [["AU","astronomical-unit"], 149597900000, "length", [""]], "":[["ls","light-second"], 299792500, "length", [""]], "":[["lmin","light-minute"], 17987550000, "length", [""]], "" : [["ly","light-year"], 9460528000000000, "length", [""]], "" : [["pc","parsec","parsecs"], 30856780000000000, "length", [""]], "" : [["DM","datamile"], 1828.8, "length", [""]], /* mass */ "" : [["kg","kilogram","kilograms"], 1.0, "mass", [""]], "" : [["u","AMU","amu"], 1.660538921e-27, "mass", [""]], "" : [["Da","Dalton","Daltons","dalton","daltons"], 1.660538921e-27, "mass", [""]], "" : [["slug","slugs"], 14.5939029, "mass", [""]], "" : [["tn","ton","short-ton"], 907.18474, "mass", [""]], "":[["t","tonne","metric-ton"], 1000, "mass", [""]], "" : [["ct","carat","carats"], 0.0002, "mass", [""]], "" : [["lbs","lb","pound","pounds","#"], 0.45359237, "mass", [""]], "" : [["oz","ounce","ounces"], 0.0283495231, "mass", [""]], "" : [["g","gram","grams","gramme","grammes"], 1e-3, "mass", [""]], "" : [["grain","grains","gr"], 6.479891e-5, "mass", [""]], "" : [["dram","drams","dr"], 0.0017718452, "mass",[""]], "" : [["stone","stones","st"],6.35029318, "mass",[""]], /* area */ "":[["hectare"], 10000, "area", ["",""]], "":[["acre","acres"], 4046.85642, "area", ["",""]], "":[["sqft"], 0.09290304, "area", ["",""]], /* volume */ "" : [["l","L","liter","liters","litre","litres"], 0.001, "volume", ["","",""]], "": [["gal","gallon","gallons"], 0.0037854118, "volume", ["","",""]], "": [["galimp","gallon-imp","gallons-imp"], 0.0045460900, "volume", ["","",""]], "": [["qt","quart","quarts"], 0.00094635295, "volume", ["","",""]], "": [["pt","pint","pints"], 0.000473176475, "volume", ["","",""]], "": [["ptimp","pint-imp","pints-imp"], 5.6826125e-4, "volume", ["","",""]], "": [["cu","cup","cups"], 0.000236588238, "volume", ["","",""]], "": [["floz","fluid-ounce","fluid-ounces"], 2.95735297e-5, "volume", ["","",""]], "": [["flozimp", "floz-imp","fluid-ounce-imp","fluid-ounces-imp"], 2.84130625e-5, "volume", ["","",""]], "": [["tb","tbsp","tbs","tablespoon","tablespoons"], 1.47867648e-5, "volume", ["","",""]], "": [["tsp","teaspoon","teaspoons"], 4.92892161e-6, "volume", ["","",""]], "": [["bu","bsh","bushel","bushels"], 0.035239072, "volume", ["","",""]], "": [["bbl","oilbarrel", "oilbarrels", "oil-barrel","oil-barrels"], 0.158987294928, "volume", ["","",""]], "": [["bl","bl-us","beerbarrel", "beerbarrels", "beer-barrel","beer-barrels"], 0.1173477658, "volume", ["","",""]], "": [["blimp","bl-imp","beerbarrel-imp", "beerbarrels-imp", "beer-barrel-imp","beer-barrels-imp"], 0.16365924, "volume", ["","",""]], /* speed */ "" : [["kph"], 0.277777778, "speed", [""], [""]], "" : [["mph"], 0.44704, "speed", [""], [""]], "" : [["kt","kn","kts","knot","knots"], 0.514444444, "speed", [""], [""]], "" : [["fps"], 0.3048, "speed", [""], [""]], /* acceleration */ "" : [["gee"], 9.80665, "acceleration", [""], ["",""]], "" : [["Gal"], 1e-2, "acceleration", [""], ["",""]], /* temperature_difference */ "" : [["degK","kelvin"], 1.0, "temperature", [""]], "" : [["degC","celsius","celsius","centigrade"], 1.0, "temperature", [""]], "" : [["degF","fahrenheit"], 5 / 9, "temperature", [""]], "" : [["degR","rankine"], 5 / 9, "temperature", [""]], "" : [["tempK","temp-K"], 1.0, "temperature", [""]], "" : [["tempC","temp-C"], 1.0, "temperature", [""]], "" : [["tempF","temp-F"], 5 / 9, "temperature", [""]], "" : [["tempR","temp-R"], 5 / 9, "temperature", [""]], /* time */ "": [["s","sec","secs","second","seconds"], 1.0, "time", [""]], "": [["min","mins","minute","minutes"], 60.0, "time", [""]], "": [["h","hr","hrs","hour","hours"], 3600.0, "time", [""]], "": [["d","day","days"], 3600 * 24, "time", [""]], "": [["wk","week","weeks"], 7 * 3600 * 24, "time", [""]], "": [["fortnight","fortnights"], 1209600, "time", [""]], "": [["y","yr","year","years","annum"], 31556926, "time", [""]], "":[["decade","decades"], 315569260, "time", [""]], "":[["century","centuries"], 3155692600, "time", [""]], /* pressure */ "" : [["Pa","pascal","Pascal"], 1.0, "pressure", [""],["","",""]], "" : [["bar","bars"], 100000, "pressure", [""],["","",""]], "" : [["mmHg"], 133.322368, "pressure", [""],["","",""]], "" : [["inHg"], 3386.3881472, "pressure", [""],["","",""]], "" : [["torr"], 133.322368, "pressure", [""],["","",""]], "" : [["atm","ATM","atmosphere","atmospheres"], 101325, "pressure", [""],["","",""]], "" : [["psi"], 6894.76, "pressure", [""],["","",""]], "" : [["cmH2O","cmh2o"], 98.0638, "pressure", [""],["","",""]], "" : [["inH2O","inh2o"], 249.082052, "pressure", [""],["","",""]], /* viscosity */ "" : [["P","poise"], 0.1, "viscosity", [""],["",""] ], "" : [["St","stokes"], 1e-4, "viscosity", ["",""], [""]], /* substance */ "" : [["mol","mole"], 1.0, "substance", [""]], /* molar_concentration */ "" : [["M","molar"], 1000, "molar_concentration", [""], ["","",""]], "" : [["wt%","wtpercent"], 10, "molar_concentration", [""], ["","",""]], /* activity */ "" : [["kat","katal","Katal"], 1.0, "activity", [""], [""]], "" : [["U","enzUnit","unit"], 16.667e-16, "activity", [""], [""]], /* capacitance */ "" : [["F","farad","Farad"], 1.0, "capacitance", ["","","","","",""], ["", "", ""]], /* charge */ "" : [["C","coulomb","Coulomb"], 1.0, "charge", ["",""]], "" : [["Ah"], 3600, "charge", ["",""]], "" : [["e"], 1.602176634e-19, "charge", ["",""]], /* current */ "" : [["A","Ampere","ampere","amp","amps"], 1.0, "current", [""]], /* conductance */ "" : [["S","Siemens","siemens"], 1.0, "conductance", ["","","","",""], ["","",""]], /* inductance */ "" : [["H","Henry","henry"], 1.0, "inductance", ["","",""], ["","","",""]], /* potential */ "" : [["V","Volt","volt","volts"], 1.0, "potential", ["","",""], ["","","",""]], /* resistance */ "" : [ ["Ohm","ohm","\u03A9"/*Ω as greek letter*/,"\u2126"/*Ω as ohm sign*/], 1.0, "resistance", ["","",""],["","","","",""] ], /* magnetism */ "" : [["Wb","weber","webers"], 1.0, "magnetism", ["","",""], ["","",""]], "" : [["T","tesla","teslas"], 1.0, "magnetism", [""], ["","",""]], "" : [["G","gauss"], 1e-4, "magnetism", [""], ["","",""]], "" : [["Mx","maxwell","maxwells"], 1e-8, "magnetism", ["","",""], ["","",""]], "" : [["Oe","oersted","oersteds"], 250.0 / Math.PI, "magnetism", [""], [""]], /* energy */ "" : [["J","joule","Joule","joules","Joules"], 1.0, "energy", ["","",""], ["",""]], "" : [["erg","ergs"], 1e-7, "energy", ["","",""], ["",""]], "" : [["BTU","btu","BTUs"], 1055.056, "energy", ["","",""], ["",""]], "" : [["cal","calorie","calories"], 4.18400, "energy",["","",""], ["",""]], "" : [["Cal","Calorie","Calories"], 4184.00, "energy",["","",""], ["",""]], "" : [["th","therm","therms","Therm","therm-US"], 105480400, "energy",["","",""], ["",""]], "" : [["Wh"], 3600, "energy",["","",""], ["",""]], "" : [["eV", "electronvolt", "electronvolts"], 1.602176634E-19, "energy", ["","",""], ["",""]], /* force */ "" : [["N","Newton","newton"], 1.0, "force", ["",""], ["",""]], "" : [["dyn","dyne"], 1e-5, "force", ["",""], ["",""]], "" : [["lbf","pound-force"], 4.448222, "force", ["",""], ["",""]], "" : [["kgf","kilogram-force", "kilopond", "kp"], 9.80665, "force", ["",""], ["",""]], "" : [["gf","gram-force"], 9.80665E-3, "force", ["",""], ["",""]], /* frequency */ "" : [["Hz","hertz","Hertz"], 1.0, "frequency", ["<1>"], [""]], /* angle */ "" :[["rad","radian","radians"], 1.0, "angle", [""]], "" :[["deg","degree","degrees"], Math.PI / 180.0, "angle", [""]], "" :[["arcmin","arcminute","arcminutes"], Math.PI / 10800.0, "angle", [""]], "" :[["arcsec","arcsecond","arcseconds"], Math.PI / 648000.0, "angle", [""]], "" :[["gon","grad","gradian","grads"], Math.PI / 200.0, "angle", [""]], "" : [["sr","steradian","steradians"], 1.0, "solid_angle", [""]], /* rotation */ "" : [["rotation"], 2.0 * Math.PI, "angle", [""]], "" :[["rpm"], 2.0 * Math.PI / 60.0, "angular_velocity", [""], [""]], /* information */ "" :[["B","byte","bytes"], 1.0, "information", [""]], "" :[["b","bit","bits"], 0.125, "information", [""]], /* information rate */ "" : [["Bps"], 1.0, "information_rate", [""], [""]], "" : [["bps"], 0.125, "information_rate", [""], [""]], /* currency */ "":[["USD","dollar"], 1.0, "currency", [""]], "" :[["cents"], 0.01, "currency", [""]], /* luminosity */ "" : [["cd","candela"], 1.0, "luminosity", [""]], "" : [["lm","lumen"], 1.0, "luminous_power", ["",""]], "" :[["lux"], 1.0, "illuminance", ["",""], ["",""]], /* power */ "" : [["W","watt","watts"], 1.0, "power", ["","",""], ["","",""]], "" : [["VA","volt-ampere"], 1.0, "power", ["","",""], ["","",""]], "" : [["var","Var","VAr","VAR","volt-ampere-reactive"], 1.0, "power", ["","",""], ["","",""]], "" : [["hp","horsepower"], 745.699872, "power", ["","",""], ["","",""]], /* radiation */ "" : [["Gy","gray","grays"], 1.0, "radiation", ["",""], ["",""]], "" : [["R","roentgen"], 0.009330, "radiation", ["",""], ["",""]], "" : [["Sv","sievert","sieverts"], 1.0, "radiation", ["",""], ["",""]], "" : [["Bq","becquerel","becquerels"], 1.0, "radiation", ["<1>"],[""]], "" : [["Ci","curie","curies"], 3.7e10, "radiation", ["<1>"],[""]], /* rate */ "" : [["cpm"], 1.0 / 60.0, "rate", [""],[""]], "" : [["dpm"], 1.0 / 60.0, "rate", [""],[""]], "" : [["bpm"], 1.0 / 60.0, "rate", [""],[""]], /* resolution / typography */ "" : [["dot","dots"], 1, "resolution", [""]], "" : [["pixel","px"], 1, "resolution", [""]], "" : [["ppi"], 1, "resolution", [""], [""]], "" : [["dpi"], 1, "typography", [""], [""]], /* other */ "" : [["cells","cell"], 1, "counting", [""]], "" : [["each"], 1.0, "counting", [""]], "" : [["count"], 1.0, "counting", [""]], "" : [["bp","base-pair"], 1.0, "counting", [""]], "" : [["nt","nucleotide"], 1.0, "counting", [""]], "" : [["molecule","molecules"], 1.0, "counting", ["<1>"]], "" : [["doz","dz","dozen"],12.0,"prefix_only", [""]], "": [["%","percent"], 0.01, "prefix_only", ["<1>"]], "" : [["ppm"],1e-6, "prefix_only", ["<1>"]], "" : [["ppb"],1e-9, "prefix_only", ["<1>"]], "" : [["ppt"],1e-12, "prefix_only", ["<1>"]], "" : [["ppq"],1e-15, "prefix_only", ["<1>"]], "" : [["gr","gross"],144.0, "prefix_only", ["",""]], "" : [["dB","decibel","decibels"], 1.0, "logarithmic", [""]] }; var BASE_UNITS = ["","","","", "","","","","","","","","",""]; var UNITY = "<1>"; var UNITY_ARRAY = [UNITY]; // Setup /** * Asserts unit definition is valid * * @param {string} unitDef - Name of unit to test * @param {Object} definition - Definition of unit to test * * @returns {void} * @throws {QtyError} if unit definition is not valid */ function validateUnitDefinition(unitDef, definition) { var scalar = definition[1]; var numerator = definition[3] || []; var denominator = definition[4] || []; if (!isNumber(scalar)) { throw new QtyError(unitDef + ": Invalid unit definition. " + "'scalar' must be a number"); } numerator.forEach(function(unit) { if (UNITS[unit] === undefined) { throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'numerator' is not recognized"); } }); denominator.forEach(function(unit) { if (UNITS[unit] === undefined) { throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'denominator' is not recognized"); } }); } var PREFIX_VALUES = {}; var PREFIX_MAP = {}; var UNIT_VALUES = {}; var UNIT_MAP = {}; var OUTPUT_MAP = {}; for (var unitDef in UNITS) { if (UNITS.hasOwnProperty(unitDef)) { var definition = UNITS[unitDef]; if (definition[2] === "prefix") { PREFIX_VALUES[unitDef] = definition[1]; for (var i = 0; i < definition[0].length; i++) { PREFIX_MAP[definition[0][i]] = unitDef; } } else { validateUnitDefinition(unitDef, definition); UNIT_VALUES[unitDef] = { scalar: definition[1], numerator: definition[3], denominator: definition[4] }; for (var j = 0; j < definition[0].length; j++) { UNIT_MAP[definition[0][j]] = unitDef; } } OUTPUT_MAP[unitDef] = definition[0][0]; } } /** * Returns a list of available units of kind * * @param {string} [kind] - kind of units * @returns {array} names of units * @throws {QtyError} if kind is unknown */ function getUnits(kind) { var i; var units = []; var unitKeys = Object.keys(UNITS); if (typeof kind === "undefined") { for (i = 0; i < unitKeys.length; i++) { if (["", "prefix"].indexOf(UNITS[unitKeys[i]][2]) === -1) { units.push(unitKeys[i].substr(1, unitKeys[i].length - 2)); } } } else if (this.getKinds().indexOf(kind) === -1) { throw new QtyError("Kind not recognized"); } else { for (i = 0; i < unitKeys.length; i++) { if (UNITS[unitKeys[i]][2] === kind) { units.push(unitKeys[i].substr(1, unitKeys[i].length - 2)); } } } return units.sort(function(a, b) { if (a.toLowerCase() < b.toLowerCase()) { return -1; } if (a.toLowerCase() > b.toLowerCase()) { return 1; } return 0; }); } /** * Returns a list of alternative names for a unit * * @param {string} unitName - name of unit * @returns {string[]} aliases for unit * @throws {QtyError} if unit is unknown */ function getAliases(unitName) { if (!UNIT_MAP[unitName]) { throw new QtyError("Unit not recognized"); } return UNITS[UNIT_MAP[unitName]][0]; } var SIGNATURE_VECTOR = ["length", "time", "temperature", "mass", "current", "substance", "luminosity", "currency", "information", "angle"]; /* 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. */ function unitSignature() { 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 function unitSignatureVector() { 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; } 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}"; // Allow unit powers representing scalar, length, area, volume; 4 is for some // special case representations in SI base units. var SAFE_POWER = "[01234]"; var TOP_REGEX = new RegExp ("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(-?" + SAFE_POWER + "(?![a-zA-Z]))"); var BOTTOM_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(" + SAFE_POWER + "(?![a-zA-Z]))"); /* 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 */ function parse(val) { if (!isString(val)) { val = val.toString(); } val = val.trim(); 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); } if (top) { this.numerator = parseUnits(top.trim()); } if (bottom) { this.denominator = parseUnits(bottom.trim()); } } var PREFIX_REGEX = Object.keys(PREFIX_MAP).sort(function(a, b) { return b.length - a.length; }).join("|"); var UNIT_REGEX = Object.keys(UNIT_MAP).sort(function(a, b) { return b.length - a.length; }).join("|"); /* * Minimal boundary regex to support units with Unicode characters * \b only works for ASCII */ var BOUNDARY_REGEX = "\\b|$"; var UNIT_MATCH = "(" + PREFIX_REGEX + ")??(" + UNIT_REGEX + ")(?:" + BOUNDARY_REGEX + ")"; var UNIT_TEST_REGEX = new RegExp("^\\s*(" + UNIT_MATCH + "[\\s\\*]*)+$"); var UNIT_MATCH_REGEX = new RegExp(UNIT_MATCH, "g"); // g flag for multiple occurences var parsedUnitsCache = {}; /** * Parses and converts units string to normalized unit array. * Result is cached to speed up next calls. * * @param {string} units Units string * @returns {string[]} Array of normalized units * * @example * // Returns ["", "", ""] * parseUnits("s m s"); * */ function parseUnits(units) { var cached = parsedUnitsCache[units]; if (cached) { return cached; } var unitMatch, normalizedUnits = []; // Scan if (!UNIT_TEST_REGEX.test(units)) { throw new QtyError("Unit not recognized"); } while ((unitMatch = UNIT_MATCH_REGEX.exec(units))) { normalizedUnits.push(unitMatch.slice(1)); } normalizedUnits = normalizedUnits.map(function(item) { return PREFIX_MAP[item[0]] ? [PREFIX_MAP[item[0]], UNIT_MAP[item[1]]] : [UNIT_MAP[item[1]]]; }); // Flatten and remove null elements normalizedUnits = normalizedUnits.reduce(function(a,b) { return a.concat(b); }, []); normalizedUnits = normalizedUnits.filter(function(item) { return item; }); parsedUnitsCache[units] = normalizedUnits; return normalizedUnits; } /** * 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 */ function globalParse(value) { if (!isString(value)) { throw new QtyError("Argument should be a string"); } try { return this(value); } catch (e) { return null; } } /** * Tests if a value is a Qty instance * * @param {*} value - Value to test * * @returns {boolean} true if value is a Qty instance, false otherwise */ function isQty(value) { return value instanceof Qty; } function Qty(initValue, initUnits) { assertValidConstructorArgs.apply(null, arguments); if (!(isQty(this))) { return new Qty(initValue, initUnits); } 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 if (initUnits) { parse.call(this, initUnits); this.scalar = initValue; } 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"); } } Qty.prototype = { // Properly set up constructor constructor: Qty, }; /** * Asserts constructor arguments are valid * * @param {*} value - Value to test * @param {string} [units] - Optional units when value is passed as a number * * @returns {void} * @throws {QtyError} if constructor arguments are invalid */ function assertValidConstructorArgs(value, units) { if (units) { if (!(isNumber(value) && isString(units))) { throw new QtyError("Only number accepted as initialization value " + "when units are explicitly provided"); } } else { if (!(isString(value) || isNumber(value) || isQty(value) || isDefinitionObject(value))) { throw new QtyError("Only string, number or quantity accepted as " + "single initialization value"); } } } /** * Tests if a value is a Qty definition object * * @param {*} value - Value to test * * @returns {boolean} true if value is a definition object, false otherwise */ function isDefinitionObject(value) { return value && typeof value === "object" && value.hasOwnProperty("scalar"); } function updateBaseScalar() { 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; } } var KINDS = { "-312078": "elastance", "-312058": "resistance", "-312038": "inductance", "-152058": "potential", "-152040": "magnetism", "-152038": "magnetism", "-7997": "specific_volume", "-79": "snap", "-59": "jolt", "-39": "acceleration", "-38": "radiation", "-20": "frequency", "-19": "speed", "-18": "viscosity", "-17": "volumetric_flow", "-1": "wavenumber", "0": "unitless", "1": "length", "2": "area", "3": "volume", "20": "time", "400": "temperature", "7941": "yank", "7942": "power", "7959": "pressure", "7961": "force", "7962": "energy", "7979": "viscosity", "7981": "momentum", "7982": "angular_momentum", "7997": "density", "7998": "area_density", "8000": "mass", "152020": "radiation_exposure", "159999": "magnetism", "160000": "current", "160020": "charge", "312058": "conductance", "312078": "capacitance", "3199980": "activity", "3199997": "molar_concentration", "3200000": "substance", "63999998": "illuminance", "64000000": "luminous_power", "1280000000": "currency", "25599999980": "information_rate", "25600000000": "information", "511999999980": "angular_velocity", "512000000000": "angle" }; /** * Returns the list of available well-known kinds of units, e.g. * "radiation" or "length". * * @returns {string[]} names of kinds of units */ function getKinds() { return uniq(Object.keys(KINDS).map(function(knownSignature) { return KINDS[knownSignature]; })); } Qty.prototype.kind = function() { return KINDS[this.signature.toString()]; }; assign(Qty.prototype, { 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(//) || this.numerator[0].match(/<(kelvin|celsius|rankine|fahrenheit)>/)); }, isTemperature: function() { return this.isDegrees() && this.numerator[0].match(//); } }); function subtractTemperatures(lhs,rhs) { var lhsUnits = lhs.units(); var rhsConverted = rhs.to(lhsUnits); var dstDegrees = Qty(getDegreeUnits(lhsUnits)); return Qty({"scalar": lhs.scalar - rhsConverted.scalar, "numerator": dstDegrees.numerator, "denominator": dstDegrees.denominator}); } function subtractTempDegrees(temp,deg) { var tempDegrees = deg.to(getDegreeUnits(temp.units())); return Qty({"scalar": temp.scalar - tempDegrees.scalar, "numerator": temp.numerator, "denominator": temp.denominator}); } function addTempDegrees(temp,deg) { var tempDegrees = deg.to(getDegreeUnits(temp.units())); return Qty({"scalar": temp.scalar + tempDegrees.scalar, "numerator": temp.numerator, "denominator": temp.denominator}); } function getDegreeUnits(units) { if (units === "tempK") { return "degK"; } else if (units === "tempC") { return "degC"; } else if (units === "tempF") { return "degF"; } else if (units === "tempR") { return "degR"; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } } function toDegrees(src,dst) { var srcDegK = toDegK(src); var dstUnits = dst.units(); var dstScalar; if (dstUnits === "degK") { dstScalar = srcDegK.scalar; } else if (dstUnits === "degC") { dstScalar = srcDegK.scalar ; } else if (dstUnits === "degF") { dstScalar = srcDegK.scalar * 9 / 5; } else if (dstUnits === "degR") { dstScalar = srcDegK.scalar * 9 / 5; } else { throw new QtyError("Unknown type for degree conversion to: " + dstUnits); } return Qty({"scalar": dstScalar, "numerator": dst.numerator, "denominator": dst.denominator}); } function toDegK(qty) { var units = qty.units(); var q; if (units.match(/(deg)[CFRK]/)) { q = qty.baseScalar; } else if (units === "tempK") { q = qty.scalar; } else if (units === "tempC") { q = qty.scalar; } else if (units === "tempF") { q = qty.scalar * 5 / 9; } else if (units === "tempR") { q = qty.scalar * 5 / 9; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } return Qty({"scalar": q, "numerator": [""], "denominator": UNITY_ARRAY}); } function toTemp(src,dst) { var dstUnits = dst.units(); var dstScalar; if (dstUnits === "tempK") { dstScalar = src.baseScalar; } else if (dstUnits === "tempC") { dstScalar = src.baseScalar - 273.15; } else if (dstUnits === "tempF") { dstScalar = (src.baseScalar * 9 / 5) - 459.67; } else if (dstUnits === "tempR") { dstScalar = src.baseScalar * 9 / 5; } else { throw new QtyError("Unknown type for temp conversion to: " + dstUnits); } return Qty({"scalar": dstScalar, "numerator": dst.numerator, "denominator": dst.denominator}); } function toTempK(qty) { var units = qty.units(); var q; if (units.match(/(deg)[CFRK]/)) { q = qty.baseScalar; } else if (units === "tempK") { q = qty.scalar; } else if (units === "tempC") { q = qty.scalar + 273.15; } else if (units === "tempF") { q = (qty.scalar + 459.67) * 5 / 9; } else if (units === "tempR") { q = qty.scalar * 5 / 9; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } return Qty({"scalar": q, "numerator": [""], "denominator": UNITY_ARRAY}); } assign(Qty.prototype, { /** * 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 === undefined || other === null) { return this; } if (!isString(other)) { return this.to(other.units()); } cached = this._conversionCache[other]; if (cached) { return cached; } // Instantiating target to normalize units target = Qty(other); if (target.units() === this.units()) { return this; } if (!this.isCompatible(target)) { if (this.isInverse(target)) { target = this.inverse().to(other); } else { throwIncompatibleUnits(this.units(), target.units()); } } else { if (target.isTemperature()) { target = toTemp(this,target); } else if (target.isDegrees()) { target = toDegrees(this,target); } else { var q = divSafe(this.baseScalar, target.baseScalar); target = Qty({"scalar": q, "numerator": target.numerator, "denominator": target.denominator}); } } this._conversionCache[other] = target; return target; }, // 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); }, // 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 the nearest multiple of quantity passed as * precision * * @param {(Qty|string|number)} precQuantity - 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(this.units(), precQuantity.units()); } 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()); } }); /** * 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); * */ 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; } }; } var baseUnitCache = {}; function toBaseUnits(numerator,denominator) { var num = []; var den = []; var q = 1; var unit; for (var i = 0; i < numerator.length; i++) { unit = numerator[i]; if (PREFIX_VALUES[unit]) { // workaround to fix // 0.1 * 0.1 => 0.010000000000000002 q = mulSafe(q, PREFIX_VALUES[unit]); } else { if (UNIT_VALUES[unit]) { q *= UNIT_VALUES[unit].scalar; if (UNIT_VALUES[unit].numerator) { num.push(UNIT_VALUES[unit].numerator); } if (UNIT_VALUES[unit].denominator) { den.push(UNIT_VALUES[unit].denominator); } } } } for (var j = 0; j < denominator.length; j++) { unit = denominator[j]; if (PREFIX_VALUES[unit]) { q /= PREFIX_VALUES[unit]; } else { if (UNIT_VALUES[unit]) { q /= UNIT_VALUES[unit].scalar; if (UNIT_VALUES[unit].numerator) { den.push(UNIT_VALUES[unit].numerator); } if (UNIT_VALUES[unit].denominator) { num.push(UNIT_VALUES[unit].denominator); } } } } // Flatten num = num.reduce(function(a,b) { return a.concat(b); }, []); den = den.reduce(function(a,b) { return a.concat(b); }, []); return Qty({"scalar": q, "numerator": num, "denominator": den}); } Qty.parse = globalParse; Qty.getUnits = getUnits; Qty.getAliases = getAliases; Qty.mulSafe = mulSafe; Qty.divSafe = divSafe; Qty.getKinds = getKinds; Qty.swiftConverter = swiftConverter; Qty.Error = QtyError; assign(Qty.prototype, { // Returns new instance with units of this add: function(other) { if (isString(other)) { other = Qty(other); } if (!this.isCompatible(other)) { throwIncompatibleUnits(this.units(), other.units()); } if (this.isTemperature() && other.isTemperature()) { throw new QtyError("Cannot add two temperatures"); } else if (this.isTemperature()) { return addTempDegrees(this, other); } else if (other.isTemperature()) { return addTempDegrees(other, this); } return Qty({"scalar": this.scalar + other.to(this).scalar, "numerator": this.numerator, "denominator": this.denominator}); }, sub: function(other) { if (isString(other)) { other = Qty(other); } if (!this.isCompatible(other)) { throwIncompatibleUnits(this.units(), other.units()); } if (this.isTemperature() && other.isTemperature()) { return subtractTemperatures(this,other); } else if (this.isTemperature()) { return subtractTempDegrees(this,other); } else if (other.isTemperature()) { throw new QtyError("Cannot subtract a temperature from a differential degree unit"); } return Qty({"scalar": this.scalar - other.to(this).scalar, "numerator": this.numerator, "denominator": this.denominator}); }, mul: function(other) { if (isNumber(other)) { return Qty({"scalar": mulSafe(this.scalar, other), "numerator": this.numerator, "denominator": this.denominator}); } else if (isString(other)) { other = Qty(other); } if ((this.isTemperature() || other.isTemperature()) && !(this.isUnitless() || other.isUnitless())) { throw new QtyError("Cannot multiply by temperatures"); } // Quantities should be multiplied with same units if compatible, with base units else var op1 = this; var op2 = other; // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC" if (op1.isCompatible(op2) && op1.signature !== 400) { op2 = op2.to(op1); } var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.numerator, op2.denominator); return Qty({"scalar": mulSafe(op1.scalar, op2.scalar, numdenscale[2]), "numerator": numdenscale[0], "denominator": numdenscale[1]}); }, div: function(other) { if (isNumber(other)) { if (other === 0) { throw new QtyError("Divide by zero"); } return Qty({"scalar": this.scalar / other, "numerator": this.numerator, "denominator": this.denominator}); } else if (isString(other)) { other = Qty(other); } if (other.scalar === 0) { throw new QtyError("Divide by zero"); } if (other.isTemperature()) { throw new QtyError("Cannot divide with temperatures"); } else if (this.isTemperature() && !other.isUnitless()) { throw new QtyError("Cannot divide with temperatures"); } // Quantities should be multiplied with same units if compatible, with base units else var op1 = this; var op2 = other; // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC" if (op1.isCompatible(op2) && op1.signature !== 400) { op2 = op2.to(op1); } var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.denominator, op2.numerator); return Qty({"scalar": mulSafe(op1.scalar, numdenscale[2]) / op2.scalar, "numerator": numdenscale[0], "denominator": numdenscale[1]}); }, // 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}); } }); function cleanTerms(num1, den1, num2, den2) { function notUnity(val) { return val !== UNITY; } num1 = num1.filter(notUnity); num2 = num2.filter(notUnity); den1 = den1.filter(notUnity); den2 = den2.filter(notUnity); var combined = {}; function combineTerms(terms, direction) { var k; var prefix; var prefixValue; for (var i = 0; i < terms.length; i++) { if (PREFIX_VALUES[terms[i]]) { k = terms[i + 1]; prefix = terms[i]; prefixValue = PREFIX_VALUES[prefix]; i++; } else { k = terms[i]; prefix = null; prefixValue = 1; } if (k && k !== UNITY) { if (combined[k]) { combined[k][0] += direction; var combinedPrefixValue = combined[k][2] ? PREFIX_VALUES[combined[k][2]] : 1; combined[k][direction === 1 ? 3 : 4] *= divSafe(prefixValue, combinedPrefixValue); } else { combined[k] = [direction, k, prefix, 1, 1]; } } } } combineTerms(num1, 1); combineTerms(den1, -1); combineTerms(num2, 1); combineTerms(den2, -1); var num = []; var den = []; var scale = 1; for (var prop in combined) { if (combined.hasOwnProperty(prop)) { var item = combined[prop]; var n; if (item[0] > 0) { for (n = 0; n < item[0]; n++) { num.push(item[2] === null ? item[1] : [item[2], item[1]]); } } else if (item[0] < 0) { for (n = 0; n < -item[0]; n++) { den.push(item[2] === null ? item[1] : [item[2], item[1]]); } } scale *= divSafe(item[3], item[4]); } } if (num.length === 0) { num = UNITY_ARRAY; } if (den.length === 0) { den = UNITY_ARRAY; } // Flatten num = num.reduce(function(a,b) { return a.concat(b); }, []); den = den.reduce(function(a,b) { return a.concat(b); }, []); return [num, den, scale]; } assign(Qty.prototype, { 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); }, // 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(this.units(), other.units()); } 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()); } }); assign(Qty.prototype, { // returns true if no associated units // false, even if the units are "unitless" like 'radians, each, etc' isUnitless: function() { return [this.numerator, this.denominator].every(function(item) { return compareArray(item, 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); }, // 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; } }); function NestedMap() {} NestedMap.prototype.get = function(keys) { // Allows to pass key1, key2, ... instead of [key1, key2, ...] if (arguments.length > 1) { // Slower with Firefox but faster with Chrome than // Array.prototype.slice.call(arguments) // See http://jsperf.com/array-apply-versus-array-prototype-slice-call keys = Array.apply(null, arguments); } return keys.reduce(function(map, key, index) { if (map) { var childMap = map[key]; if (index === keys.length - 1) { return childMap ? childMap.data : undefined; } else { return childMap; } } }, this); }; NestedMap.prototype.set = function(keys, value) { if (arguments.length > 2) { keys = Array.prototype.slice.call(arguments, 0, -1); value = arguments[arguments.length - 1]; } return keys.reduce(function(map, key, index) { var childMap = map[key]; if (childMap === undefined) { childMap = map[key] = {}; } if (index === keys.length - 1) { childMap.data = value; return value; } else { return childMap; } }, this); }; /** * Default formatter * * @param {number} scalar - scalar value * @param {string} units - units as string * * @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; assign(Qty.prototype, { // 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); var denIsUnity = compareArray(this.denominator, UNITY_ARRAY); if (numIsUnity && denIsUnity) { this._units = ""; return this._units; } var numUnits = stringifyUnits(this.numerator); var denUnits = stringifyUnits(this.denominator); this._units = numUnits + (denIsUnity ? "" : ("/" + denUnits)); return 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()); } }); var stringifiedUnitsCache = new NestedMap(); /** * Returns a string representing a normalized unit array * * @param {string[]} units Normalized unit array * @returns {string} String representing passed normalized unit array and * suitable for output * */ function stringifyUnits(units) { var stringified = stringifiedUnitsCache.get(units); if (stringified) { return stringified; } var isUnity = compareArray(units, UNITY_ARRAY); if (isUnity) { stringified = "1"; } else { stringified = simplify(getOutputNames(units)).join("*"); } // Cache result stringifiedUnitsCache.set(units, stringified); return stringified; } function getOutputNames(units) { var unitNames = [], token, tokenNext; for (var i = 0; i < units.length; i++) { token = units[i]; tokenNext = units[i + 1]; if (PREFIX_VALUES[token]) { unitNames.push(OUTPUT_MAP[token] + OUTPUT_MAP[tokenNext]); i++; } else { unitNames.push(OUTPUT_MAP[token]); } } return unitNames; } function simplify(units) { // this turns ['s','m','s'] into ['s2','m'] var unitCounts = units.reduce(function(acc, unit) { var unitCounter = acc[unit]; if (!unitCounter) { acc.push(unitCounter = acc[unit] = [unit, 0]); } unitCounter[1]++; return acc; }, []); return unitCounts.map(function(unitCount) { return unitCount[0] + (unitCount[1] > 1 ? unitCount[1] : ""); }); } Qty.version = "1.8.0"; return Qty; })); ================================================ FILE: build/quantities.mjs ================================================ /* The MIT License (MIT) Copyright © 2006-2007 Kevin C. Olbrich Copyright © 2010-2016 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. */ /** * Tests if a value is a string * * @param {*} value - Value to test * * @returns {boolean} true if value is a string, false otherwise */ function isString(value) { return typeof value === "string" || value instanceof String; } /* * Prefer stricter Number.isFinite if currently supported. * To be dropped when ES6 is finalized. Obsolete browsers will * have to use ES6 polyfills. */ var isFiniteImpl = Number.isFinite || window.isFinite; /** * Tests if a value is a number * * @param {*} value - Value to test * * @returns {boolean} true if value is a number, false otherwise */ function isNumber(value) { // Number.isFinite allows not to consider NaN or '1' as numbers return isFiniteImpl(value); } /* * Identity function */ function identity(value) { return value; } /** * Returns unique strings from list * * @param {string[]} strings - array of strings * * * @returns {string[]} a new array of strings without duplicates */ function uniq(strings) { var seen = {}; return strings.filter(function(item) { return seen.hasOwnProperty(item) ? false : (seen[item] = true); }); } function compareArray(array1, array2) { if (array2.length !== array1.length) { return false; } for (var i = 0; i < array1.length; i++) { if (array2[i].compareArray) { if (!array2[i].compareArray(array1[i])) { return false; } } if (array2[i] !== array1[i]) { return false; } } return true; } function assign(target, properties) { Object.keys(properties).forEach(function(key) { target[key] = properties[key]; }); } /** * Safely multiplies numbers while avoiding floating errors * like 0.1 * 0.1 => 0.010000000000000002 * * @param {...number} numbers - numbers to multiply * * @returns {number} result */ function mulSafe() { var result = 1, decimals = 0; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; decimals = decimals + getFractional(arg); result *= arg; } return decimals !== 0 ? round(result, decimals) : result; } /** * Safely divides two numbers while avoiding floating errors * like 0.3 / 0.05 => 5.999999999999999 * * @returns {number} result * @param {number} num Numerator * @param {number} den Denominator */ function divSafe(num, den) { if (den === 0) { throw new Error("Divide by zero"); } var factor = Math.pow(10, getFractional(den)); var invDen = factor / (factor * den); return mulSafe(num, invDen); } /** * Rounds value at the specified number of decimals * * @param {number} val - value to round * @param {number} decimals - number of decimals * * @returns {number} rounded number */ function round(val, decimals) { return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals); } function getFractional(num) { // Check for NaNs or Infinities if (!isFinite(num)) { return 0; } // Faster than parsing strings // http://jsperf.com/count-decimals/2 var count = 0; while (num % 1 !== 0) { num *= 10; count++; } return count; } /** * Custom error type definition * @constructor */ function QtyError() { var err; if (!this) { // Allows to instantiate QtyError without new() err = Object.create(QtyError.prototype); QtyError.apply(err, arguments); return err; } err = Error.apply(this, arguments); this.name = "QtyError"; this.message = err.message; this.stack = err.stack; } QtyError.prototype = Object.create(Error.prototype, {constructor: { value: QtyError }}); /* * Throws incompatible units error * @param {string} left - units * @param {string} right - units incompatible with first argument * @throws "Incompatible units" error */ function throwIncompatibleUnits(left, right) { throw new QtyError("Incompatible units: " + left + " and " + right); } var UNITS = { /* prefixes */ "" : [["googol"], 1e100, "prefix"], "" : [["Ki","Kibi","kibi"], Math.pow(2,10), "prefix"], "" : [["Mi","Mebi","mebi"], Math.pow(2,20), "prefix"], "" : [["Gi","Gibi","gibi"], Math.pow(2,30), "prefix"], "" : [["Ti","Tebi","tebi"], Math.pow(2,40), "prefix"], "" : [["Pi","Pebi","pebi"], Math.pow(2,50), "prefix"], "" : [["Ei","Exi","exi"], Math.pow(2,60), "prefix"], "" : [["Zi","Zebi","zebi"], Math.pow(2,70), "prefix"], "" : [["Yi","Yebi","yebi"], Math.pow(2,80), "prefix"], "" : [["Y","Yotta","yotta"], 1e24, "prefix"], "" : [["Z","Zetta","zetta"], 1e21, "prefix"], "" : [["E","Exa","exa"], 1e18, "prefix"], "" : [["P","Peta","peta"], 1e15, "prefix"], "" : [["T","Tera","tera"], 1e12, "prefix"], "" : [["G","Giga","giga"], 1e9, "prefix"], "" : [["M","Mega","mega"], 1e6, "prefix"], "" : [["k","kilo"], 1e3, "prefix"], "" : [["h","Hecto","hecto"], 1e2, "prefix"], "" : [["da","Deca","deca","deka"], 1e1, "prefix"], "" : [["d","Deci","deci"], 1e-1, "prefix"], "" : [["c","Centi","centi"], 1e-2, "prefix"], "" : [["m","Milli","milli"], 1e-3, "prefix"], "" : [ ["u","\u03BC"/*µ as greek letter*/,"\u00B5"/*µ as micro sign*/,"Micro","mc","micro"], 1e-6, "prefix" ], "" : [["n","Nano","nano"], 1e-9, "prefix"], "" : [["p","Pico","pico"], 1e-12, "prefix"], "" : [["f","Femto","femto"], 1e-15, "prefix"], "" : [["a","Atto","atto"], 1e-18, "prefix"], "" : [["z","Zepto","zepto"], 1e-21, "prefix"], "" : [["y","Yocto","yocto"], 1e-24, "prefix"], "<1>" : [["1", "<1>"], 1, ""], /* length units */ "" : [["m","meter","meters","metre","metres"], 1.0, "length", [""] ], "" : [["in","inch","inches","\""], 0.0254, "length", [""]], "" : [["ft","foot","feet","'"], 0.3048, "length", [""]], "" : [["yd","yard","yards"], 0.9144, "length", [""]], "" : [["mi","mile","miles"], 1609.344, "length", [""]], "" : [["nmi","naut-mile"], 1852, "length", [""]], "": [["league","leagues"], 4828, "length", [""]], "": [["furlong","furlongs"], 201.2, "length", [""]], "" : [["rd","rod","rods"], 5.029, "length", [""]], "" : [["mil","mils"], 0.0000254, "length", [""]], "" :[["ang","angstrom","angstroms"], 1e-10, "length", [""]], "" : [["fathom","fathoms"], 1.829, "length", [""]], "" : [["pica","picas"], 0.00423333333, "length", [""]], "" : [["pt","point","points"], 0.000352777778, "length", [""]], "" : [["z","red-shift", "redshift"], 1.302773e26, "length", [""]], "" : [["AU","astronomical-unit"], 149597900000, "length", [""]], "":[["ls","light-second"], 299792500, "length", [""]], "":[["lmin","light-minute"], 17987550000, "length", [""]], "" : [["ly","light-year"], 9460528000000000, "length", [""]], "" : [["pc","parsec","parsecs"], 30856780000000000, "length", [""]], "" : [["DM","datamile"], 1828.8, "length", [""]], /* mass */ "" : [["kg","kilogram","kilograms"], 1.0, "mass", [""]], "" : [["u","AMU","amu"], 1.660538921e-27, "mass", [""]], "" : [["Da","Dalton","Daltons","dalton","daltons"], 1.660538921e-27, "mass", [""]], "" : [["slug","slugs"], 14.5939029, "mass", [""]], "" : [["tn","ton","short-ton"], 907.18474, "mass", [""]], "":[["t","tonne","metric-ton"], 1000, "mass", [""]], "" : [["ct","carat","carats"], 0.0002, "mass", [""]], "" : [["lbs","lb","pound","pounds","#"], 0.45359237, "mass", [""]], "" : [["oz","ounce","ounces"], 0.0283495231, "mass", [""]], "" : [["g","gram","grams","gramme","grammes"], 1e-3, "mass", [""]], "" : [["grain","grains","gr"], 6.479891e-5, "mass", [""]], "" : [["dram","drams","dr"], 0.0017718452, "mass",[""]], "" : [["stone","stones","st"],6.35029318, "mass",[""]], /* area */ "":[["hectare"], 10000, "area", ["",""]], "":[["acre","acres"], 4046.85642, "area", ["",""]], "":[["sqft"], 0.09290304, "area", ["",""]], /* volume */ "" : [["l","L","liter","liters","litre","litres"], 0.001, "volume", ["","",""]], "": [["gal","gallon","gallons"], 0.0037854118, "volume", ["","",""]], "": [["galimp","gallon-imp","gallons-imp"], 0.0045460900, "volume", ["","",""]], "": [["qt","quart","quarts"], 0.00094635295, "volume", ["","",""]], "": [["pt","pint","pints"], 0.000473176475, "volume", ["","",""]], "": [["ptimp","pint-imp","pints-imp"], 5.6826125e-4, "volume", ["","",""]], "": [["cu","cup","cups"], 0.000236588238, "volume", ["","",""]], "": [["floz","fluid-ounce","fluid-ounces"], 2.95735297e-5, "volume", ["","",""]], "": [["flozimp", "floz-imp","fluid-ounce-imp","fluid-ounces-imp"], 2.84130625e-5, "volume", ["","",""]], "": [["tb","tbsp","tbs","tablespoon","tablespoons"], 1.47867648e-5, "volume", ["","",""]], "": [["tsp","teaspoon","teaspoons"], 4.92892161e-6, "volume", ["","",""]], "": [["bu","bsh","bushel","bushels"], 0.035239072, "volume", ["","",""]], "": [["bbl","oilbarrel", "oilbarrels", "oil-barrel","oil-barrels"], 0.158987294928, "volume", ["","",""]], "": [["bl","bl-us","beerbarrel", "beerbarrels", "beer-barrel","beer-barrels"], 0.1173477658, "volume", ["","",""]], "": [["blimp","bl-imp","beerbarrel-imp", "beerbarrels-imp", "beer-barrel-imp","beer-barrels-imp"], 0.16365924, "volume", ["","",""]], /* speed */ "" : [["kph"], 0.277777778, "speed", [""], [""]], "" : [["mph"], 0.44704, "speed", [""], [""]], "" : [["kt","kn","kts","knot","knots"], 0.514444444, "speed", [""], [""]], "" : [["fps"], 0.3048, "speed", [""], [""]], /* acceleration */ "" : [["gee"], 9.80665, "acceleration", [""], ["",""]], "" : [["Gal"], 1e-2, "acceleration", [""], ["",""]], /* temperature_difference */ "" : [["degK","kelvin"], 1.0, "temperature", [""]], "" : [["degC","celsius","celsius","centigrade"], 1.0, "temperature", [""]], "" : [["degF","fahrenheit"], 5 / 9, "temperature", [""]], "" : [["degR","rankine"], 5 / 9, "temperature", [""]], "" : [["tempK","temp-K"], 1.0, "temperature", [""]], "" : [["tempC","temp-C"], 1.0, "temperature", [""]], "" : [["tempF","temp-F"], 5 / 9, "temperature", [""]], "" : [["tempR","temp-R"], 5 / 9, "temperature", [""]], /* time */ "": [["s","sec","secs","second","seconds"], 1.0, "time", [""]], "": [["min","mins","minute","minutes"], 60.0, "time", [""]], "": [["h","hr","hrs","hour","hours"], 3600.0, "time", [""]], "": [["d","day","days"], 3600 * 24, "time", [""]], "": [["wk","week","weeks"], 7 * 3600 * 24, "time", [""]], "": [["fortnight","fortnights"], 1209600, "time", [""]], "": [["y","yr","year","years","annum"], 31556926, "time", [""]], "":[["decade","decades"], 315569260, "time", [""]], "":[["century","centuries"], 3155692600, "time", [""]], /* pressure */ "" : [["Pa","pascal","Pascal"], 1.0, "pressure", [""],["","",""]], "" : [["bar","bars"], 100000, "pressure", [""],["","",""]], "" : [["mmHg"], 133.322368, "pressure", [""],["","",""]], "" : [["inHg"], 3386.3881472, "pressure", [""],["","",""]], "" : [["torr"], 133.322368, "pressure", [""],["","",""]], "" : [["atm","ATM","atmosphere","atmospheres"], 101325, "pressure", [""],["","",""]], "" : [["psi"], 6894.76, "pressure", [""],["","",""]], "" : [["cmH2O","cmh2o"], 98.0638, "pressure", [""],["","",""]], "" : [["inH2O","inh2o"], 249.082052, "pressure", [""],["","",""]], /* viscosity */ "" : [["P","poise"], 0.1, "viscosity", [""],["",""] ], "" : [["St","stokes"], 1e-4, "viscosity", ["",""], [""]], /* substance */ "" : [["mol","mole"], 1.0, "substance", [""]], /* molar_concentration */ "" : [["M","molar"], 1000, "molar_concentration", [""], ["","",""]], "" : [["wt%","wtpercent"], 10, "molar_concentration", [""], ["","",""]], /* activity */ "" : [["kat","katal","Katal"], 1.0, "activity", [""], [""]], "" : [["U","enzUnit","unit"], 16.667e-16, "activity", [""], [""]], /* capacitance */ "" : [["F","farad","Farad"], 1.0, "capacitance", ["","","","","",""], ["", "", ""]], /* charge */ "" : [["C","coulomb","Coulomb"], 1.0, "charge", ["",""]], "" : [["Ah"], 3600, "charge", ["",""]], "" : [["e"], 1.602176634e-19, "charge", ["",""]], /* current */ "" : [["A","Ampere","ampere","amp","amps"], 1.0, "current", [""]], /* conductance */ "" : [["S","Siemens","siemens"], 1.0, "conductance", ["","","","",""], ["","",""]], /* inductance */ "" : [["H","Henry","henry"], 1.0, "inductance", ["","",""], ["","","",""]], /* potential */ "" : [["V","Volt","volt","volts"], 1.0, "potential", ["","",""], ["","","",""]], /* resistance */ "" : [ ["Ohm","ohm","\u03A9"/*Ω as greek letter*/,"\u2126"/*Ω as ohm sign*/], 1.0, "resistance", ["","",""],["","","","",""] ], /* magnetism */ "" : [["Wb","weber","webers"], 1.0, "magnetism", ["","",""], ["","",""]], "" : [["T","tesla","teslas"], 1.0, "magnetism", [""], ["","",""]], "" : [["G","gauss"], 1e-4, "magnetism", [""], ["","",""]], "" : [["Mx","maxwell","maxwells"], 1e-8, "magnetism", ["","",""], ["","",""]], "" : [["Oe","oersted","oersteds"], 250.0 / Math.PI, "magnetism", [""], [""]], /* energy */ "" : [["J","joule","Joule","joules","Joules"], 1.0, "energy", ["","",""], ["",""]], "" : [["erg","ergs"], 1e-7, "energy", ["","",""], ["",""]], "" : [["BTU","btu","BTUs"], 1055.056, "energy", ["","",""], ["",""]], "" : [["cal","calorie","calories"], 4.18400, "energy",["","",""], ["",""]], "" : [["Cal","Calorie","Calories"], 4184.00, "energy",["","",""], ["",""]], "" : [["th","therm","therms","Therm","therm-US"], 105480400, "energy",["","",""], ["",""]], "" : [["Wh"], 3600, "energy",["","",""], ["",""]], "" : [["eV", "electronvolt", "electronvolts"], 1.602176634E-19, "energy", ["","",""], ["",""]], /* force */ "" : [["N","Newton","newton"], 1.0, "force", ["",""], ["",""]], "" : [["dyn","dyne"], 1e-5, "force", ["",""], ["",""]], "" : [["lbf","pound-force"], 4.448222, "force", ["",""], ["",""]], "" : [["kgf","kilogram-force", "kilopond", "kp"], 9.80665, "force", ["",""], ["",""]], "" : [["gf","gram-force"], 9.80665E-3, "force", ["",""], ["",""]], /* frequency */ "" : [["Hz","hertz","Hertz"], 1.0, "frequency", ["<1>"], [""]], /* angle */ "" :[["rad","radian","radians"], 1.0, "angle", [""]], "" :[["deg","degree","degrees"], Math.PI / 180.0, "angle", [""]], "" :[["arcmin","arcminute","arcminutes"], Math.PI / 10800.0, "angle", [""]], "" :[["arcsec","arcsecond","arcseconds"], Math.PI / 648000.0, "angle", [""]], "" :[["gon","grad","gradian","grads"], Math.PI / 200.0, "angle", [""]], "" : [["sr","steradian","steradians"], 1.0, "solid_angle", [""]], /* rotation */ "" : [["rotation"], 2.0 * Math.PI, "angle", [""]], "" :[["rpm"], 2.0 * Math.PI / 60.0, "angular_velocity", [""], [""]], /* information */ "" :[["B","byte","bytes"], 1.0, "information", [""]], "" :[["b","bit","bits"], 0.125, "information", [""]], /* information rate */ "" : [["Bps"], 1.0, "information_rate", [""], [""]], "" : [["bps"], 0.125, "information_rate", [""], [""]], /* currency */ "":[["USD","dollar"], 1.0, "currency", [""]], "" :[["cents"], 0.01, "currency", [""]], /* luminosity */ "" : [["cd","candela"], 1.0, "luminosity", [""]], "" : [["lm","lumen"], 1.0, "luminous_power", ["",""]], "" :[["lux"], 1.0, "illuminance", ["",""], ["",""]], /* power */ "" : [["W","watt","watts"], 1.0, "power", ["","",""], ["","",""]], "" : [["VA","volt-ampere"], 1.0, "power", ["","",""], ["","",""]], "" : [["var","Var","VAr","VAR","volt-ampere-reactive"], 1.0, "power", ["","",""], ["","",""]], "" : [["hp","horsepower"], 745.699872, "power", ["","",""], ["","",""]], /* radiation */ "" : [["Gy","gray","grays"], 1.0, "radiation", ["",""], ["",""]], "" : [["R","roentgen"], 0.009330, "radiation", ["",""], ["",""]], "" : [["Sv","sievert","sieverts"], 1.0, "radiation", ["",""], ["",""]], "" : [["Bq","becquerel","becquerels"], 1.0, "radiation", ["<1>"],[""]], "" : [["Ci","curie","curies"], 3.7e10, "radiation", ["<1>"],[""]], /* rate */ "" : [["cpm"], 1.0 / 60.0, "rate", [""],[""]], "" : [["dpm"], 1.0 / 60.0, "rate", [""],[""]], "" : [["bpm"], 1.0 / 60.0, "rate", [""],[""]], /* resolution / typography */ "" : [["dot","dots"], 1, "resolution", [""]], "" : [["pixel","px"], 1, "resolution", [""]], "" : [["ppi"], 1, "resolution", [""], [""]], "" : [["dpi"], 1, "typography", [""], [""]], /* other */ "" : [["cells","cell"], 1, "counting", [""]], "" : [["each"], 1.0, "counting", [""]], "" : [["count"], 1.0, "counting", [""]], "" : [["bp","base-pair"], 1.0, "counting", [""]], "" : [["nt","nucleotide"], 1.0, "counting", [""]], "" : [["molecule","molecules"], 1.0, "counting", ["<1>"]], "" : [["doz","dz","dozen"],12.0,"prefix_only", [""]], "": [["%","percent"], 0.01, "prefix_only", ["<1>"]], "" : [["ppm"],1e-6, "prefix_only", ["<1>"]], "" : [["ppb"],1e-9, "prefix_only", ["<1>"]], "" : [["ppt"],1e-12, "prefix_only", ["<1>"]], "" : [["ppq"],1e-15, "prefix_only", ["<1>"]], "" : [["gr","gross"],144.0, "prefix_only", ["",""]], "" : [["dB","decibel","decibels"], 1.0, "logarithmic", [""]] }; var BASE_UNITS = ["","","","", "","","","","","","","","",""]; var UNITY = "<1>"; var UNITY_ARRAY = [UNITY]; // Setup /** * Asserts unit definition is valid * * @param {string} unitDef - Name of unit to test * @param {Object} definition - Definition of unit to test * * @returns {void} * @throws {QtyError} if unit definition is not valid */ function validateUnitDefinition(unitDef, definition) { var scalar = definition[1]; var numerator = definition[3] || []; var denominator = definition[4] || []; if (!isNumber(scalar)) { throw new QtyError(unitDef + ": Invalid unit definition. " + "'scalar' must be a number"); } numerator.forEach(function(unit) { if (UNITS[unit] === undefined) { throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'numerator' is not recognized"); } }); denominator.forEach(function(unit) { if (UNITS[unit] === undefined) { throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'denominator' is not recognized"); } }); } var PREFIX_VALUES = {}; var PREFIX_MAP = {}; var UNIT_VALUES = {}; var UNIT_MAP = {}; var OUTPUT_MAP = {}; for (var unitDef in UNITS) { if (UNITS.hasOwnProperty(unitDef)) { var definition = UNITS[unitDef]; if (definition[2] === "prefix") { PREFIX_VALUES[unitDef] = definition[1]; for (var i = 0; i < definition[0].length; i++) { PREFIX_MAP[definition[0][i]] = unitDef; } } else { validateUnitDefinition(unitDef, definition); UNIT_VALUES[unitDef] = { scalar: definition[1], numerator: definition[3], denominator: definition[4] }; for (var j = 0; j < definition[0].length; j++) { UNIT_MAP[definition[0][j]] = unitDef; } } OUTPUT_MAP[unitDef] = definition[0][0]; } } /** * Returns a list of available units of kind * * @param {string} [kind] - kind of units * @returns {array} names of units * @throws {QtyError} if kind is unknown */ function getUnits(kind) { var i; var units = []; var unitKeys = Object.keys(UNITS); if (typeof kind === "undefined") { for (i = 0; i < unitKeys.length; i++) { if (["", "prefix"].indexOf(UNITS[unitKeys[i]][2]) === -1) { units.push(unitKeys[i].substr(1, unitKeys[i].length - 2)); } } } else if (this.getKinds().indexOf(kind) === -1) { throw new QtyError("Kind not recognized"); } else { for (i = 0; i < unitKeys.length; i++) { if (UNITS[unitKeys[i]][2] === kind) { units.push(unitKeys[i].substr(1, unitKeys[i].length - 2)); } } } return units.sort(function(a, b) { if (a.toLowerCase() < b.toLowerCase()) { return -1; } if (a.toLowerCase() > b.toLowerCase()) { return 1; } return 0; }); } /** * Returns a list of alternative names for a unit * * @param {string} unitName - name of unit * @returns {string[]} aliases for unit * @throws {QtyError} if unit is unknown */ function getAliases(unitName) { if (!UNIT_MAP[unitName]) { throw new QtyError("Unit not recognized"); } return UNITS[UNIT_MAP[unitName]][0]; } var SIGNATURE_VECTOR = ["length", "time", "temperature", "mass", "current", "substance", "luminosity", "currency", "information", "angle"]; /* 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. */ function unitSignature() { 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 function unitSignatureVector() { 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; } 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}"; // Allow unit powers representing scalar, length, area, volume; 4 is for some // special case representations in SI base units. var SAFE_POWER = "[01234]"; var TOP_REGEX = new RegExp ("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(-?" + SAFE_POWER + "(?![a-zA-Z]))"); var BOTTOM_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(" + SAFE_POWER + "(?![a-zA-Z]))"); /* 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 */ function parse(val) { if (!isString(val)) { val = val.toString(); } val = val.trim(); 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); } if (top) { this.numerator = parseUnits(top.trim()); } if (bottom) { this.denominator = parseUnits(bottom.trim()); } } var PREFIX_REGEX = Object.keys(PREFIX_MAP).sort(function(a, b) { return b.length - a.length; }).join("|"); var UNIT_REGEX = Object.keys(UNIT_MAP).sort(function(a, b) { return b.length - a.length; }).join("|"); /* * Minimal boundary regex to support units with Unicode characters * \b only works for ASCII */ var BOUNDARY_REGEX = "\\b|$"; var UNIT_MATCH = "(" + PREFIX_REGEX + ")??(" + UNIT_REGEX + ")(?:" + BOUNDARY_REGEX + ")"; var UNIT_TEST_REGEX = new RegExp("^\\s*(" + UNIT_MATCH + "[\\s\\*]*)+$"); var UNIT_MATCH_REGEX = new RegExp(UNIT_MATCH, "g"); // g flag for multiple occurences var parsedUnitsCache = {}; /** * Parses and converts units string to normalized unit array. * Result is cached to speed up next calls. * * @param {string} units Units string * @returns {string[]} Array of normalized units * * @example * // Returns ["", "", ""] * parseUnits("s m s"); * */ function parseUnits(units) { var cached = parsedUnitsCache[units]; if (cached) { return cached; } var unitMatch, normalizedUnits = []; // Scan if (!UNIT_TEST_REGEX.test(units)) { throw new QtyError("Unit not recognized"); } while ((unitMatch = UNIT_MATCH_REGEX.exec(units))) { normalizedUnits.push(unitMatch.slice(1)); } normalizedUnits = normalizedUnits.map(function(item) { return PREFIX_MAP[item[0]] ? [PREFIX_MAP[item[0]], UNIT_MAP[item[1]]] : [UNIT_MAP[item[1]]]; }); // Flatten and remove null elements normalizedUnits = normalizedUnits.reduce(function(a,b) { return a.concat(b); }, []); normalizedUnits = normalizedUnits.filter(function(item) { return item; }); parsedUnitsCache[units] = normalizedUnits; return normalizedUnits; } /** * 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 */ function globalParse(value) { if (!isString(value)) { throw new QtyError("Argument should be a string"); } try { return this(value); } catch (e) { return null; } } /** * Tests if a value is a Qty instance * * @param {*} value - Value to test * * @returns {boolean} true if value is a Qty instance, false otherwise */ function isQty(value) { return value instanceof Qty; } function Qty(initValue, initUnits) { assertValidConstructorArgs.apply(null, arguments); if (!(isQty(this))) { return new Qty(initValue, initUnits); } 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 if (initUnits) { parse.call(this, initUnits); this.scalar = initValue; } 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"); } } Qty.prototype = { // Properly set up constructor constructor: Qty, }; /** * Asserts constructor arguments are valid * * @param {*} value - Value to test * @param {string} [units] - Optional units when value is passed as a number * * @returns {void} * @throws {QtyError} if constructor arguments are invalid */ function assertValidConstructorArgs(value, units) { if (units) { if (!(isNumber(value) && isString(units))) { throw new QtyError("Only number accepted as initialization value " + "when units are explicitly provided"); } } else { if (!(isString(value) || isNumber(value) || isQty(value) || isDefinitionObject(value))) { throw new QtyError("Only string, number or quantity accepted as " + "single initialization value"); } } } /** * Tests if a value is a Qty definition object * * @param {*} value - Value to test * * @returns {boolean} true if value is a definition object, false otherwise */ function isDefinitionObject(value) { return value && typeof value === "object" && value.hasOwnProperty("scalar"); } function updateBaseScalar() { 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; } } var KINDS = { "-312078": "elastance", "-312058": "resistance", "-312038": "inductance", "-152058": "potential", "-152040": "magnetism", "-152038": "magnetism", "-7997": "specific_volume", "-79": "snap", "-59": "jolt", "-39": "acceleration", "-38": "radiation", "-20": "frequency", "-19": "speed", "-18": "viscosity", "-17": "volumetric_flow", "-1": "wavenumber", "0": "unitless", "1": "length", "2": "area", "3": "volume", "20": "time", "400": "temperature", "7941": "yank", "7942": "power", "7959": "pressure", "7961": "force", "7962": "energy", "7979": "viscosity", "7981": "momentum", "7982": "angular_momentum", "7997": "density", "7998": "area_density", "8000": "mass", "152020": "radiation_exposure", "159999": "magnetism", "160000": "current", "160020": "charge", "312058": "conductance", "312078": "capacitance", "3199980": "activity", "3199997": "molar_concentration", "3200000": "substance", "63999998": "illuminance", "64000000": "luminous_power", "1280000000": "currency", "25599999980": "information_rate", "25600000000": "information", "511999999980": "angular_velocity", "512000000000": "angle" }; /** * Returns the list of available well-known kinds of units, e.g. * "radiation" or "length". * * @returns {string[]} names of kinds of units */ function getKinds() { return uniq(Object.keys(KINDS).map(function(knownSignature) { return KINDS[knownSignature]; })); } Qty.prototype.kind = function() { return KINDS[this.signature.toString()]; }; assign(Qty.prototype, { 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(//) || this.numerator[0].match(/<(kelvin|celsius|rankine|fahrenheit)>/)); }, isTemperature: function() { return this.isDegrees() && this.numerator[0].match(//); } }); function subtractTemperatures(lhs,rhs) { var lhsUnits = lhs.units(); var rhsConverted = rhs.to(lhsUnits); var dstDegrees = Qty(getDegreeUnits(lhsUnits)); return Qty({"scalar": lhs.scalar - rhsConverted.scalar, "numerator": dstDegrees.numerator, "denominator": dstDegrees.denominator}); } function subtractTempDegrees(temp,deg) { var tempDegrees = deg.to(getDegreeUnits(temp.units())); return Qty({"scalar": temp.scalar - tempDegrees.scalar, "numerator": temp.numerator, "denominator": temp.denominator}); } function addTempDegrees(temp,deg) { var tempDegrees = deg.to(getDegreeUnits(temp.units())); return Qty({"scalar": temp.scalar + tempDegrees.scalar, "numerator": temp.numerator, "denominator": temp.denominator}); } function getDegreeUnits(units) { if (units === "tempK") { return "degK"; } else if (units === "tempC") { return "degC"; } else if (units === "tempF") { return "degF"; } else if (units === "tempR") { return "degR"; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } } function toDegrees(src,dst) { var srcDegK = toDegK(src); var dstUnits = dst.units(); var dstScalar; if (dstUnits === "degK") { dstScalar = srcDegK.scalar; } else if (dstUnits === "degC") { dstScalar = srcDegK.scalar ; } else if (dstUnits === "degF") { dstScalar = srcDegK.scalar * 9 / 5; } else if (dstUnits === "degR") { dstScalar = srcDegK.scalar * 9 / 5; } else { throw new QtyError("Unknown type for degree conversion to: " + dstUnits); } return Qty({"scalar": dstScalar, "numerator": dst.numerator, "denominator": dst.denominator}); } function toDegK(qty) { var units = qty.units(); var q; if (units.match(/(deg)[CFRK]/)) { q = qty.baseScalar; } else if (units === "tempK") { q = qty.scalar; } else if (units === "tempC") { q = qty.scalar; } else if (units === "tempF") { q = qty.scalar * 5 / 9; } else if (units === "tempR") { q = qty.scalar * 5 / 9; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } return Qty({"scalar": q, "numerator": [""], "denominator": UNITY_ARRAY}); } function toTemp(src,dst) { var dstUnits = dst.units(); var dstScalar; if (dstUnits === "tempK") { dstScalar = src.baseScalar; } else if (dstUnits === "tempC") { dstScalar = src.baseScalar - 273.15; } else if (dstUnits === "tempF") { dstScalar = (src.baseScalar * 9 / 5) - 459.67; } else if (dstUnits === "tempR") { dstScalar = src.baseScalar * 9 / 5; } else { throw new QtyError("Unknown type for temp conversion to: " + dstUnits); } return Qty({"scalar": dstScalar, "numerator": dst.numerator, "denominator": dst.denominator}); } function toTempK(qty) { var units = qty.units(); var q; if (units.match(/(deg)[CFRK]/)) { q = qty.baseScalar; } else if (units === "tempK") { q = qty.scalar; } else if (units === "tempC") { q = qty.scalar + 273.15; } else if (units === "tempF") { q = (qty.scalar + 459.67) * 5 / 9; } else if (units === "tempR") { q = qty.scalar * 5 / 9; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } return Qty({"scalar": q, "numerator": [""], "denominator": UNITY_ARRAY}); } assign(Qty.prototype, { /** * 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 === undefined || other === null) { return this; } if (!isString(other)) { return this.to(other.units()); } cached = this._conversionCache[other]; if (cached) { return cached; } // Instantiating target to normalize units target = Qty(other); if (target.units() === this.units()) { return this; } if (!this.isCompatible(target)) { if (this.isInverse(target)) { target = this.inverse().to(other); } else { throwIncompatibleUnits(this.units(), target.units()); } } else { if (target.isTemperature()) { target = toTemp(this,target); } else if (target.isDegrees()) { target = toDegrees(this,target); } else { var q = divSafe(this.baseScalar, target.baseScalar); target = Qty({"scalar": q, "numerator": target.numerator, "denominator": target.denominator}); } } this._conversionCache[other] = target; return target; }, // 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); }, // 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 the nearest multiple of quantity passed as * precision * * @param {(Qty|string|number)} precQuantity - 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(this.units(), precQuantity.units()); } 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()); } }); /** * 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); * */ 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; } }; } var baseUnitCache = {}; function toBaseUnits(numerator,denominator) { var num = []; var den = []; var q = 1; var unit; for (var i = 0; i < numerator.length; i++) { unit = numerator[i]; if (PREFIX_VALUES[unit]) { // workaround to fix // 0.1 * 0.1 => 0.010000000000000002 q = mulSafe(q, PREFIX_VALUES[unit]); } else { if (UNIT_VALUES[unit]) { q *= UNIT_VALUES[unit].scalar; if (UNIT_VALUES[unit].numerator) { num.push(UNIT_VALUES[unit].numerator); } if (UNIT_VALUES[unit].denominator) { den.push(UNIT_VALUES[unit].denominator); } } } } for (var j = 0; j < denominator.length; j++) { unit = denominator[j]; if (PREFIX_VALUES[unit]) { q /= PREFIX_VALUES[unit]; } else { if (UNIT_VALUES[unit]) { q /= UNIT_VALUES[unit].scalar; if (UNIT_VALUES[unit].numerator) { den.push(UNIT_VALUES[unit].numerator); } if (UNIT_VALUES[unit].denominator) { num.push(UNIT_VALUES[unit].denominator); } } } } // Flatten num = num.reduce(function(a,b) { return a.concat(b); }, []); den = den.reduce(function(a,b) { return a.concat(b); }, []); return Qty({"scalar": q, "numerator": num, "denominator": den}); } Qty.parse = globalParse; Qty.getUnits = getUnits; Qty.getAliases = getAliases; Qty.mulSafe = mulSafe; Qty.divSafe = divSafe; Qty.getKinds = getKinds; Qty.swiftConverter = swiftConverter; Qty.Error = QtyError; assign(Qty.prototype, { // Returns new instance with units of this add: function(other) { if (isString(other)) { other = Qty(other); } if (!this.isCompatible(other)) { throwIncompatibleUnits(this.units(), other.units()); } if (this.isTemperature() && other.isTemperature()) { throw new QtyError("Cannot add two temperatures"); } else if (this.isTemperature()) { return addTempDegrees(this, other); } else if (other.isTemperature()) { return addTempDegrees(other, this); } return Qty({"scalar": this.scalar + other.to(this).scalar, "numerator": this.numerator, "denominator": this.denominator}); }, sub: function(other) { if (isString(other)) { other = Qty(other); } if (!this.isCompatible(other)) { throwIncompatibleUnits(this.units(), other.units()); } if (this.isTemperature() && other.isTemperature()) { return subtractTemperatures(this,other); } else if (this.isTemperature()) { return subtractTempDegrees(this,other); } else if (other.isTemperature()) { throw new QtyError("Cannot subtract a temperature from a differential degree unit"); } return Qty({"scalar": this.scalar - other.to(this).scalar, "numerator": this.numerator, "denominator": this.denominator}); }, mul: function(other) { if (isNumber(other)) { return Qty({"scalar": mulSafe(this.scalar, other), "numerator": this.numerator, "denominator": this.denominator}); } else if (isString(other)) { other = Qty(other); } if ((this.isTemperature() || other.isTemperature()) && !(this.isUnitless() || other.isUnitless())) { throw new QtyError("Cannot multiply by temperatures"); } // Quantities should be multiplied with same units if compatible, with base units else var op1 = this; var op2 = other; // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC" if (op1.isCompatible(op2) && op1.signature !== 400) { op2 = op2.to(op1); } var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.numerator, op2.denominator); return Qty({"scalar": mulSafe(op1.scalar, op2.scalar, numdenscale[2]), "numerator": numdenscale[0], "denominator": numdenscale[1]}); }, div: function(other) { if (isNumber(other)) { if (other === 0) { throw new QtyError("Divide by zero"); } return Qty({"scalar": this.scalar / other, "numerator": this.numerator, "denominator": this.denominator}); } else if (isString(other)) { other = Qty(other); } if (other.scalar === 0) { throw new QtyError("Divide by zero"); } if (other.isTemperature()) { throw new QtyError("Cannot divide with temperatures"); } else if (this.isTemperature() && !other.isUnitless()) { throw new QtyError("Cannot divide with temperatures"); } // Quantities should be multiplied with same units if compatible, with base units else var op1 = this; var op2 = other; // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC" if (op1.isCompatible(op2) && op1.signature !== 400) { op2 = op2.to(op1); } var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.denominator, op2.numerator); return Qty({"scalar": mulSafe(op1.scalar, numdenscale[2]) / op2.scalar, "numerator": numdenscale[0], "denominator": numdenscale[1]}); }, // 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}); } }); function cleanTerms(num1, den1, num2, den2) { function notUnity(val) { return val !== UNITY; } num1 = num1.filter(notUnity); num2 = num2.filter(notUnity); den1 = den1.filter(notUnity); den2 = den2.filter(notUnity); var combined = {}; function combineTerms(terms, direction) { var k; var prefix; var prefixValue; for (var i = 0; i < terms.length; i++) { if (PREFIX_VALUES[terms[i]]) { k = terms[i + 1]; prefix = terms[i]; prefixValue = PREFIX_VALUES[prefix]; i++; } else { k = terms[i]; prefix = null; prefixValue = 1; } if (k && k !== UNITY) { if (combined[k]) { combined[k][0] += direction; var combinedPrefixValue = combined[k][2] ? PREFIX_VALUES[combined[k][2]] : 1; combined[k][direction === 1 ? 3 : 4] *= divSafe(prefixValue, combinedPrefixValue); } else { combined[k] = [direction, k, prefix, 1, 1]; } } } } combineTerms(num1, 1); combineTerms(den1, -1); combineTerms(num2, 1); combineTerms(den2, -1); var num = []; var den = []; var scale = 1; for (var prop in combined) { if (combined.hasOwnProperty(prop)) { var item = combined[prop]; var n; if (item[0] > 0) { for (n = 0; n < item[0]; n++) { num.push(item[2] === null ? item[1] : [item[2], item[1]]); } } else if (item[0] < 0) { for (n = 0; n < -item[0]; n++) { den.push(item[2] === null ? item[1] : [item[2], item[1]]); } } scale *= divSafe(item[3], item[4]); } } if (num.length === 0) { num = UNITY_ARRAY; } if (den.length === 0) { den = UNITY_ARRAY; } // Flatten num = num.reduce(function(a,b) { return a.concat(b); }, []); den = den.reduce(function(a,b) { return a.concat(b); }, []); return [num, den, scale]; } assign(Qty.prototype, { 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); }, // 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(this.units(), other.units()); } 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()); } }); assign(Qty.prototype, { // returns true if no associated units // false, even if the units are "unitless" like 'radians, each, etc' isUnitless: function() { return [this.numerator, this.denominator].every(function(item) { return compareArray(item, 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); }, // 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; } }); function NestedMap() {} NestedMap.prototype.get = function(keys) { // Allows to pass key1, key2, ... instead of [key1, key2, ...] if (arguments.length > 1) { // Slower with Firefox but faster with Chrome than // Array.prototype.slice.call(arguments) // See http://jsperf.com/array-apply-versus-array-prototype-slice-call keys = Array.apply(null, arguments); } return keys.reduce(function(map, key, index) { if (map) { var childMap = map[key]; if (index === keys.length - 1) { return childMap ? childMap.data : undefined; } else { return childMap; } } }, this); }; NestedMap.prototype.set = function(keys, value) { if (arguments.length > 2) { keys = Array.prototype.slice.call(arguments, 0, -1); value = arguments[arguments.length - 1]; } return keys.reduce(function(map, key, index) { var childMap = map[key]; if (childMap === undefined) { childMap = map[key] = {}; } if (index === keys.length - 1) { childMap.data = value; return value; } else { return childMap; } }, this); }; /** * Default formatter * * @param {number} scalar - scalar value * @param {string} units - units as string * * @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; assign(Qty.prototype, { // 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); var denIsUnity = compareArray(this.denominator, UNITY_ARRAY); if (numIsUnity && denIsUnity) { this._units = ""; return this._units; } var numUnits = stringifyUnits(this.numerator); var denUnits = stringifyUnits(this.denominator); this._units = numUnits + (denIsUnity ? "" : ("/" + denUnits)); return 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()); } }); var stringifiedUnitsCache = new NestedMap(); /** * Returns a string representing a normalized unit array * * @param {string[]} units Normalized unit array * @returns {string} String representing passed normalized unit array and * suitable for output * */ function stringifyUnits(units) { var stringified = stringifiedUnitsCache.get(units); if (stringified) { return stringified; } var isUnity = compareArray(units, UNITY_ARRAY); if (isUnity) { stringified = "1"; } else { stringified = simplify(getOutputNames(units)).join("*"); } // Cache result stringifiedUnitsCache.set(units, stringified); return stringified; } function getOutputNames(units) { var unitNames = [], token, tokenNext; for (var i = 0; i < units.length; i++) { token = units[i]; tokenNext = units[i + 1]; if (PREFIX_VALUES[token]) { unitNames.push(OUTPUT_MAP[token] + OUTPUT_MAP[tokenNext]); i++; } else { unitNames.push(OUTPUT_MAP[token]); } } return unitNames; } function simplify(units) { // this turns ['s','m','s'] into ['s2','m'] var unitCounts = units.reduce(function(acc, unit) { var unitCounter = acc[unit]; if (!unitCounter) { acc.push(unitCounter = acc[unit] = [unit, 0]); } unitCounter[1]++; return acc; }, []); return unitCounts.map(function(unitCount) { return unitCount[0] + (unitCount[1] > 1 ? unitCount[1] : ""); }); } Qty.version = "1.8.0"; export { Qty as default }; ================================================ FILE: lib/JSLitmus.js ================================================ // JSLitmus.js // // Copyright (c) 2010, Robert Kieffer, http://broofa.com // Available under MIT license (http://en.wikipedia.org/wiki/MIT_License) (function() { // Private methods and state // Get platform info but don't go crazy trying to recognize everything // that's out there. This is just for the major platforms and OSes. var platform = 'unknown platform', ua = navigator.userAgent; // Detect OS var oses = ['Windows','iPhone OS','(Intel |PPC )?Mac OS X','Linux'].join('|'); var pOS = new RegExp('((' + oses + ') [^ \);]*)').test(ua) ? RegExp.$1 : null; if (!pOS) pOS = new RegExp('((' + oses + ')[^ \);]*)').test(ua) ? RegExp.$1 : null; // Detect browser var pName = /(Chrome|MSIE|Safari|Opera|Firefox)/.test(ua) ? RegExp.$1 : null; // Detect version var vre = new RegExp('(Version|' + pName + ')[ \/]([^ ;]*)'); var pVersion = (pName && vre.test(ua)) ? RegExp.$2 : null; var platform = (pOS && pName && pVersion) ? pName + ' ' + pVersion + ' on ' + pOS : 'unknown platform'; /** * A smattering of methods that are needed to implement the JSLitmus testbed. */ var jsl = { /** * Enhanced version of escape() */ escape: function(s) { s = s.replace(/,/g, '\\,'); s = escape(s); s = s.replace(/\+/g, '%2b'); s = s.replace(/ /g, '+'); return s; }, /** * Get an element by ID. */ $: function(id) { return document.getElementById(id); }, /** * Null function */ F: function() {}, /** * Set the status shown in the UI */ status: function(msg) { var el = jsl.$('jsl_status'); if (el) el.innerHTML = msg || ''; }, /** * Convert a number to an abbreviated string like, "15K" or "10M" */ toLabel: function(n) { if (n == Infinity) { return 'Infinity'; } else if (n > 1e9) { n = Math.round(n/1e8); return n/10 + 'B'; } else if (n > 1e6) { n = Math.round(n/1e5); return n/10 + 'M'; } else if (n > 1e3) { n = Math.round(n/1e2); return n/10 + 'K'; } return n; }, /** * Copy properties from src to dst */ extend: function(dst, src) { for (var k in src) dst[k] = src[k]; return dst; }, /** * Like Array.join(), but for the key-value pairs in an object */ join: function(o, delimit1, delimit2) { if (o.join) return o.join(delimit1); // If it's an array var pairs = []; for (var k in o) pairs.push(k + delimit1 + o[k]); return pairs.join(delimit2); }, /** * Array#indexOf isn't supported in IE, so we use this as a cross-browser solution */ indexOf: function(arr, o) { if (arr.indexOf) return arr.indexOf(o); for (var i = 0; i < this.length; i++) if (arr[i] === o) return i; return -1; } }; /** * Test manages a single test (created with * JSLitmus.test()) * * @private */ var Test = function (name, f) { if (!f) throw new Error('Undefined test function'); if (!/function[^\(]*\(([^,\)]*)/.test(f.toString())) { throw new Error('"' + name + '" test: Test is not a valid Function object'); } this.loopArg = RegExp.$1; this.name = name; this.f = f; }; jsl.extend(Test, /** @lends Test */ { /** Calibration tests for establishing iteration loop overhead */ CALIBRATIONS: [ new Test('calibrating loop', function(count) {while (count--);}), new Test('calibrating function', jsl.F) ], /** * Run calibration tests. Returns true if calibrations are not yet * complete (in which case calling code should run the tests yet again). * onCalibrated - Callback to invoke when calibrations have finished */ calibrate: function(onCalibrated) { for (var i = 0; i < Test.CALIBRATIONS.length; i++) { var cal = Test.CALIBRATIONS[i]; if (cal.running) return true; if (!cal.count) { cal.isCalibration = true; cal.onStop = onCalibrated; //cal.MIN_TIME = .1; // Do calibrations quickly cal.run(2e4); return true; } } return false; } }); jsl.extend(Test.prototype, {/** @lends Test.prototype */ /** Initial number of iterations */ INIT_COUNT: 10, /** Max iterations allowed (i.e. used to detect bad looping functions) */ MAX_COUNT: 1e9, /** Minimum time a test should take to get valid results (secs) */ MIN_TIME: .5, /** Callback invoked when test state changes */ onChange: jsl.F, /** Callback invoked when test is finished */ onStop: jsl.F, /** * Reset test state */ reset: function() { delete this.count; delete this.time; delete this.running; delete this.error; }, /** * Run the test (in a timeout). We use a timeout to make sure the browser * has a chance to finish rendering any UI changes we've made, like * updating the status message. */ run: function(count) { count = count || this.INIT_COUNT; jsl.status(this.name + ' x ' + count); this.running = true; var me = this; setTimeout(function() {me._run(count);}, 200); }, /** * The nuts and bolts code that actually runs a test */ _run: function(count) { var me = this; // Make sure calibration tests have run if (!me.isCalibration && Test.calibrate(function() {me.run(count);})) return; this.error = null; try { var start, f = this.f, now, i = count; // Start the timer start = new Date(); // Now for the money shot. If this is a looping function ... if (this.loopArg) { // ... let it do the iteration itself f(count); } else { // ... otherwise do the iteration for it while (i--) f(); } // Get time test took (in secs) this.time = Math.max(1,new Date() - start)/1000; // Store iteration count and per-operation time taken this.count = count; this.period = this.time/count; // Do we need to do another run? this.running = this.time <= this.MIN_TIME; // ... if so, compute how many times we should iterate if (this.running) { // Bump the count to the nearest power of 2 var x = this.MIN_TIME/this.time; var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2)))); count *= pow; if (count > this.MAX_COUNT) { throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.'); } } } catch (e) { // Exceptions are caught and displayed in the test UI this.reset(); this.error = e; } // Figure out what to do next if (this.running) { me.run(count); } else { jsl.status(''); me.onStop(me); } // Finish up this.onChange(this); }, /** * Get the number of operations per second for this test. * * @param normalize if true, iteration loop overhead taken into account */ getHz: function(/**Boolean*/ normalize) { var p = this.period; // Adjust period based on the calibration test time if (normalize && !this.isCalibration) { var cal = Test.CALIBRATIONS[this.loopArg ? 0 : 1]; // If the period is within 20% of the calibration time, then zero the // it out p = p < cal.period*1.2 ? 0 : p - cal.period; } return Math.round(1/p); }, /** * Get a friendly string describing the test */ toString: function() { return this.name + ' - ' + this.time/this.count + ' secs'; } }); // CSS we need for the UI var STYLESHEET = ''; // HTML markup for the UI var MARKUP = '
\ \ \
\
\ Normalize results \ \ \ \ \ \ \ \ \ \ \ \
' + platform + '
TestOps/sec
\
\ \ Powered by JSLitmus \
'; /** * The public API for creating and running tests */ window.JSLitmus = { /** The list of all tests that have been registered with JSLitmus.test */ _tests: [], /** The queue of tests that need to be run */ _queue: [], /** * The parsed query parameters the current page URL. This is provided as a * convenience for test functions - it's not used by JSLitmus proper */ params: {}, /** * Initialize */ _init: function() { // Parse query params into JSLitmus.params[] hash var match = (location + '').match(/([^?#]*)(#.*)?$/); if (match) { var pairs = match[1].split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); if (pair.length > 1) { var key = pair.shift(); var value = pair.length > 1 ? pair.join('=') : pair[0]; this.params[key] = value; } } } // Write out the stylesheet. We have to do this here because IE // doesn't honor sheets written after the document has loaded. document.write(STYLESHEET); // Setup the rest of the UI once the document is loaded if (window.addEventListener) { window.addEventListener('load', this._setup, false); } else if (document.addEventListener) { document.addEventListener('load', this._setup, false); } else if (window.attachEvent) { window.attachEvent('onload', this._setup); } return this; }, /** * Set up the UI */ _setup: function() { var el = jsl.$('jslitmus_container'); if (!el) document.body.appendChild(el = document.createElement('div')); el.innerHTML = MARKUP; // Render the UI for all our tests for (var i=0; i < JSLitmus._tests.length; i++) JSLitmus.renderTest(JSLitmus._tests[i]); }, /** * (Re)render all the test results */ renderAll: function() { for (var i = 0; i < JSLitmus._tests.length; i++) JSLitmus.renderTest(JSLitmus._tests[i]); JSLitmus.renderChart(); }, /** * (Re)render the chart graphics */ renderChart: function() { var url = JSLitmus.chartUrl(); jsl.$('chart_link').href = url; jsl.$('chart_image').src = url; jsl.$('chart').style.display = ''; // Update the tiny URL jsl.$('tiny_url').src = 'http://tinyurl.com/api-create.php?url='+escape(url); }, /** * (Re)render the results for a specific test */ renderTest: function(test) { // Make a new row if needed if (!test._row) { var trow = jsl.$('test_row_template'); if (!trow) return; test._row = trow.cloneNode(true); test._row.style.display = ''; test._row.id = ''; test._row.onclick = function() {JSLitmus._queueTest(test);}; test._row.title = 'Run ' + test.name + ' test'; trow.parentNode.appendChild(test._row); test._row.cells[0].innerHTML = test.name; } var cell = test._row.cells[1]; var cns = [test.loopArg ? 'test_looping' : 'test_nonlooping']; if (test.error) { cns.push('test_error'); cell.innerHTML = '
' + test.error + '
' + '
  • ' + jsl.join(test.error, ': ', '
  • ') + '
'; } else { if (test.running) { cns.push('test_running'); cell.innerHTML = 'running'; } else if (jsl.indexOf(JSLitmus._queue, test) >= 0) { cns.push('test_pending'); cell.innerHTML = 'pending'; } else if (test.count) { cns.push('test_done'); var hz = test.getHz(jsl.$('test_normalize').checked); cell.innerHTML = hz != Infinity ? hz : '∞'; cell.title = 'Looped ' + test.count + ' times in ' + test.time + ' seconds'; } else { cell.innerHTML = 'ready'; } } cell.className = cns.join(' '); }, /** * Create a new test */ test: function(name, f) { // Create the Test object var test = new Test(name, f); JSLitmus._tests.push(test); // Re-render if the test state changes test.onChange = JSLitmus.renderTest; // Run the next test if this one finished test.onStop = function(test) { if (JSLitmus.onTestFinish) JSLitmus.onTestFinish(test); JSLitmus.currentTest = null; JSLitmus._nextTest(); }; // Render the new test this.renderTest(test); }, /** * Add all tests to the run queue */ runAll: function(e) { e = e || window.event; var reverse = e && e.shiftKey, len = JSLitmus._tests.length; for (var i = 0; i < len; i++) { JSLitmus._queueTest(JSLitmus._tests[!reverse ? i : (len - i - 1)]); } }, /** * Remove all tests from the run queue. The current test has to finish on * it's own though */ stop: function() { while (JSLitmus._queue.length) { var test = JSLitmus._queue.shift(); JSLitmus.renderTest(test); } }, /** * Run the next test in the run queue */ _nextTest: function() { if (!JSLitmus.currentTest) { var test = JSLitmus._queue.shift(); if (test) { jsl.$('stop_button').disabled = false; JSLitmus.currentTest = test; test.run(); JSLitmus.renderTest(test); if (JSLitmus.onTestStart) JSLitmus.onTestStart(test); } else { jsl.$('stop_button').disabled = true; JSLitmus.renderChart(); } } }, /** * Add a test to the run queue */ _queueTest: function(test) { if (jsl.indexOf(JSLitmus._queue, test) >= 0) return; JSLitmus._queue.push(test); JSLitmus.renderTest(test); JSLitmus._nextTest(); }, /** * Generate a Google Chart URL that shows the data for all tests */ chartUrl: function() { var n = JSLitmus._tests.length, markers = [], data = []; var d, min = 0, max = -1e10; var normalize = jsl.$('test_normalize').checked; // Gather test data for (var i=0; i < JSLitmus._tests.length; i++) { var test = JSLitmus._tests[i]; if (test.count) { var hz = test.getHz(normalize); var v = hz != Infinity ? hz : 0; data.push(v); markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' + markers.length + ',10'); max = Math.max(v, max); } } if (markers.length <= 0) return null; // Build chart title var title = document.getElementsByTagName('title'); title = (title && title.length) ? title[0].innerHTML : null; var chart_title = []; if (title) chart_title.push(title); chart_title.push('Ops/sec (' + platform + ')'); // Build labels var labels = [jsl.toLabel(min), jsl.toLabel(max)]; var w = 250, bw = 15; var bs = 5; var h = markers.length*(bw + bs) + 30 + chart_title.length*20; var params = { chtt: escape(chart_title.join('|')), chts: '000000,10', cht: 'bhg', // chart type chd: 't:' + data.join(','), // data set chds: min + ',' + max, // max/min of data chxt: 'x', // label axes chxl: '0:|' + labels.join('|'), // labels chsp: '0,1', chm: markers.join('|'), // test names chbh: [bw, 0, bs].join(','), // bar widths // chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient chs: w + 'x' + h }; return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&'); } }; JSLitmus._init(); })(); ================================================ FILE: lib/jasmine-3.4.0/boot.js ================================================ /** Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. [jasmine-gem]: http://github.com/pivotal/jasmine-gem */ (function() { /** * ## Require & Instantiate * * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. */ window.jasmine = jasmineRequire.core(jasmineRequire); /** * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. */ jasmineRequire.html(jasmine); /** * Create the Jasmine environment. This is used to run all specs in a project. */ var env = jasmine.getEnv(); /** * ## The Global Interface * * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. */ var jasmineInterface = jasmineRequire.interface(jasmine, env); /** * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. */ extend(window, jasmineInterface); /** * ## Runner Parameters * * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. */ var queryString = new jasmine.QueryString({ getWindowLocation: function() { return window.location; } }); var filterSpecs = !!queryString.getParam("spec"); var config = { failFast: queryString.getParam("failFast"), oneFailurePerSpec: queryString.getParam("oneFailurePerSpec"), hideDisabled: queryString.getParam("hideDisabled") }; var random = queryString.getParam("random"); if (random !== undefined && random !== "") { config.random = random; } var seed = queryString.getParam("seed"); if (seed) { config.seed = seed; } /** * ## Reporters * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). */ var htmlReporter = new jasmine.HtmlReporter({ env: env, navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, getContainer: function() { return document.body; }, createElement: function() { return document.createElement.apply(document, arguments); }, createTextNode: function() { return document.createTextNode.apply(document, arguments); }, timer: new jasmine.Timer(), filterSpecs: filterSpecs }); /** * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. */ env.addReporter(jasmineInterface.jsApiReporter); env.addReporter(htmlReporter); /** * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ var specFilter = new jasmine.HtmlSpecFilter({ filterString: function() { return queryString.getParam("spec"); } }); config.specFilter = function(spec) { return specFilter.matches(spec.getFullName()); }; env.configure(config); /** * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. */ window.setTimeout = window.setTimeout; window.setInterval = window.setInterval; window.clearTimeout = window.clearTimeout; window.clearInterval = window.clearInterval; /** * ## Execution * * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. */ var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } htmlReporter.initialize(); env.execute(); }; /** * Helper function for readability above. */ function extend(destination, source) { for (var property in source) destination[property] = source[property]; return destination; } }()); ================================================ FILE: lib/jasmine-3.4.0/jasmine-html.js ================================================ /* Copyright (c) 2008-2019 Pivotal Labs 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. */ jasmineRequire.html = function(j$) { j$.ResultsNode = jasmineRequire.ResultsNode(); j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); j$.QueryString = jasmineRequire.QueryString(); j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); }; jasmineRequire.HtmlReporter = function(j$) { function ResultsStateBuilder() { this.topResults = new j$.ResultsNode({}, '', null); this.currentParent = this.topResults; this.specsExecuted = 0; this.failureCount = 0; this.pendingSpecCount = 0; } ResultsStateBuilder.prototype.suiteStarted = function(result) { this.currentParent.addChild(result, 'suite'); this.currentParent = this.currentParent.last(); }; ResultsStateBuilder.prototype.suiteDone = function(result) { this.currentParent.updateResult(result); if (this.currentParent !== this.topResults) { this.currentParent = this.currentParent.parent; } if (result.status === 'failed') { this.failureCount++; } }; ResultsStateBuilder.prototype.specStarted = function(result) { }; ResultsStateBuilder.prototype.specDone = function(result) { this.currentParent.addChild(result, 'spec'); if (result.status !== 'excluded') { this.specsExecuted++; } if (result.status === 'failed') { this.failureCount++; } if (result.status == 'pending') { this.pendingSpecCount++; } }; function HtmlReporter(options) { var config = function() { return (options.env && options.env.configuration()) || {}; }, getContainer = options.getContainer, createElement = options.createElement, createTextNode = options.createTextNode, navigateWithNewParam = options.navigateWithNewParam || function() {}, addToExistingQueryString = options.addToExistingQueryString || defaultQueryString, filterSpecs = options.filterSpecs, timer = options.timer || j$.noopTimer, htmlReporterMain, symbols, deprecationWarnings = []; this.initialize = function() { clearPrior(); htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'}, createDom('div', {className: 'jasmine-banner'}, createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}), createDom('span', {className: 'jasmine-version'}, j$.version) ), createDom('ul', {className: 'jasmine-symbol-summary'}), createDom('div', {className: 'jasmine-alert'}), createDom('div', {className: 'jasmine-results'}, createDom('div', {className: 'jasmine-failures'}) ) ); getContainer().appendChild(htmlReporterMain); }; var totalSpecsDefined; this.jasmineStarted = function(options) { totalSpecsDefined = options.totalSpecsDefined || 0; timer.start(); }; var summary = createDom('div', {className: 'jasmine-summary'}); var stateBuilder = new ResultsStateBuilder(); this.suiteStarted = function(result) { stateBuilder.suiteStarted(result); }; this.suiteDone = function(result) { stateBuilder.suiteDone(result); if (result.status === 'failed') { failures.push(failureDom(result)); } addDeprecationWarnings(result); }; this.specStarted = function(result) { stateBuilder.specStarted(result); }; var failures = []; this.specDone = function(result) { stateBuilder.specDone(result); if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') { console.error('Spec \'' + result.fullName + '\' has no expectations.'); } if (!symbols){ symbols = find('.jasmine-symbol-summary'); } symbols.appendChild(createDom('li', { className: this.displaySpecInCorrectFormat(result), id: 'spec_' + result.id, title: result.fullName } )); if (result.status === 'failed') { failures.push(failureDom(result)); } addDeprecationWarnings(result); }; this.displaySpecInCorrectFormat = function(result) { return noExpectations(result) ? 'jasmine-empty' : this.resultStatus(result.status); }; this.resultStatus = function(status) { if(status === 'excluded') { return config().hideDisabled ? 'jasmine-excluded-no-display' : 'jasmine-excluded'; } return 'jasmine-' + status; }; this.jasmineDone = function(doneResult) { var banner = find('.jasmine-banner'); var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; var i; alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's')); banner.appendChild(optionsMenu(config())); if (stateBuilder.specsExecuted < totalSpecsDefined) { var skippedMessage = 'Ran ' + stateBuilder.specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; var skippedLink = addToExistingQueryString('spec', ''); alert.appendChild( createDom('span', {className: 'jasmine-bar jasmine-skipped'}, createDom('a', {href: skippedLink, title: 'Run all specs'}, skippedMessage) ) ); } var statusBarMessage = ''; var statusBarClassName = 'jasmine-overall-result jasmine-bar '; var globalFailures = (doneResult && doneResult.failedExpectations) || []; var failed = stateBuilder.failureCount + globalFailures.length > 0; if (totalSpecsDefined > 0 || failed) { statusBarMessage += pluralize('spec', stateBuilder.specsExecuted) + ', ' + pluralize('failure', stateBuilder.failureCount); if (stateBuilder.pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); } } if (doneResult.overallStatus === 'passed') { statusBarClassName += ' jasmine-passed '; } else if (doneResult.overallStatus === 'incomplete') { statusBarClassName += ' jasmine-incomplete '; statusBarMessage = 'Incomplete: ' + doneResult.incompleteReason + ', ' + statusBarMessage; } else { statusBarClassName += ' jasmine-failed '; } var seedBar; if (order && order.random) { seedBar = createDom('span', {className: 'jasmine-seed-bar'}, ', randomized with seed ', createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed) ); } alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar)); var errorBarClassName = 'jasmine-bar jasmine-errored'; var afterAllMessagePrefix = 'AfterAll '; for(i = 0; i < globalFailures.length; i++) { alert.appendChild(createDom('span', {className: errorBarClassName}, globalFailureMessage(globalFailures[i]))); } function globalFailureMessage(failure) { if (failure.globalErrorType === 'load') { var prefix = 'Error during loading: ' + failure.message; if (failure.filename) { return prefix + ' in ' + failure.filename + ' line ' + failure.lineno; } else { return prefix; } } else { return afterAllMessagePrefix + failure.message; } } addDeprecationWarnings(doneResult); var warningBarClassName = 'jasmine-bar jasmine-warning'; for(i = 0; i < deprecationWarnings.length; i++) { var warning = deprecationWarnings[i]; alert.appendChild(createDom('span', {className: warningBarClassName}, 'DEPRECATION: ' + warning)); } var results = find('.jasmine-results'); results.appendChild(summary); summaryList(stateBuilder.topResults, summary); if (failures.length) { alert.appendChild( createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'}, createDom('span', {}, 'Spec List | '), createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures'))); alert.appendChild( createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'}, createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'), createDom('span', {}, ' | Failures '))); find('.jasmine-failures-menu').onclick = function() { setMenuModeTo('jasmine-failure-list'); }; find('.jasmine-spec-list-menu').onclick = function() { setMenuModeTo('jasmine-spec-list'); }; setMenuModeTo('jasmine-failure-list'); var failureNode = find('.jasmine-failures'); for (i = 0; i < failures.length; i++) { failureNode.appendChild(failures[i]); } } }; return this; function failureDom(result) { var failure = createDom('div', {className: 'jasmine-spec-detail jasmine-failed'}, failureDescription(result, stateBuilder.currentParent), createDom('div', {className: 'jasmine-messages'}) ); var messages = failure.childNodes[1]; for (var i = 0; i < result.failedExpectations.length; i++) { var expectation = result.failedExpectations[i]; messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message)); messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack)); } return failure; } function summaryList(resultsTree, domParent) { var specListNode; for (var i = 0; i < resultsTree.children.length; i++) { var resultNode = resultsTree.children[i]; if (filterSpecs && !hasActiveSpec(resultNode)) { continue; } if (resultNode.type === 'suite') { var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id}, createDom('li', {className: 'jasmine-suite-detail jasmine-' + resultNode.result.status}, createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description) ) ); summaryList(resultNode, suiteListNode); domParent.appendChild(suiteListNode); } if (resultNode.type === 'spec') { if (domParent.getAttribute('class') !== 'jasmine-specs') { specListNode = createDom('ul', {className: 'jasmine-specs'}); domParent.appendChild(specListNode); } var specDescription = resultNode.result.description; if(noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') { specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason; } specListNode.appendChild( createDom('li', { className: 'jasmine-' + resultNode.result.status, id: 'spec-' + resultNode.result.id }, createDom('a', {href: specHref(resultNode.result)}, specDescription) ) ); } } } function optionsMenu(config) { var optionsMenuDom = createDom('div', { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), createDom('div', { className: 'jasmine-payload' }, createDom('div', { className: 'jasmine-stop-on-failure' }, createDom('input', { className: 'jasmine-fail-fast', id: 'jasmine-fail-fast', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-fail-fast' }, 'stop execution on spec failure')), createDom('div', { className: 'jasmine-throw-failures' }, createDom('input', { className: 'jasmine-throw', id: 'jasmine-throw-failures', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')), createDom('div', { className: 'jasmine-random-order' }, createDom('input', { className: 'jasmine-random', id: 'jasmine-random-order', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')), createDom('div', { className: 'jasmine-hide-disabled' }, createDom('input', { className: 'jasmine-disabled', id: 'jasmine-hide-disabled', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-hide-disabled' }, 'hide disabled tests')) ) ); var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast'); failFastCheckbox.checked = config.failFast; failFastCheckbox.onclick = function() { navigateWithNewParam('failFast', !config.failFast); }; var throwCheckbox = optionsMenuDom.querySelector('#jasmine-throw-failures'); throwCheckbox.checked = config.oneFailurePerSpec; throwCheckbox.onclick = function() { navigateWithNewParam('throwFailures', !config.oneFailurePerSpec); }; var randomCheckbox = optionsMenuDom.querySelector('#jasmine-random-order'); randomCheckbox.checked = config.random; randomCheckbox.onclick = function() { navigateWithNewParam('random', !config.random); }; var hideDisabled = optionsMenuDom.querySelector('#jasmine-hide-disabled'); hideDisabled.checked = config.hideDisabled; hideDisabled.onclick = function() { navigateWithNewParam('hideDisabled', !config.hideDisabled); }; var optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), optionsPayload = optionsMenuDom.querySelector('.jasmine-payload'), isOpen = /\bjasmine-open\b/; optionsTrigger.onclick = function() { if (isOpen.test(optionsPayload.className)) { optionsPayload.className = optionsPayload.className.replace(isOpen, ''); } else { optionsPayload.className += ' jasmine-open'; } }; return optionsMenuDom; } function failureDescription(result, suite) { var wrapper = createDom('div', {className: 'jasmine-description'}, createDom('a', {title: result.description, href: specHref(result)}, result.description) ); var suiteLink; while (suite && suite.parent) { wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); suiteLink = createDom('a', {href: suiteHref(suite)}, suite.result.description); wrapper.insertBefore(suiteLink, wrapper.firstChild); suite = suite.parent; } return wrapper; } function suiteHref(suite) { var els = []; while (suite && suite.parent) { els.unshift(suite.result.description); suite = suite.parent; } return addToExistingQueryString('spec', els.join(' ')); } function addDeprecationWarnings(result) { if (result && result.deprecationWarnings) { for(var i = 0; i < result.deprecationWarnings.length; i++) { var warning = result.deprecationWarnings[i].message; if (!j$.util.arrayContains(warning)) { deprecationWarnings.push(warning); } } } } function find(selector) { return getContainer().querySelector('.jasmine_html-reporter ' + selector); } function clearPrior() { // return the reporter var oldReporter = find(''); if(oldReporter) { getContainer().removeChild(oldReporter); } } function createDom(type, attrs, childrenVarArgs) { var el = createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == 'className') { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; } function pluralize(singular, count) { var word = (count == 1 ? singular : singular + 's'); return '' + count + ' ' + word; } function specHref(result) { return addToExistingQueryString('spec', result.fullName); } function seedHref(seed) { return addToExistingQueryString('seed', seed); } function defaultQueryString(key, value) { return '?' + key + '=' + value; } function setMenuModeTo(mode) { htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode); } function noExpectations(result) { return (result.failedExpectations.length + result.passedExpectations.length) === 0 && result.status === 'passed'; } function hasActiveSpec(resultNode) { if (resultNode.type == 'spec' && resultNode.result.status != 'excluded') { return true; } if (resultNode.type == 'suite') { for (var i = 0, j = resultNode.children.length; i < j; i++) { if (hasActiveSpec(resultNode.children[i])) { return true; } } } } } return HtmlReporter; }; jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); var filterPattern = new RegExp(filterString); this.matches = function(specName) { return filterPattern.test(specName); }; } return HtmlSpecFilter; }; jasmineRequire.ResultsNode = function() { function ResultsNode(result, type, parent) { this.result = result; this.type = type; this.parent = parent; this.children = []; this.addChild = function(result, type) { this.children.push(new ResultsNode(result, type, this)); }; this.last = function() { return this.children[this.children.length - 1]; }; this.updateResult = function(result) { this.result = result; }; } return ResultsNode; }; jasmineRequire.QueryString = function() { function QueryString(options) { this.navigateWithNewParam = function(key, value) { options.getWindowLocation().search = this.fullStringWithNewParam(key, value); }; this.fullStringWithNewParam = function(key, value) { var paramMap = queryStringToParamMap(); paramMap[key] = value; return toQueryString(paramMap); }; this.getParam = function(key) { return queryStringToParamMap()[key]; }; return this; function toQueryString(paramMap) { var qStrPairs = []; for (var prop in paramMap) { qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])); } return '?' + qStrPairs.join('&'); } function queryStringToParamMap() { var paramStr = options.getWindowLocation().search.substring(1), params = [], paramMap = {}; if (paramStr.length > 0) { params = paramStr.split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); var value = decodeURIComponent(p[1]); if (value === 'true' || value === 'false') { value = JSON.parse(value); } paramMap[decodeURIComponent(p[0])] = value; } } return paramMap; } } return QueryString; }; ================================================ FILE: lib/jasmine-3.4.0/jasmine.css ================================================ @charset "UTF-8"; body { overflow-y: scroll; } .jasmine_html-reporter { background-color: #eee; padding: 5px; margin: -8px; font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333; } .jasmine_html-reporter a { text-decoration: none; } .jasmine_html-reporter a:hover { text-decoration: underline; } .jasmine_html-reporter p, .jasmine_html-reporter h1, .jasmine_html-reporter h2, .jasmine_html-reporter h3, .jasmine_html-reporter h4, .jasmine_html-reporter h5, .jasmine_html-reporter h6 { margin: 0; line-height: 14px; } .jasmine_html-reporter .jasmine-banner, .jasmine_html-reporter .jasmine-symbol-summary, .jasmine_html-reporter .jasmine-summary, .jasmine_html-reporter .jasmine-result-message, .jasmine_html-reporter .jasmine-spec .jasmine-description, .jasmine_html-reporter .jasmine-spec-detail .jasmine-description, .jasmine_html-reporter .jasmine-alert .jasmine-bar, .jasmine_html-reporter .jasmine-stack-trace { padding-left: 9px; padding-right: 9px; } .jasmine_html-reporter .jasmine-banner { position: relative; } .jasmine_html-reporter .jasmine-banner .jasmine-title { background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZCAMAAACGusnyAAACdlBMVEX/////AP+AgICqVaqAQICZM5mAVYCSSZKAQICOOY6ATYCLRouAQICJO4mSSYCIRIiPQICHPIeOR4CGQ4aMQICGPYaLRoCFQ4WKQICPPYWJRYCOQoSJQICNPoSIRICMQoSHQICHRICKQoOHQICKPoOJO4OJQYOMQICMQ4CIQYKLQICIPoKLQ4CKQICNPoKJQISMQ4KJQoSLQYKJQISLQ4KIQoSKQYKIQICIQISMQoSKQYKLQIOLQoOJQYGLQIOKQIOMQoGKQYOLQYGKQIOLQoGJQYOJQIOKQYGJQIOKQoGKQIGLQIKLQ4KKQoGLQYKJQIGKQYKJQIGKQIKJQoGKQYKLQIGKQYKLQIOJQoKKQoOJQYKKQIOJQoKKQoOKQIOLQoKKQYOLQYKJQIOKQoKKQYKKQoKJQYOKQYKLQIOKQoKLQYOKQYKLQIOJQoGKQYKJQYGJQoGKQYKLQoGLQYGKQoGJQYKKQYGJQIKKQoGJQYKLQIKKQYGLQYKKQYGKQYGKQYKJQYOKQoKJQYOKQYKLQYOLQYOKQYKLQYOKQoKKQYKKQYOKQYOJQYKKQYKLQYKKQIKKQoKKQYKKQYKKQoKJQIKKQYKLQYKKQYKKQIKKQYKKQYKKQYKKQIKKQYKJQYGLQYGKQYKKQYKKQYGKQIKKQYGKQYOJQoKKQYOLQYKKQYOKQoKKQYKKQoKKQYKKQYKJQYKLQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKJQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKLQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKmIDpEAAAA0XRSTlMAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAiIyQlJycoKissLS4wMTQ1Njc4OTo7PDw+P0BCQ0RISUpLTE1OUFNUVVdYWFlaW15fYGFiY2ZnaGlqa2xtb3BxcnN0dnh5ent8fX5/gIGChIWIioyNjo+QkZOUlZaYmZqbnJ2eoKGio6WmqKmsra6vsLGztre4ubq7vL2+wMHDxMjJysvNzs/Q0dLU1tfY2dvc3t/g4eLj5ebn6Onq6+zt7u/w8vP09fb3+Pn6+/z9/vkVQXAAAAMaSURBVHhe5dXxV1N1GMfxz2ABbDgIAm5VDJOyVDIJLUMaVpBWUZUaGbmqoGpZRSiGiRWp6KoZ5AB0ZY50RImZQIlahKkMYXv/R90dBvET/rJfOr3Ouc8v99zPec59zvf56j+vYKlViSf7250X4Mr3O29Tgq08BdGB4DhcekEJ5YkQKFsgWZdtj9JpV+I8xPjLFqkrsEIqO8PHSpis36jWazcqjEsfJjkvRssVU37SdIOu4XCf5vEJPsnwJpnRNU9JmxhMk8l1gehIrq7hTFjzOD+Vf88629qKMJVNltInFeRexRQyJlNeqd1iGDlSzrIUIyXbyFfm3RYprcQRe7lqtWyGYbfc6dT0R2vmdOOkX3u55C1rP37ftiH+tDby4r/RBT0w8TyEkr+epB9XgPDmSYYWbrhCuFYaIyw3fDQAXTnSkh+ANofiHmWf9l+FY1I90FdQTetstO00o23novzVsJ7uB3/C5TkbjRwZ5JerwV4iRWq9HFbFMaK/d0TYqayRiQPuIxxS3Bu8JWU90/60tKi7vkhaznez0a/TbVOKj5CaOZh6fWG6/Lyv9B/ZLR1gw/S/fpbeVD3MCW1li6SvWDOn65tr99/uvWtBS0XDm4s1t+sOHpG0kpBKx/l77wOSnxLpcx6TXmXLTPQOKYOf9Q1dfr8/SJ2mFdCvl1Yl93DiHUZvXeLJbGSzYu5gVJ2slbSakOR8dxCq5adQ2oFLqsE9Ex3L4qQO0eOPeU5x56bypXp4onSEb5OkICX6lDat55TeoztNKQcJaakrz9KCb95oD69IKq+yKW4XPjknaS52V0TZqE2cTtXjcHSCRmUO88e+85hj3EP74i9p8pylw7lxgMDyyl6OV7ZejnjNMfatu87LxRbH0IS35gt2a4ZjmGpVBdKK3Wr6INk8jWWSGqbA55CKgjBRC6E9w78ydTg3ABS3AFV1QN0Y4Aa2pgEjWnQURj9L0ayK6R2ysEqxHUKzYnLvvyU+i9KM2JHJzE4vyZOyDcOwOsySajeLPc8sNvPJkFlyJd20wpqAzZeAfZ3oWybxd+P/3j+SG3uSBdf2VQAAAABJRU5ErkJggg==") no-repeat; background: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiCiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICB3aWR0aD0iNjgxLjk2MjUyIgogICBoZWlnaHQ9IjE4Ny41IgogICBpZD0ic3ZnMiIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhOCI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczYiPjxjbGlwUGF0aAogICAgICAgaWQ9ImNsaXBQYXRoMTgiPjxwYXRoCiAgICAgICAgIGQ9Ik0gMCwxNTAwIDAsMCBsIDU0NTUuNzQsMCAwLDE1MDAgTCAwLDE1MDAgeiIKICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgaWQ9InBhdGgyMCIgLz48L2NsaXBQYXRoPjwvZGVmcz48ZwogICAgIHRyYW5zZm9ybT0ibWF0cml4KDEuMjUsMCwwLC0xLjI1LDAsMTg3LjUpIgogICAgIGlkPSJnMTAiPjxnCiAgICAgICB0cmFuc2Zvcm09InNjYWxlKDAuMSwwLjEpIgogICAgICAgaWQ9ImcxMiI+PGcKICAgICAgICAgaWQ9ImcxNCI+PGcKICAgICAgICAgICBjbGlwLXBhdGg9InVybCgjY2xpcFBhdGgxOCkiCiAgICAgICAgICAgaWQ9ImcxNiI+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMTU0NCw1OTkuNDM0IGMgMC45MiwtNDAuMzUyIDI1LjY4LC04MS42MDIgNzEuNTMsLTgxLjYwMiAyNy41MSwwIDQ3LjY4LDEyLjgzMiA2MS40NCwzNS43NTQgMTIuODMsMjIuOTMgMTIuODMsNTYuODUyIDEyLjgzLDgyLjUyNyBsIDAsMzI5LjE4NCAtNzEuNTIsMCAwLDEwNC41NDMgMjY2LjgzLDAgMCwtMTA0LjU0MyAtNzAuNiwwIDAsLTM0NC43NyBjIDAsLTU4LjY5MSAtMy42OCwtMTA0LjUzMSAtNDQuOTMsLTE1Mi4yMTggLTM2LjY4LC00Mi4xOCAtOTYuMjgsLTY2LjAyIC0xNTMuMTQsLTY2LjAyIC0xMTcuMzcsMCAtMjA3LjI0LDc3Ljk0MSAtMjAyLjY0LDE5Ny4xNDUgbCAxMzAuMiwwIgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMjIiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDIzMDEuNCw2NjIuNjk1IGMgMCw4MC43MDMgLTY2Ljk0LDE0NS44MTMgLTE0Ny42MywxNDUuODEzIC04My40NCwwIC0xNDcuNjMsLTY4Ljc4MSAtMTQ3LjYzLC0xNTEuMzAxIDAsLTc5Ljc4NSA2Ni45NCwtMTQ1LjgwMSAxNDUuOCwtMTQ1LjgwMSA4NC4zNSwwIDE0OS40Niw2Ny44NTIgMTQ5LjQ2LDE1MS4yODkgeiBtIC0xLjgzLC0xODEuNTQ3IGMgLTM1Ljc3LC01NC4wOTcgLTkzLjUzLC03OC44NTkgLTE1Ny43MiwtNzguODU5IC0xNDAuMywwIC0yNTEuMjQsMTE2LjQ0OSAtMjUxLjI0LDI1NC45MTggMCwxNDIuMTI5IDExMy43LDI2MC40MSAyNTYuNzQsMjYwLjQxIDYzLjI3LDAgMTE4LjI5LC0yOS4zMzYgMTUyLjIyLC04Mi41MjMgbCAwLDY5LjY4NyAxNzUuMTQsMCAwLC0xMDQuNTI3IC02MS40NCwwIDAsLTI4MC41OTggNjEuNDQsMCAwLC0xMDQuNTI3IC0xNzUuMTQsMCAwLDY2LjAxOSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDI0IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSAyNjIyLjMzLDU1Ny4yNTggYyAzLjY3LC00NC4wMTYgMzMuMDEsLTczLjM0OCA3OC44NiwtNzMuMzQ4IDMzLjkzLDAgNjYuOTMsMjMuODI0IDY2LjkzLDYwLjUwNCAwLDQ4LjYwNiAtNDUuODQsNTYuODU2IC04My40NCw2Ni45NDEgLTg1LjI4LDIyLjAwNCAtMTc4LjgxLDQ4LjYwNiAtMTc4LjgxLDE1NS44NzkgMCw5My41MzYgNzguODYsMTQ3LjYzMyAxNjUuOTgsMTQ3LjYzMyA0NCwwIDgzLjQzLC05LjE3NiAxMTAuOTQsLTQ0LjAwOCBsIDAsMzMuOTIyIDgyLjUzLDAgMCwtMTMyLjk2NSAtMTA4LjIxLDAgYyAtMS44MywzNC44NTYgLTI4LjQyLDU3Ljc3NCAtNjMuMjYsNTcuNzc0IC0zMC4yNiwwIC02Mi4zNSwtMTcuNDIyIC02Mi4zNSwtNTEuMzQ4IDAsLTQ1Ljg0NyA0NC45MywtNTUuOTMgODAuNjksLTY0LjE4IDg4LjAyLC0yMC4xNzUgMTgyLjQ3LC00Ny42OTUgMTgyLjQ3LC0xNTcuNzM0IDAsLTk5LjAyNyAtODMuNDQsLTE1NC4wMzkgLTE3NS4xMywtMTU0LjAzOSAtNDkuNTMsMCAtOTQuNDYsMTUuNTgyIC0xMjYuNTUsNTMuMTggbCAwLC00MC4zNCAtODUuMjcsMCAwLDE0Mi4xMjkgMTE0LjYyLDAiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGgyNiIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMjk4OC4xOCw4MDAuMjU0IC02My4yNiwwIDAsMTA0LjUyNyAxNjUuMDUsMCAwLC03My4zNTUgYyAzMS4xOCw1MS4zNDcgNzguODYsODUuMjc3IDE0MS4yMSw4NS4yNzcgNjcuODUsMCAxMjQuNzEsLTQxLjI1OCAxNTIuMjEsLTEwMi42OTkgMjYuNiw2Mi4zNTEgOTIuNjIsMTAyLjY5OSAxNjAuNDcsMTAyLjY5OSA1My4xOSwwIDEwNS40NiwtMjIgMTQxLjIxLC02Mi4zNTEgMzguNTIsLTQ0LjkzOCAzOC41MiwtOTMuNTMyIDM4LjUyLC0xNDkuNDU3IGwgMCwtMTg1LjIzOSA2My4yNywwIDAsLTEwNC41MjcgLTIzOC40MiwwIDAsMTA0LjUyNyA2My4yOCwwIDAsMTU3LjcxNSBjIDAsMzIuMTAyIDAsNjAuNTI3IC0xNC42Nyw4OC45NTcgLTE4LjM0LDI2LjU4MiAtNDguNjEsNDAuMzQ0IC03OS43Nyw0MC4zNDQgLTMwLjI2LDAgLTYzLjI4LC0xMi44NDQgLTgyLjUzLC0zNi42NzIgLTIyLjkzLC0yOS4zNTUgLTIyLjkzLC01Ni44NjMgLTIyLjkzLC05Mi42MjkgbCAwLC0xNTcuNzE1IDYzLjI3LDAgMCwtMTA0LjUyNyAtMjM4LjQxLDAgMCwxMDQuNTI3IDYzLjI4LDAgMCwxNTAuMzgzIGMgMCwyOS4zNDggMCw2Ni4wMjMgLTE0LjY3LDkxLjY5OSAtMTUuNTksMjkuMzM2IC00Ny42OSw0NC45MzQgLTgwLjcsNDQuOTM0IC0zMS4xOCwwIC01Ny43NywtMTEuMDA4IC03Ny45NCwtMzUuNzc0IC0yNC43NywtMzAuMjUzIC0yNi42LC02Mi4zNDMgLTI2LjYsLTk5Ljk0MSBsIDAsLTE1MS4zMDEgNjMuMjcsMCAwLC0xMDQuNTI3IC0yMzguNCwwIDAsMTA0LjUyNyA2My4yNiwwIDAsMjgwLjU5OCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDI4IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSAzOTk4LjY2LDk1MS41NDcgLTExMS44NywwIDAsMTE4LjI5MyAxMTEuODcsMCAwLC0xMTguMjkzIHogbSAwLC00MzEuODkxIDYzLjI3LDAgMCwtMTA0LjUyNyAtMjM5LjMzLDAgMCwxMDQuNTI3IDY0LjE5LDAgMCwyODAuNTk4IC02My4yNywwIDAsMTA0LjUyNyAxNzUuMTQsMCAwLC0zODUuMTI1IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzAiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDQxNTkuMTIsODAwLjI1NCAtNjMuMjcsMCAwLDEwNC41MjcgMTc1LjE0LDAgMCwtNjkuNjg3IGMgMjkuMzUsNTQuMTAxIDg0LjM2LDgwLjY5OSAxNDQuODcsODAuNjk5IDUzLjE5LDAgMTA1LjQ1LC0yMi4wMTYgMTQxLjIyLC02MC41MjcgNDAuMzQsLTQ0LjkzNCA0MS4yNiwtODguMDMyIDQxLjI2LC0xNDMuOTU3IGwgMCwtMTkxLjY1MyA2My4yNywwIDAsLTEwNC41MjcgLTIzOC40LDAgMCwxMDQuNTI3IDYzLjI2LDAgMCwxNTguNjM3IGMgMCwzMC4yNjIgMCw2MS40MzQgLTE5LjI2LDg4LjAzNSAtMjAuMTcsMjYuNTgyIC01My4xOCwzOS40MTQgLTg2LjE5LDM5LjQxNCAtMzMuOTMsMCAtNjguNzcsLTEzLjc1IC04OC45NCwtNDEuMjUgLTIxLjA5LC0yNy41IC0yMS4wOSwtNjkuNjg3IC0yMS4wOSwtMTAyLjcwNyBsIDAsLTE0Mi4xMjkgNjMuMjYsMCAwLC0xMDQuNTI3IC0yMzguNCwwIDAsMTA0LjUyNyA2My4yNywwIDAsMjgwLjU5OCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDMyIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA1MDgyLjQ4LDcwMy45NjUgYyAtMTkuMjQsNzAuNjA1IC04MS42LDExNS41NDcgLTE1NC4wNCwxMTUuNTQ3IC02Ni4wNCwwIC0xMjkuMywtNTEuMzQ4IC0xNDMuMDUsLTExNS41NDcgbCAyOTcuMDksMCB6IG0gODUuMjcsLTE0NC44ODMgYyAtMzguNTEsLTkzLjUyMyAtMTI5LjI3LC0xNTYuNzkzIC0yMzEuMDUsLTE1Ni43OTMgLTE0My4wNywwIC0yNTcuNjgsMTExLjg3MSAtMjU3LjY4LDI1NS44MzYgMCwxNDQuODgzIDEwOS4xMiwyNjEuMzI4IDI1NC45MSwyNjEuMzI4IDY3Ljg3LDAgMTM1LjcyLC0zMC4yNTggMTgzLjM5LC03OC44NjMgNDguNjIsLTUxLjM0NCA2OC43OSwtMTEzLjY5NSA2OC43OSwtMTgzLjM4MyBsIC0zLjY3LC0zOS40MzQgLTM5Ni4xMywwIGMgMTQuNjcsLTY3Ljg2MyA3Ny4wMywtMTE3LjM2MyAxNDYuNzIsLTExNy4zNjMgNDguNTksMCA5MC43NiwxOC4zMjggMTE4LjI4LDU4LjY3MiBsIDExNi40NCwwIgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzQiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDY5MC44OTUsODUwLjcwMyA5MC43NSwwIDIyLjU0MywzMS4wMzUgMCwyNDMuMTIyIC0xMzUuODI5LDAgMCwtMjQzLjE0MSAyMi41MzYsLTMxLjAxNiIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDM2IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA2MzIuMzk1LDc0Mi4yNTggMjguMDM5LDg2LjMwNCAtMjIuNTUxLDMxLjA0IC0yMzEuMjIzLDc1LjEyOCAtNDEuOTc2LC0xMjkuMTgzIDIzMS4yNTcsLTc1LjEzNyAzNi40NTQsMTEuODQ4IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzgiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDcxNy40NDksNjUzLjEwNSAtNzMuNDEsNTMuMzYgLTM2LjQ4OCwtMTEuODc1IC0xNDIuOTAzLC0xOTYuNjkyIDEwOS44ODMsLTc5LjgyOCAxNDIuOTE4LDE5Ni43MDMgMCwzOC4zMzIiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGg0MCIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gODI4LjUyLDcwNi40NjUgLTczLjQyNiwtNTMuMzQgMC4wMTEsLTM4LjM1OSBMIDg5OC4wMDQsNDE4LjA3IDEwMDcuOSw0OTcuODk4IDg2NC45NzMsNjk0LjYwOSA4MjguNTIsNzA2LjQ2NSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDQyIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA4MTIuMDg2LDgyOC41ODYgMjguMDU1LC04Ni4zMiAzNi40ODQsLTExLjgzNiAyMzEuMjI1LDc1LjExNyAtNDEuOTcsMTI5LjE4MyAtMjMxLjIzOSwtNzUuMTQgLTIyLjU1NSwtMzEuMDA0IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNDQiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDczNi4zMDEsMTMzNS44OCBjIC0zMjMuMDQ3LDAgLTU4NS44NzUsLTI2Mi43OCAtNTg1Ljg3NSwtNTg1Ljc4MiAwLC0zMjMuMTE4IDI2Mi44MjgsLTU4NS45NzcgNTg1Ljg3NSwtNTg1Ljk3NyAzMjMuMDE5LDAgNTg1LjgwOSwyNjIuODU5IDU4NS44MDksNTg1Ljk3NyAwLDMyMy4wMDIgLTI2Mi43OSw1ODUuNzgyIC01ODUuODA5LDU4NS43ODIgbCAwLDAgeiBtIDAsLTExOC42MSBjIDI1Ny45NzIsMCA0NjcuMTg5LC0yMDkuMTMgNDY3LjE4OSwtNDY3LjE3MiAwLC0yNTguMTI5IC0yMDkuMjE3LC00NjcuMzQ4IC00NjcuMTg5LC00NjcuMzQ4IC0yNTguMDc0LDAgLTQ2Ny4yNTQsMjA5LjIxOSAtNDY3LjI1NCw0NjcuMzQ4IDAsMjU4LjA0MiAyMDkuMTgsNDY3LjE3MiA0NjcuMjU0LDQ2Ny4xNzIiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGg0NiIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMTA5MS4xMyw2MTkuODgzIC0xNzUuNzcxLDU3LjEyMSAxMS42MjksMzUuODA4IDE3NS43NjIsLTU3LjEyMSAtMTEuNjIsLTM1LjgwOCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDQ4IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0iTSA4NjYuOTU3LDkwMi4wNzQgODM2LjUsOTI0LjE5OSA5NDUuMTIxLDEwNzMuNzMgOTc1LjU4NiwxMDUxLjYxIDg2Ni45NTcsOTAyLjA3NCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDUwIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0iTSA2MDcuNDY1LDkwMy40NDUgNDk4Ljg1NSwxMDUyLjk3IDUyOS4zMiwxMDc1LjEgNjM3LjkzLDkyNS41NjYgNjA3LjQ2NSw5MDMuNDQ1IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTIiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDM4MC42ODgsNjIyLjEyOSAtMTEuNjI2LDM1LjgwMSAxNzUuNzU4LDU3LjA5IDExLjYyMSwtMzUuODAxIC0xNzUuNzUzLC01Ny4wOSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDU0IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA3MTYuMjg5LDM3Ni41OSAzNy42NDA2LDAgMCwxODQuODE2IC0zNy42NDA2LDAgMCwtMTg0LjgxNiB6IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTYiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=") no-repeat, none; -moz-background-size: 100%; -o-background-size: 100%; -webkit-background-size: 100%; background-size: 100%; display: block; float: left; width: 90px; height: 25px; } .jasmine_html-reporter .jasmine-banner .jasmine-version { margin-left: 14px; position: relative; top: 6px; } .jasmine_html-reporter #jasmine_content { position: fixed; right: 100%; } .jasmine_html-reporter .jasmine-version { color: #aaa; } .jasmine_html-reporter .jasmine-banner { margin-top: 14px; } .jasmine_html-reporter .jasmine-duration { color: #fff; float: right; line-height: 28px; padding-right: 9px; } .jasmine_html-reporter .jasmine-symbol-summary { overflow: hidden; margin: 14px 0; } .jasmine_html-reporter .jasmine-symbol-summary li { display: inline-block; height: 10px; width: 14px; font-size: 16px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-passed { font-size: 14px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-passed:before { color: #007069; content: "•"; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-failed { line-height: 9px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-failed:before { color: #ca3a11; content: "×"; font-weight: bold; margin-left: -1px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-excluded { font-size: 14px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-excluded:before { color: #bababa; content: "•"; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-excluded-no-display { font-size: 14px; display: none; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-pending { line-height: 17px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-pending:before { color: #ba9d37; content: "*"; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-empty { font-size: 14px; } .jasmine_html-reporter .jasmine-symbol-summary li.jasmine-empty:before { color: #ba9d37; content: "•"; } .jasmine_html-reporter .jasmine-run-options { float: right; margin-right: 5px; border: 1px solid #8a4182; color: #8a4182; position: relative; line-height: 20px; } .jasmine_html-reporter .jasmine-run-options .jasmine-trigger { cursor: pointer; padding: 8px 16px; } .jasmine_html-reporter .jasmine-run-options .jasmine-payload { position: absolute; display: none; right: -1px; border: 1px solid #8a4182; background-color: #eee; white-space: nowrap; padding: 4px 8px; } .jasmine_html-reporter .jasmine-run-options .jasmine-payload.jasmine-open { display: block; } .jasmine_html-reporter .jasmine-bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } .jasmine_html-reporter .jasmine-bar.jasmine-failed, .jasmine_html-reporter .jasmine-bar.jasmine-errored { background-color: #ca3a11; border-bottom: 1px solid #eee; } .jasmine_html-reporter .jasmine-bar.jasmine-passed { background-color: #007069; } .jasmine_html-reporter .jasmine-bar.jasmine-incomplete { background-color: #bababa; } .jasmine_html-reporter .jasmine-bar.jasmine-skipped { background-color: #bababa; } .jasmine_html-reporter .jasmine-bar.jasmine-warning { background-color: #ba9d37; color: #333; } .jasmine_html-reporter .jasmine-bar.jasmine-menu { background-color: #fff; color: #aaa; } .jasmine_html-reporter .jasmine-bar.jasmine-menu a { color: #333; } .jasmine_html-reporter .jasmine-bar a { color: white; } .jasmine_html-reporter.jasmine-spec-list .jasmine-bar.jasmine-menu.jasmine-failure-list, .jasmine_html-reporter.jasmine-spec-list .jasmine-results .jasmine-failures { display: none; } .jasmine_html-reporter.jasmine-failure-list .jasmine-bar.jasmine-menu.jasmine-spec-list, .jasmine_html-reporter.jasmine-failure-list .jasmine-summary { display: none; } .jasmine_html-reporter .jasmine-results { margin-top: 14px; } .jasmine_html-reporter .jasmine-summary { margin-top: 14px; } .jasmine_html-reporter .jasmine-summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; } .jasmine_html-reporter .jasmine-summary ul.jasmine-suite { margin-top: 7px; margin-bottom: 7px; } .jasmine_html-reporter .jasmine-summary li.jasmine-passed a { color: #007069; } .jasmine_html-reporter .jasmine-summary li.jasmine-failed a { color: #ca3a11; } .jasmine_html-reporter .jasmine-summary li.jasmine-empty a { color: #ba9d37; } .jasmine_html-reporter .jasmine-summary li.jasmine-pending a { color: #ba9d37; } .jasmine_html-reporter .jasmine-summary li.jasmine-excluded a { color: #bababa; } .jasmine_html-reporter .jasmine-specs li.jasmine-passed a:before { content: "• "; } .jasmine_html-reporter .jasmine-specs li.jasmine-failed a:before { content: "× "; } .jasmine_html-reporter .jasmine-specs li.jasmine-empty a:before { content: "* "; } .jasmine_html-reporter .jasmine-specs li.jasmine-pending a:before { content: "• "; } .jasmine_html-reporter .jasmine-specs li.jasmine-excluded a:before { content: "• "; } .jasmine_html-reporter .jasmine-description + .jasmine-suite { margin-top: 0; } .jasmine_html-reporter .jasmine-suite { margin-top: 14px; } .jasmine_html-reporter .jasmine-suite a { color: #333; } .jasmine_html-reporter .jasmine-failures .jasmine-spec-detail { margin-bottom: 28px; } .jasmine_html-reporter .jasmine-failures .jasmine-spec-detail .jasmine-description { background-color: #ca3a11; color: white; } .jasmine_html-reporter .jasmine-failures .jasmine-spec-detail .jasmine-description a { color: white; } .jasmine_html-reporter .jasmine-result-message { padding-top: 14px; color: #333; white-space: pre-wrap; } .jasmine_html-reporter .jasmine-result-message span.jasmine-result { display: block; } .jasmine_html-reporter .jasmine-stack-trace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666; border: 1px solid #ddd; background: white; white-space: pre; } ================================================ FILE: lib/jasmine-3.4.0/jasmine.js ================================================ /* Copyright (c) 2008-2019 Pivotal Labs 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. */ var getJasmineRequireObj = (function (jasmineGlobal) { /* globals exports, global, module, window */ var jasmineRequire; if (typeof module !== 'undefined' && module.exports && typeof exports !== 'undefined') { if (typeof global !== 'undefined') { jasmineGlobal = global; } else { jasmineGlobal = {}; } jasmineRequire = exports; } else { if (typeof window !== 'undefined' && typeof window.toString === 'function' && window.toString() === '[object GjsGlobal]') { jasmineGlobal = window; } jasmineRequire = jasmineGlobal.jasmineRequire = {}; } function getJasmineRequire() { return jasmineRequire; } getJasmineRequire().core = function(jRequire) { var j$ = {}; jRequire.base(j$, jasmineGlobal); j$.util = jRequire.util(j$); j$.errors = jRequire.errors(); j$.formatErrorMsg = jRequire.formatErrorMsg(); j$.Any = jRequire.Any(j$); j$.Anything = jRequire.Anything(j$); j$.CallTracker = jRequire.CallTracker(j$); j$.MockDate = jRequire.MockDate(); j$.getClearStack = jRequire.clearStack(j$); j$.Clock = jRequire.Clock(); j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(j$); j$.Env = jRequire.Env(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); j$.Expector = jRequire.Expector(j$); j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.noopTimer = jRequire.noopTimer(); j$.JsApiReporter = jRequire.JsApiReporter(j$); j$.matchersUtil = jRequire.matchersUtil(j$); j$.ObjectContaining = jRequire.ObjectContaining(j$); j$.ArrayContaining = jRequire.ArrayContaining(j$); j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); j$.pp = jRequire.pp(j$); j$.QueueRunner = jRequire.QueueRunner(j$); j$.ReportDispatcher = jRequire.ReportDispatcher(j$); j$.Spec = jRequire.Spec(j$); j$.Spy = jRequire.Spy(j$); j$.SpyFactory = jRequire.SpyFactory(j$); j$.SpyRegistry = jRequire.SpyRegistry(j$); j$.SpyStrategy = jRequire.SpyStrategy(j$); j$.StringMatching = jRequire.StringMatching(j$); j$.UserContext = jRequire.UserContext(j$); j$.Suite = jRequire.Suite(j$); j$.Timer = jRequire.Timer(); j$.TreeProcessor = jRequire.TreeProcessor(); j$.version = jRequire.version(); j$.Order = jRequire.Order(); j$.DiffBuilder = jRequire.DiffBuilder(j$); j$.NullDiffBuilder = jRequire.NullDiffBuilder(j$); j$.ObjectPath = jRequire.ObjectPath(j$); j$.GlobalErrors = jRequire.GlobalErrors(j$); j$.Truthy = jRequire.Truthy(j$); j$.Falsy = jRequire.Falsy(j$); j$.Empty = jRequire.Empty(j$); j$.NotEmpty = jRequire.NotEmpty(j$); j$.matchers = jRequire.requireMatchers(jRequire, j$); j$.asyncMatchers = jRequire.requireAsyncMatchers(jRequire, j$); return j$; }; return getJasmineRequire; })(this); getJasmineRequireObj().requireMatchers = function(jRequire, j$) { var availableMatchers = [ 'nothing', 'toBe', 'toBeCloseTo', 'toBeDefined', 'toBeFalsy', 'toBeGreaterThan', 'toBeGreaterThanOrEqual', 'toBeLessThan', 'toBeLessThanOrEqual', 'toBeNaN', 'toBeNegativeInfinity', 'toBeNull', 'toBePositiveInfinity', 'toBeTruthy', 'toBeUndefined', 'toContain', 'toEqual', 'toHaveBeenCalled', 'toHaveBeenCalledBefore', 'toHaveBeenCalledTimes', 'toHaveBeenCalledWith', 'toHaveClass', 'toMatch', 'toThrow', 'toThrowError', 'toThrowMatching', ], matchers = {}; for (var i = 0; i < availableMatchers.length; i++) { var name = availableMatchers[i]; matchers[name] = jRequire[name](j$); } return matchers; }; getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.unimplementedMethod_ = function() { throw new Error('unimplemented method'); }; /** * Maximum object depth the pretty printer will print to. * Set this to a lower value to speed up pretty printing if you have large objects. * @name jasmine.MAX_PRETTY_PRINT_DEPTH */ j$.MAX_PRETTY_PRINT_DEPTH = 8; /** * Maximum number of array elements to display when pretty printing objects. * This will also limit the number of keys and values displayed for an object. * Elements past this number will be ellipised. * @name jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH */ j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 50; /** * Maximum number of characters to display when pretty printing objects. * Characters past this number will be ellipised. * @name jasmine.MAX_PRETTY_PRINT_CHARS */ j$.MAX_PRETTY_PRINT_CHARS = 1000; /** * Default number of milliseconds Jasmine will wait for an asynchronous spec to complete. * @name jasmine.DEFAULT_TIMEOUT_INTERVAL */ j$.DEFAULT_TIMEOUT_INTERVAL = 5000; j$.getGlobal = function() { return jasmineGlobal; }; /** * Get the currently booted Jasmine Environment. * * @name jasmine.getEnv * @function * @return {Env} */ j$.getEnv = function(options) { var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); //jasmine. singletons in here (setTimeout blah blah). return env; }; j$.isArray_ = function(value) { return j$.isA_('Array', value); }; j$.isObject_ = function(value) { return !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value); }; j$.isString_ = function(value) { return j$.isA_('String', value); }; j$.isNumber_ = function(value) { return j$.isA_('Number', value); }; j$.isFunction_ = function(value) { return j$.isA_('Function', value); }; j$.isAsyncFunction_ = function(value) { return j$.isA_('AsyncFunction', value); }; j$.isTypedArray_ = function(value) { return j$.isA_('Float32Array', value) || j$.isA_('Float64Array', value) || j$.isA_('Int16Array', value) || j$.isA_('Int32Array', value) || j$.isA_('Int8Array', value) || j$.isA_('Uint16Array', value) || j$.isA_('Uint32Array', value) || j$.isA_('Uint8Array', value) || j$.isA_('Uint8ClampedArray', value); }; j$.isA_ = function(typeName, value) { return j$.getType_(value) === '[object ' + typeName + ']'; }; j$.isError_ = function(value) { if (value instanceof Error) { return true; } if (value && value.constructor && value.constructor.constructor) { var valueGlobal = value.constructor.constructor('return this'); if (j$.isFunction_(valueGlobal)) { valueGlobal = valueGlobal(); } if (valueGlobal.Error && value instanceof valueGlobal.Error) { return true; } } return false; }; j$.getType_ = function(value) { return Object.prototype.toString.apply(value); }; j$.isDomNode = function(obj) { // Node is a function, because constructors return typeof jasmineGlobal.Node !== 'undefined' ? obj instanceof jasmineGlobal.Node : obj !== null && typeof obj === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'; // return obj.nodeType > 0; }; j$.isMap = function(obj) { return typeof jasmineGlobal.Map !== 'undefined' && obj.constructor === jasmineGlobal.Map; }; j$.isSet = function(obj) { return typeof jasmineGlobal.Set !== 'undefined' && obj.constructor === jasmineGlobal.Set; }; j$.isPromise = function(obj) { return typeof jasmineGlobal.Promise !== 'undefined' && !!obj && obj.constructor === jasmineGlobal.Promise; }; j$.isPromiseLike = function(obj) { return !!obj && j$.isFunction_(obj.then); }; j$.fnNameFor = function(func) { if (func.name) { return func.name; } var matches = func.toString().match(/^\s*function\s*(\w+)\s*\(/) || func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); return matches ? matches[1] : ''; }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared is an instance of the specified class/constructor. * @name jasmine.any * @function * @param {Constructor} clazz - The constructor to check against. */ j$.any = function(clazz) { return new j$.Any(clazz); }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared is not `null` and not `undefined`. * @name jasmine.anything * @function */ j$.anything = function() { return new j$.Anything(); }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared is `true` or anything truthy. * @name jasmine.truthy * @function */ j$.truthy = function() {return new j$.Truthy();}; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared is `null`, `undefined`, `0`, `false` or anything falsey. * @name jasmine.falsy * @function */ j$.falsy = function() {return new j$.Falsy();}; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared is empty. * @name jasmine.empty * @function */ j$.empty = function() {return new j$.Empty();}; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared is not empty. * @name jasmine.notEmpty * @function */ j$.notEmpty = function() {return new j$.NotEmpty();}; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value being compared contains at least the keys and values. * @name jasmine.objectContaining * @function * @param {Object} sample - The subset of properties that _must_ be in the actual. */ j$.objectContaining = function(sample) { return new j$.ObjectContaining(sample); }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value is a `String` that matches the `RegExp` or `String`. * @name jasmine.stringMatching * @function * @param {RegExp|String} expected */ j$.stringMatching = function(expected) { return new j$.StringMatching(expected); }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value is an `Array` that contains at least the elements in the sample. * @name jasmine.arrayContaining * @function * @param {Array} sample */ j$.arrayContaining = function(sample) { return new j$.ArrayContaining(sample); }; /** * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), * that will succeed if the actual value is an `Array` that contains all of the elements in the sample in any order. * @name jasmine.arrayWithExactContents * @function * @param {Array} sample */ j$.arrayWithExactContents = function(sample) { return new j$.ArrayWithExactContents(sample); }; j$.isSpy = function(putativeSpy) { if (!putativeSpy) { return false; } return putativeSpy.and instanceof j$.SpyStrategy && putativeSpy.calls instanceof j$.CallTracker; }; }; getJasmineRequireObj().util = function(j$) { var util = {}; util.inherit = function(childClass, parentClass) { var Subclass = function() { }; Subclass.prototype = parentClass.prototype; childClass.prototype = new Subclass(); }; util.htmlEscape = function(str) { if (!str) { return str; } return str.replace(/&/g, '&') .replace(//g, '>'); }; util.argsToArray = function(args) { var arrayOfArgs = []; for (var i = 0; i < args.length; i++) { arrayOfArgs.push(args[i]); } return arrayOfArgs; }; util.isUndefined = function(obj) { return obj === void 0; }; util.arrayContains = function(array, search) { var i = array.length; while (i--) { if (array[i] === search) { return true; } } return false; }; util.clone = function(obj) { if (Object.prototype.toString.apply(obj) === '[object Array]') { return obj.slice(); } var cloned = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { cloned[prop] = obj[prop]; } } return cloned; }; util.cloneArgs = function(args) { var clonedArgs = []; var argsAsArray = j$.util.argsToArray(args); for(var i = 0; i < argsAsArray.length; i++) { var str = Object.prototype.toString.apply(argsAsArray[i]), primitives = /^\[object (Boolean|String|RegExp|Number)/; // All falsey values are either primitives, `null`, or `undefined. if (!argsAsArray[i] || str.match(primitives)) { clonedArgs.push(argsAsArray[i]); } else { clonedArgs.push(j$.util.clone(argsAsArray[i])); } } return clonedArgs; }; util.getPropertyDescriptor = function(obj, methodName) { var descriptor, proto = obj; do { descriptor = Object.getOwnPropertyDescriptor(proto, methodName); proto = Object.getPrototypeOf(proto); } while (!descriptor && proto); return descriptor; }; util.objectDifference = function(obj, toRemove) { var diff = {}; for (var key in obj) { if (util.has(obj, key) && !util.has(toRemove, key)) { diff[key] = obj[key]; } } return diff; }; util.has = function(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; function anyMatch(pattern, lines) { var i; for (i = 0; i < lines.length; i++) { if (lines[i].match(pattern)) { return true; } } return false; } util.errorWithStack = function errorWithStack () { // Don't throw and catch if we don't have to, because it makes it harder // for users to debug their code with exception breakpoints. var error = new Error(); if (error.stack) { return error; } // But some browsers (e.g. Phantom) only provide a stack trace if we throw. try { throw new Error(); } catch (e) { return e; } }; function callerFile() { var trace = new j$.StackTrace(util.errorWithStack()); return trace.frames[2].file; } util.jasmineFile = (function() { var result; return function() { var trace; if (!result) { result = callerFile(); } return result; }; }()); return util; }; getJasmineRequireObj().Spec = function(j$) { function Spec(attrs) { this.expectationFactory = attrs.expectationFactory; this.asyncExpectationFactory = attrs.asyncExpectationFactory; this.resultCallback = attrs.resultCallback || function() {}; this.id = attrs.id; this.description = attrs.description || ''; this.queueableFn = attrs.queueableFn; this.beforeAndAfterFns = attrs.beforeAndAfterFns || function() { return {befores: [], afters: []}; }; this.userContext = attrs.userContext || function() { return {}; }; this.onStart = attrs.onStart || function() {}; this.getSpecName = attrs.getSpecName || function() { return ''; }; this.expectationResultFactory = attrs.expectationResultFactory || function() { }; this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.timer = attrs.timer || j$.noopTimer; if (!this.queueableFn.fn) { this.pend(); } /** * @typedef SpecResult * @property {Int} id - The unique id of this spec. * @property {String} description - The description passed to the {@link it} that created this spec. * @property {String} fullName - The full description including all ancestors of this spec. * @property {Expectation[]} failedExpectations - The list of expectations that failed during execution of this spec. * @property {Expectation[]} passedExpectations - The list of expectations that passed during execution of this spec. * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred during execution this spec. * @property {String} pendingReason - If the spec is {@link pending}, this will be the reason. * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. */ this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], passedExpectations: [], deprecationWarnings: [], pendingReason: '', duration: null, }; } Spec.prototype.addExpectationResult = function(passed, data, isError) { var expectationResult = this.expectationResultFactory(data); if (passed) { this.result.passedExpectations.push(expectationResult); } else { this.result.failedExpectations.push(expectationResult); if (this.throwOnExpectationFailure && !isError) { throw new j$.errors.ExpectationFailed(); } } }; Spec.prototype.expect = function(actual) { return this.expectationFactory(actual, this); }; Spec.prototype.expectAsync = function(actual) { return this.asyncExpectationFactory(actual, this); }; Spec.prototype.execute = function(onComplete, excluded) { var self = this; var onStart = { fn: function(done) { self.timer.start(); self.onStart(self, done); } }; var complete = { fn: function(done) { self.queueableFn.fn = null; self.result.status = self.status(excluded); self.resultCallback(self.result, done); } }; var fns = this.beforeAndAfterFns(); var regularFns = fns.befores.concat(this.queueableFn); var runnerConfig = { isLeaf: true, queueableFns: regularFns, cleanupFns: fns.afters, onException: function () { self.onException.apply(self, arguments); }, onComplete: function() { self.result.duration = self.timer.elapsed(); onComplete(self.result.status === 'failed' && new j$.StopExecutionError('spec failed')); }, userContext: this.userContext() }; if (this.markedPending || excluded === true) { runnerConfig.queueableFns = []; runnerConfig.cleanupFns = []; } runnerConfig.queueableFns.unshift(onStart); runnerConfig.cleanupFns.push(complete); this.queueRunnerFactory(runnerConfig); }; Spec.prototype.onException = function onException(e) { if (Spec.isPendingSpecException(e)) { this.pend(extractCustomPendingMessage(e)); return; } if (e instanceof j$.errors.ExpectationFailed) { return; } this.addExpectationResult(false, { matcherName: '', passed: false, expected: '', actual: '', error: e }, true); }; Spec.prototype.pend = function(message) { this.markedPending = true; if (message) { this.result.pendingReason = message; } }; Spec.prototype.getResult = function() { this.result.status = this.status(); return this.result; }; Spec.prototype.status = function(excluded) { if (excluded === true) { return 'excluded'; } if (this.markedPending) { return 'pending'; } if (this.result.failedExpectations.length > 0) { return 'failed'; } else { return 'passed'; } }; Spec.prototype.getFullName = function() { return this.getSpecName(this); }; Spec.prototype.addDeprecationWarning = function(deprecation) { if (typeof deprecation === 'string') { deprecation = { message: deprecation }; } this.result.deprecationWarnings.push(this.expectationResultFactory(deprecation)); }; var extractCustomPendingMessage = function(e) { var fullMessage = e.toString(), boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length; return fullMessage.substr(boilerplateEnd); }; Spec.pendingSpecExceptionMessage = '=> marked Pending'; Spec.isPendingSpecException = function(e) { return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1); }; return Spec; }; if (typeof window == void 0 && typeof exports == 'object') { /* globals exports */ exports.Spec = jasmineRequire.Spec; } /*jshint bitwise: false*/ getJasmineRequireObj().Order = function() { function Order(options) { this.random = 'random' in options ? options.random : true; var seed = this.seed = options.seed || generateSeed(); this.sort = this.random ? randomOrder : naturalOrder; function naturalOrder(items) { return items; } function randomOrder(items) { var copy = items.slice(); copy.sort(function(a, b) { return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id); }); return copy; } function generateSeed() { return String(Math.random()).slice(-5); } // Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function // used to get a different output when the key changes slightly. // We use your return to sort the children randomly in a consistent way when // used in conjunction with a seed function jenkinsHash(key) { var hash, i; for(hash = i = 0; i < key.length; ++i) { hash += key.charCodeAt(i); hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } } return Order; }; getJasmineRequireObj().Env = function(j$) { /** * _Note:_ Do not construct this directly, Jasmine will make one during booting. * @name Env * @classdesc The Jasmine environment * @constructor */ function Env(options) { options = options || {}; var self = this; var global = options.global || j$.getGlobal(); var totalSpecsDefined = 0; var realSetTimeout = global.setTimeout; var realClearTimeout = global.clearTimeout; var clearStack = j$.getClearStack(global); this.clock = new j$.Clock(global, function () { return new j$.DelayedFunctionScheduler(); }, new j$.MockDate(global)); var runnableResources = {}; var currentSpec = null; var currentlyExecutingSuites = []; var currentDeclarationSuite = null; var hasFailures = false; /** * This represents the available options to configure Jasmine. * Options that are not provided will use their default values * @interface Configuration */ var config = { /** * Whether to randomize spec execution order * @name Configuration#random * @type Boolean * @default true */ random: true, /** * Seed to use as the basis of randomization. * Null causes the seed to be determined randomly at the start of execution. * @name Configuration#seed * @type function * @default null */ seed: null, /** * Whether to stop execution of the suite after the first spec failure * @name Configuration#failFast * @type Boolean * @default false */ failFast: false, /** * Whether to cause specs to only have one expectation failure. * @name Configuration#oneFailurePerSpec * @type Boolean * @default false */ oneFailurePerSpec: false, /** * Function to use to filter specs * @name Configuration#specFilter * @type function * @default true */ specFilter: function() { return true; }, /** * Whether or not reporters should hide disabled specs from their output. * Currently only supported by Jasmine's HTMLReporter * @name Configuration#hideDisabled * @type Boolean * @default false */ hideDisabled: false }; var currentSuite = function() { return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; }; var currentRunnable = function() { return currentSpec || currentSuite(); }; var globalErrors = null; var installGlobalErrors = function() { if (globalErrors) { return; } globalErrors = new j$.GlobalErrors(); globalErrors.install(); }; if (!options.suppressLoadErrors) { installGlobalErrors(); globalErrors.pushListener(function(message, filename, lineno, colNo, err) { topSuite.result.failedExpectations.push({ passed: false, globalErrorType: 'load', message: message, stack: err && err.stack, filename: filename, lineno: lineno }); }); } /** * Configure your jasmine environment * @name Env#configure * @argument {Configuration} configuration * @function */ this.configure = function(configuration) { if (configuration.specFilter) { config.specFilter = configuration.specFilter; } if (configuration.hasOwnProperty('random')) { config.random = !!configuration.random; } if (configuration.hasOwnProperty('seed')) { config.seed = configuration.seed; } if (configuration.hasOwnProperty('failFast')) { config.failFast = configuration.failFast; } if (configuration.hasOwnProperty('oneFailurePerSpec')) { config.oneFailurePerSpec = configuration.oneFailurePerSpec; } if (configuration.hasOwnProperty('hideDisabled')) { config.hideDisabled = configuration.hideDisabled; } }; /** * Get the current configuration for your jasmine environment * @name Env#configuration * @function * @returns {Configuration} */ this.configuration = function() { var result = {}; for (var property in config) { result[property] = config[property]; } return result; }; Object.defineProperty(this, 'specFilter', { get: function() { self.deprecated('Getting specFilter directly from Env is deprecated, please check the specFilter option from `configuration`'); return config.specFilter; }, set: function(val) { self.deprecated('Setting specFilter directly on Env is deprecated, please use the specFilter option in `configure`'); config.specFilter = val; } }); this.addSpyStrategy = function(name, fn) { if(!currentRunnable()) { throw new Error('Custom spy strategies must be added in a before function or a spec'); } runnableResources[currentRunnable().id].customSpyStrategies[name] = fn; }; this.addCustomEqualityTester = function(tester) { if(!currentRunnable()) { throw new Error('Custom Equalities must be added in a before function or a spec'); } runnableResources[currentRunnable().id].customEqualityTesters.push(tester); }; this.addMatchers = function(matchersToAdd) { if(!currentRunnable()) { throw new Error('Matchers must be added in a before function or a spec'); } var customMatchers = runnableResources[currentRunnable().id].customMatchers; for (var matcherName in matchersToAdd) { customMatchers[matcherName] = matchersToAdd[matcherName]; } }; j$.Expectation.addCoreMatchers(j$.matchers); j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { return 'spec' + nextSpecId++; }; var nextSuiteId = 0; var getNextSuiteId = function() { return 'suite' + nextSuiteId++; }; var expectationFactory = function(actual, spec) { return j$.Expectation.factory({ util: j$.matchersUtil, customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customMatchers: runnableResources[spec.id].customMatchers, actual: actual, addExpectationResult: addExpectationResult }); function addExpectationResult(passed, result) { return spec.addExpectationResult(passed, result); } }; var asyncExpectationFactory = function(actual, spec) { return j$.Expectation.asyncFactory({ util: j$.matchersUtil, customEqualityTesters: runnableResources[spec.id].customEqualityTesters, actual: actual, addExpectationResult: addExpectationResult }); function addExpectationResult(passed, result) { return spec.addExpectationResult(passed, result); } }; var defaultResourcesForRunnable = function(id, parentRunnableId) { var resources = {spies: [], customEqualityTesters: [], customMatchers: {}, customSpyStrategies: {}}; if(runnableResources[parentRunnableId]){ resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters); resources.customMatchers = j$.util.clone(runnableResources[parentRunnableId].customMatchers); } runnableResources[id] = resources; }; var clearResourcesForRunnable = function(id) { spyRegistry.clearSpies(); delete runnableResources[id]; }; var beforeAndAfterFns = function(suite) { return function() { var befores = [], afters = []; while(suite) { befores = befores.concat(suite.beforeFns); afters = afters.concat(suite.afterFns); suite = suite.parentSuite; } return { befores: befores.reverse(), afters: afters }; }; }; var getSpecName = function(spec, suite) { var fullName = [spec.description], suiteFullName = suite.getFullName(); if (suiteFullName !== '') { fullName.unshift(suiteFullName); } return fullName.join(' '); }; // TODO: we may just be able to pass in the fn instead of wrapping here var buildExpectationResult = j$.buildExpectationResult, exceptionFormatter = new j$.ExceptionFormatter(), expectationResultFactory = function(attrs) { attrs.messageFormatter = exceptionFormatter.message; attrs.stackFormatter = exceptionFormatter.stack; return buildExpectationResult(attrs); }; var maximumSpecCallbackDepth = 20; var currentSpecCallbackDepth = 0; /** * Sets whether Jasmine should throw an Error when an expectation fails. * This causes a spec to only have one expectation failure. * @name Env#throwOnExpectationFailure * @function * @param {Boolean} value Whether to throw when a expectation fails * @deprecated Use the `oneFailurePerSpec` option with {@link Env#configure} */ this.throwOnExpectationFailure = function(value) { this.deprecated('Setting throwOnExpectationFailure directly on Env is deprecated, please use the oneFailurePerSpec option in `configure`'); this.configure({oneFailurePerSpec: !!value}); }; this.throwingExpectationFailures = function() { this.deprecated('Getting throwingExpectationFailures directly from Env is deprecated, please check the oneFailurePerSpec option from `configuration`'); return config.oneFailurePerSpec; }; /** * Set whether to stop suite execution when a spec fails * @name Env#stopOnSpecFailure * @function * @param {Boolean} value Whether to stop suite execution when a spec fails * @deprecated Use the `failFast` option with {@link Env#configure} */ this.stopOnSpecFailure = function(value) { this.deprecated('Setting stopOnSpecFailure directly is deprecated, please use the failFast option in `configure`'); this.configure({failFast: !!value}); }; this.stoppingOnSpecFailure = function() { this.deprecated('Getting stoppingOnSpecFailure directly from Env is deprecated, please check the failFast option from `configuration`'); return config.failFast; }; /** * Set whether to randomize test execution order * @name Env#randomizeTests * @function * @param {Boolean} value Whether to randomize execution order * @deprecated Use the `random` option with {@link Env#configure} */ this.randomizeTests = function(value) { this.deprecated('Setting randomizeTests directly is deprecated, please use the random option in `configure`'); config.random = !!value; }; this.randomTests = function() { this.deprecated('Getting randomTests directly from Env is deprecated, please check the random option from `configuration`'); return config.random; }; /** * Set the random number seed for spec randomization * @name Env#seed * @function * @param {Number} value The seed value * @deprecated Use the `seed` option with {@link Env#configure} */ this.seed = function(value) { this.deprecated('Setting seed directly is deprecated, please use the seed option in `configure`'); if (value) { config.seed = value; } return config.seed; }; this.hidingDisabled = function(value) { this.deprecated('Getting hidingDisabled directly from Env is deprecated, please check the hideDisabled option from `configuration`'); return config.hideDisabled; }; /** * @name Env#hideDisabled * @function */ this.hideDisabled = function(value) { this.deprecated('Setting hideDisabled directly is deprecated, please use the hideDisabled option in `configure`'); config.hideDisabled = !!value; }; this.deprecated = function(deprecation) { var runnable = currentRunnable() || topSuite; runnable.addDeprecationWarning(deprecation); if(typeof console !== 'undefined' && typeof console.error === 'function') { console.error('DEPRECATION:', deprecation); } }; var queueRunnerFactory = function(options, args) { var failFast = false; if (options.isLeaf) { failFast = config.oneFailurePerSpec; } else if (!options.isReporter) { failFast = config.failFast; } options.clearStack = options.clearStack || clearStack; options.timeout = {setTimeout: realSetTimeout, clearTimeout: realClearTimeout}; options.fail = self.fail; options.globalErrors = globalErrors; options.completeOnFirstError = failFast; options.onException = options.onException || function(e) { (currentRunnable() || topSuite).onException(e); }; options.deprecated = self.deprecated; new j$.QueueRunner(options).execute(args); }; var topSuite = new j$.Suite({ env: this, id: getNextSuiteId(), description: 'Jasmine__TopLevel__Suite', expectationFactory: expectationFactory, asyncExpectationFactory: asyncExpectationFactory, expectationResultFactory: expectationResultFactory }); defaultResourcesForRunnable(topSuite.id); currentDeclarationSuite = topSuite; this.topSuite = function() { return topSuite; }; /** * This represents the available reporter callback for an object passed to {@link Env#addReporter}. * @interface Reporter * @see custom_reporter */ var reporter = new j$.ReportDispatcher([ /** * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. * @function * @name Reporter#jasmineStarted * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. * @see async */ 'jasmineStarted', /** * When the entire suite has finished execution `jasmineDone` is called * @function * @name Reporter#jasmineDone * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. * @see async */ 'jasmineDone', /** * `suiteStarted` is invoked when a `describe` starts to run * @function * @name Reporter#suiteStarted * @param {SuiteResult} result Information about the individual {@link describe} being run * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. * @see async */ 'suiteStarted', /** * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run * * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. * @function * @name Reporter#suiteDone * @param {SuiteResult} result * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. * @see async */ 'suiteDone', /** * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) * @function * @name Reporter#specStarted * @param {SpecResult} result Information about the individual {@link it} being run * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. * @see async */ 'specStarted', /** * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. * * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. * @function * @name Reporter#specDone * @param {SpecResult} result * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. * @see async */ 'specDone' ], queueRunnerFactory); this.execute = function(runnablesToRun) { var self = this; installGlobalErrors(); if(!runnablesToRun) { if (focusedRunnables.length) { runnablesToRun = focusedRunnables; } else { runnablesToRun = [topSuite.id]; } } var order = new j$.Order({ random: config.random, seed: config.seed }); var processor = new j$.TreeProcessor({ tree: topSuite, runnableIds: runnablesToRun, queueRunnerFactory: queueRunnerFactory, nodeStart: function(suite, next) { currentlyExecutingSuites.push(suite); defaultResourcesForRunnable(suite.id, suite.parentSuite.id); reporter.suiteStarted(suite.result, next); suite.startTimer(); }, nodeComplete: function(suite, result, next) { if (suite !== currentSuite()) { throw new Error('Tried to complete the wrong suite'); } clearResourcesForRunnable(suite.id); currentlyExecutingSuites.pop(); if (result.status === 'failed') { hasFailures = true; } suite.endTimer(); reporter.suiteDone(result, next); }, orderChildren: function(node) { return order.sort(node.children); }, excludeNode: function(spec) { return !config.specFilter(spec); } }); if(!processor.processTree().valid) { throw new Error('Invalid order: would cause a beforeAll or afterAll to be run multiple times'); } /** * Information passed to the {@link Reporter#jasmineStarted} event. * @typedef JasmineStartedInfo * @property {Int} totalSpecsDefined - The total number of specs defined in this suite. * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. */ reporter.jasmineStarted({ totalSpecsDefined: totalSpecsDefined, order: order }, function() { currentlyExecutingSuites.push(topSuite); processor.execute(function () { clearResourcesForRunnable(topSuite.id); currentlyExecutingSuites.pop(); var overallStatus, incompleteReason; if (hasFailures || topSuite.result.failedExpectations.length > 0) { overallStatus = 'failed'; } else if (focusedRunnables.length > 0) { overallStatus = 'incomplete'; incompleteReason = 'fit() or fdescribe() was found'; } else if (totalSpecsDefined === 0) { overallStatus = 'incomplete'; incompleteReason = 'No specs found'; } else { overallStatus = 'passed'; } /** * Information passed to the {@link Reporter#jasmineDone} event. * @typedef JasmineDoneInfo * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. */ reporter.jasmineDone({ overallStatus: overallStatus, incompleteReason: incompleteReason, order: order, failedExpectations: topSuite.result.failedExpectations, deprecationWarnings: topSuite.result.deprecationWarnings }, function() {}); }); }); }; /** * Add a custom reporter to the Jasmine environment. * @name Env#addReporter * @function * @param {Reporter} reporterToAdd The reporter to be added. * @see custom_reporter */ this.addReporter = function(reporterToAdd) { reporter.addReporter(reporterToAdd); }; /** * Provide a fallback reporter if no other reporters have been specified. * @name Env#provideFallbackReporter * @function * @param {Reporter} reporterToAdd The reporter * @see custom_reporter */ this.provideFallbackReporter = function(reporterToAdd) { reporter.provideFallbackReporter(reporterToAdd); }; /** * Clear all registered reporters * @name Env#clearReporters * @function */ this.clearReporters = function() { reporter.clearReporters(); }; var spyFactory = new j$.SpyFactory(function() { var runnable = currentRunnable(); if (runnable) { return runnableResources[runnable.id].customSpyStrategies; } return {}; }); var spyRegistry = new j$.SpyRegistry({ currentSpies: function() { if(!currentRunnable()) { throw new Error('Spies must be created in a before function or a spec'); } return runnableResources[currentRunnable().id].spies; }, createSpy: function(name, originalFn) { return self.createSpy(name, originalFn); } }); this.allowRespy = function(allow){ spyRegistry.allowRespy(allow); }; this.spyOn = function() { return spyRegistry.spyOn.apply(spyRegistry, arguments); }; this.spyOnProperty = function() { return spyRegistry.spyOnProperty.apply(spyRegistry, arguments); }; this.spyOnAllFunctions = function() { return spyRegistry.spyOnAllFunctions.apply(spyRegistry, arguments); }; this.createSpy = function(name, originalFn) { if (arguments.length === 1 && j$.isFunction_(name)) { originalFn = name; name = originalFn.name; } return spyFactory.createSpy(name, originalFn); }; this.createSpyObj = function(baseName, methodNames) { return spyFactory.createSpyObj(baseName, methodNames); }; var ensureIsFunction = function(fn, caller) { if (!j$.isFunction_(fn)) { throw new Error(caller + ' expects a function argument; received ' + j$.getType_(fn)); } }; var ensureIsFunctionOrAsync = function(fn, caller) { if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { throw new Error(caller + ' expects a function argument; received ' + j$.getType_(fn)); } }; function ensureIsNotNested(method) { var runnable = currentRunnable(); if (runnable !== null && runnable !== undefined) { throw new Error('\'' + method + '\' should only be used in \'describe\' function'); } } var suiteFactory = function(description) { var suite = new j$.Suite({ env: self, id: getNextSuiteId(), description: description, parentSuite: currentDeclarationSuite, expectationFactory: expectationFactory, asyncExpectationFactory: asyncExpectationFactory, expectationResultFactory: expectationResultFactory, throwOnExpectationFailure: config.oneFailurePerSpec }); return suite; }; this.describe = function(description, specDefinitions) { ensureIsNotNested('describe'); ensureIsFunction(specDefinitions, 'describe'); var suite = suiteFactory(description); if (specDefinitions.length > 0) { throw new Error('describe does not expect any arguments'); } if (currentDeclarationSuite.markedPending) { suite.pend(); } addSpecsToSuite(suite, specDefinitions); return suite; }; this.xdescribe = function(description, specDefinitions) { ensureIsNotNested('xdescribe'); ensureIsFunction(specDefinitions, 'xdescribe'); var suite = suiteFactory(description); suite.pend(); addSpecsToSuite(suite, specDefinitions); return suite; }; var focusedRunnables = []; this.fdescribe = function(description, specDefinitions) { ensureIsNotNested('fdescribe'); ensureIsFunction(specDefinitions, 'fdescribe'); var suite = suiteFactory(description); suite.isFocused = true; focusedRunnables.push(suite.id); unfocusAncestor(); addSpecsToSuite(suite, specDefinitions); return suite; }; function addSpecsToSuite(suite, specDefinitions) { var parentSuite = currentDeclarationSuite; parentSuite.addChild(suite); currentDeclarationSuite = suite; var declarationError = null; try { specDefinitions.call(suite); } catch (e) { declarationError = e; } if (declarationError) { suite.onException(declarationError); } currentDeclarationSuite = parentSuite; } function findFocusedAncestor(suite) { while (suite) { if (suite.isFocused) { return suite.id; } suite = suite.parentSuite; } return null; } function unfocusAncestor() { var focusedAncestor = findFocusedAncestor(currentDeclarationSuite); if (focusedAncestor) { for (var i = 0; i < focusedRunnables.length; i++) { if (focusedRunnables[i] === focusedAncestor) { focusedRunnables.splice(i, 1); break; } } } } var specFactory = function(description, fn, suite, timeout) { totalSpecsDefined++; var spec = new j$.Spec({ id: getNextSpecId(), beforeAndAfterFns: beforeAndAfterFns(suite), expectationFactory: expectationFactory, asyncExpectationFactory: asyncExpectationFactory, resultCallback: specResultCallback, getSpecName: function(spec) { return getSpecName(spec, suite); }, onStart: specStarted, description: description, expectationResultFactory: expectationResultFactory, queueRunnerFactory: queueRunnerFactory, userContext: function() { return suite.clonedSharedUserContext(); }, queueableFn: { fn: fn, timeout: timeout || 0 }, throwOnExpectationFailure: config.oneFailurePerSpec, timer: new j$.Timer(), }); return spec; function specResultCallback(result, next) { clearResourcesForRunnable(spec.id); currentSpec = null; if (result.status === 'failed') { hasFailures = true; } reporter.specDone(result, next); } function specStarted(spec, next) { currentSpec = spec; defaultResourcesForRunnable(spec.id, suite.id); reporter.specStarted(spec.result, next); } }; this.it = function(description, fn, timeout) { ensureIsNotNested('it'); // it() sometimes doesn't have a fn argument, so only check the type if // it's given. if (arguments.length > 1 && typeof fn !== 'undefined') { ensureIsFunctionOrAsync(fn, 'it'); } var spec = specFactory(description, fn, currentDeclarationSuite, timeout); if (currentDeclarationSuite.markedPending) { spec.pend(); } currentDeclarationSuite.addChild(spec); return spec; }; this.xit = function(description, fn, timeout) { ensureIsNotNested('xit'); // xit(), like it(), doesn't always have a fn argument, so only check the // type when needed. if (arguments.length > 1 && typeof fn !== 'undefined') { ensureIsFunctionOrAsync(fn, 'xit'); } var spec = this.it.apply(this, arguments); spec.pend('Temporarily disabled with xit'); return spec; }; this.fit = function(description, fn, timeout){ ensureIsNotNested('fit'); ensureIsFunctionOrAsync(fn, 'fit'); var spec = specFactory(description, fn, currentDeclarationSuite, timeout); currentDeclarationSuite.addChild(spec); focusedRunnables.push(spec.id); unfocusAncestor(); return spec; }; this.expect = function(actual) { if (!currentRunnable()) { throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out'); } return currentRunnable().expect(actual); }; this.expectAsync = function(actual) { if (!currentRunnable()) { throw new Error('\'expectAsync\' was used when there was no current spec, this could be because an asynchronous test timed out'); } return currentRunnable().expectAsync(actual); }; this.beforeEach = function(beforeEachFunction, timeout) { ensureIsNotNested('beforeEach'); ensureIsFunctionOrAsync(beforeEachFunction, 'beforeEach'); currentDeclarationSuite.beforeEach({ fn: beforeEachFunction, timeout: timeout || 0 }); }; this.beforeAll = function(beforeAllFunction, timeout) { ensureIsNotNested('beforeAll'); ensureIsFunctionOrAsync(beforeAllFunction, 'beforeAll'); currentDeclarationSuite.beforeAll({ fn: beforeAllFunction, timeout: timeout || 0 }); }; this.afterEach = function(afterEachFunction, timeout) { ensureIsNotNested('afterEach'); ensureIsFunctionOrAsync(afterEachFunction, 'afterEach'); afterEachFunction.isCleanup = true; currentDeclarationSuite.afterEach({ fn: afterEachFunction, timeout: timeout || 0 }); }; this.afterAll = function(afterAllFunction, timeout) { ensureIsNotNested('afterAll'); ensureIsFunctionOrAsync(afterAllFunction, 'afterAll'); currentDeclarationSuite.afterAll({ fn: afterAllFunction, timeout: timeout || 0 }); }; this.pending = function(message) { var fullMessage = j$.Spec.pendingSpecExceptionMessage; if(message) { fullMessage += message; } throw fullMessage; }; this.fail = function(error) { if (!currentRunnable()) { throw new Error('\'fail\' was used when there was no current spec, this could be because an asynchronous test timed out'); } var message = 'Failed'; if (error) { message += ': '; if (error.message) { message += error.message; } else if (j$.isString_(error)) { message += error; } else { // pretty print all kind of objects. This includes arrays. message += j$.pp(error); } } currentRunnable().addExpectationResult(false, { matcherName: '', passed: false, expected: '', actual: '', message: message, error: error && error.message ? error : null }); if (config.oneFailurePerSpec) { throw new Error(message); } }; } return Env; }; getJasmineRequireObj().JsApiReporter = function(j$) { /** * @name jsApiReporter * @classdesc {@link Reporter} added by default in `boot.js` to record results for retrieval in javascript code. An instance is made available as `jsApiReporter` on the global object. * @class * @hideconstructor */ function JsApiReporter(options) { var timer = options.timer || j$.noopTimer, status = 'loaded'; this.started = false; this.finished = false; this.runDetails = {}; this.jasmineStarted = function() { this.started = true; status = 'started'; timer.start(); }; var executionTime; this.jasmineDone = function(runDetails) { this.finished = true; this.runDetails = runDetails; executionTime = timer.elapsed(); status = 'done'; }; /** * Get the current status for the Jasmine environment. * @name jsApiReporter#status * @function * @return {String} - One of `loaded`, `started`, or `done` */ this.status = function() { return status; }; var suites = [], suites_hash = {}; this.suiteStarted = function(result) { suites_hash[result.id] = result; }; this.suiteDone = function(result) { storeSuite(result); }; /** * Get the results for a set of suites. * * Retrievable in slices for easier serialization. * @name jsApiReporter#suiteResults * @function * @param {Number} index - The position in the suites list to start from. * @param {Number} length - Maximum number of suite results to return. * @return {SuiteResult[]} */ this.suiteResults = function(index, length) { return suites.slice(index, index + length); }; function storeSuite(result) { suites.push(result); suites_hash[result.id] = result; } /** * Get all of the suites in a single object, with their `id` as the key. * @name jsApiReporter#suites * @function * @return {Object} - Map of suite id to {@link SuiteResult} */ this.suites = function() { return suites_hash; }; var specs = []; this.specDone = function(result) { specs.push(result); }; /** * Get the results for a set of specs. * * Retrievable in slices for easier serialization. * @name jsApiReporter#specResults * @function * @param {Number} index - The position in the specs list to start from. * @param {Number} length - Maximum number of specs results to return. * @return {SpecResult[]} */ this.specResults = function(index, length) { return specs.slice(index, index + length); }; /** * Get all spec results. * @name jsApiReporter#specs * @function * @return {SpecResult[]} */ this.specs = function() { return specs; }; /** * Get the number of milliseconds it took for the full Jasmine suite to run. * @name jsApiReporter#executionTime * @function * @return {Number} */ this.executionTime = function() { return executionTime; }; } return JsApiReporter; }; getJasmineRequireObj().Any = function(j$) { function Any(expectedObject) { if (typeof expectedObject === 'undefined') { throw new TypeError( 'jasmine.any() expects to be passed a constructor function. ' + 'Please pass one or use jasmine.anything() to match any object.' ); } this.expectedObject = expectedObject; } Any.prototype.asymmetricMatch = function(other) { if (this.expectedObject == String) { return typeof other == 'string' || other instanceof String; } if (this.expectedObject == Number) { return typeof other == 'number' || other instanceof Number; } if (this.expectedObject == Function) { return typeof other == 'function' || other instanceof Function; } if (this.expectedObject == Object) { return other !== null && typeof other == 'object'; } if (this.expectedObject == Boolean) { return typeof other == 'boolean'; } /* jshint -W122 */ /* global Symbol */ if (typeof Symbol != 'undefined' && this.expectedObject == Symbol) { return typeof other == 'symbol'; } /* jshint +W122 */ return other instanceof this.expectedObject; }; Any.prototype.jasmineToString = function() { return ''; }; return Any; }; getJasmineRequireObj().Anything = function(j$) { function Anything() {} Anything.prototype.asymmetricMatch = function(other) { return !j$.util.isUndefined(other) && other !== null; }; Anything.prototype.jasmineToString = function() { return ''; }; return Anything; }; getJasmineRequireObj().ArrayContaining = function(j$) { function ArrayContaining(sample) { this.sample = sample; } ArrayContaining.prototype.asymmetricMatch = function(other, customTesters) { if (!j$.isArray_(this.sample)) { throw new Error('You must provide an array to arrayContaining, not ' + j$.pp(this.sample) + '.'); } for (var i = 0; i < this.sample.length; i++) { var item = this.sample[i]; if (!j$.matchersUtil.contains(other, item, customTesters)) { return false; } } return true; }; ArrayContaining.prototype.jasmineToString = function () { return ''; }; return ArrayContaining; }; getJasmineRequireObj().ArrayWithExactContents = function(j$) { function ArrayWithExactContents(sample) { this.sample = sample; } ArrayWithExactContents.prototype.asymmetricMatch = function(other, customTesters) { if (!j$.isArray_(this.sample)) { throw new Error('You must provide an array to arrayWithExactContents, not ' + j$.pp(this.sample) + '.'); } if (this.sample.length !== other.length) { return false; } for (var i = 0; i < this.sample.length; i++) { var item = this.sample[i]; if (!j$.matchersUtil.contains(other, item, customTesters)) { return false; } } return true; }; ArrayWithExactContents.prototype.jasmineToString = function() { return ''; }; return ArrayWithExactContents; }; getJasmineRequireObj().Empty = function (j$) { function Empty() {} Empty.prototype.asymmetricMatch = function (other) { if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { return other.length === 0; } if (j$.isMap(other) || j$.isSet(other)) { return other.size === 0; } if (j$.isObject_(other)) { return Object.keys(other).length === 0; } return false; }; Empty.prototype.jasmineToString = function () { return ''; }; return Empty; }; getJasmineRequireObj().Falsy = function(j$) { function Falsy() {} Falsy.prototype.asymmetricMatch = function(other) { return !other; }; Falsy.prototype.jasmineToString = function() { return ''; }; return Falsy; }; getJasmineRequireObj().NotEmpty = function (j$) { function NotEmpty() {} NotEmpty.prototype.asymmetricMatch = function (other) { if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { return other.length !== 0; } if (j$.isMap(other) || j$.isSet(other)) { return other.size !== 0; } if (j$.isObject_(other)) { return Object.keys(other).length !== 0; } return false; }; NotEmpty.prototype.jasmineToString = function () { return ''; }; return NotEmpty; }; getJasmineRequireObj().ObjectContaining = function(j$) { function ObjectContaining(sample) { this.sample = sample; } function getPrototype(obj) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(obj); } if (obj.constructor.prototype == obj) { return null; } return obj.constructor.prototype; } function hasProperty(obj, property) { if (!obj) { return false; } if (Object.prototype.hasOwnProperty.call(obj, property)) { return true; } return hasProperty(getPrototype(obj), property); } ObjectContaining.prototype.asymmetricMatch = function(other, customTesters) { if (typeof(this.sample) !== 'object') { throw new Error('You must provide an object to objectContaining, not \''+this.sample+'\'.'); } for (var property in this.sample) { if (!hasProperty(other, property) || !j$.matchersUtil.equals(this.sample[property], other[property], customTesters)) { return false; } } return true; }; ObjectContaining.prototype.jasmineToString = function() { return ''; }; return ObjectContaining; }; getJasmineRequireObj().StringMatching = function(j$) { function StringMatching(expected) { if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { throw new Error('Expected is not a String or a RegExp'); } this.regexp = new RegExp(expected); } StringMatching.prototype.asymmetricMatch = function(other) { return this.regexp.test(other); }; StringMatching.prototype.jasmineToString = function() { return ''; }; return StringMatching; }; getJasmineRequireObj().Truthy = function(j$) { function Truthy() {} Truthy.prototype.asymmetricMatch = function(other) { return !!other; }; Truthy.prototype.jasmineToString = function() { return ''; }; return Truthy; }; getJasmineRequireObj().CallTracker = function(j$) { /** * @namespace Spy#calls */ function CallTracker() { var calls = []; var opts = {}; this.track = function(context) { if(opts.cloneArgs) { context.args = j$.util.cloneArgs(context.args); } calls.push(context); }; /** * Check whether this spy has been invoked. * @name Spy#calls#any * @function * @return {Boolean} */ this.any = function() { return !!calls.length; }; /** * Get the number of invocations of this spy. * @name Spy#calls#count * @function * @return {Integer} */ this.count = function() { return calls.length; }; /** * Get the arguments that were passed to a specific invocation of this spy. * @name Spy#calls#argsFor * @function * @param {Integer} index The 0-based invocation index. * @return {Array} */ this.argsFor = function(index) { var call = calls[index]; return call ? call.args : []; }; /** * Get the raw calls array for this spy. * @name Spy#calls#all * @function * @return {Spy.callData[]} */ this.all = function() { return calls; }; /** * Get all of the arguments for each invocation of this spy in the order they were received. * @name Spy#calls#allArgs * @function * @return {Array} */ this.allArgs = function() { var callArgs = []; for(var i = 0; i < calls.length; i++){ callArgs.push(calls[i].args); } return callArgs; }; /** * Get the first invocation of this spy. * @name Spy#calls#first * @function * @return {ObjecSpy.callData} */ this.first = function() { return calls[0]; }; /** * Get the most recent invocation of this spy. * @name Spy#calls#mostRecent * @function * @return {ObjecSpy.callData} */ this.mostRecent = function() { return calls[calls.length - 1]; }; /** * Reset this spy as if it has never been called. * @name Spy#calls#reset * @function */ this.reset = function() { calls = []; }; /** * Set this spy to do a shallow clone of arguments passed to each invocation. * @name Spy#calls#saveArgumentsByValue * @function */ this.saveArgumentsByValue = function() { opts.cloneArgs = true; }; } return CallTracker; }; getJasmineRequireObj().clearStack = function(j$) { var maxInlineCallCount = 10; function messageChannelImpl(global, setTimeout) { var channel = new global.MessageChannel(), head = {}, tail = head; var taskRunning = false; channel.port1.onmessage = function() { head = head.next; var task = head.task; delete head.task; if (taskRunning) { global.setTimeout(task, 0); } else { try { taskRunning = true; task(); } finally { taskRunning = false; } } }; var currentCallCount = 0; return function clearStack(fn) { currentCallCount++; if (currentCallCount < maxInlineCallCount) { tail = tail.next = { task: fn }; channel.port2.postMessage(0); } else { currentCallCount = 0; setTimeout(fn); } }; } function getClearStack(global) { var currentCallCount = 0; var realSetTimeout = global.setTimeout; var setTimeoutImpl = function clearStack(fn) { Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); }; if (j$.isFunction_(global.setImmediate)) { var realSetImmediate = global.setImmediate; return function(fn) { currentCallCount++; if (currentCallCount < maxInlineCallCount) { realSetImmediate(fn); } else { currentCallCount = 0; setTimeoutImpl(fn); } }; } else if (!j$.util.isUndefined(global.MessageChannel)) { return messageChannelImpl(global, setTimeoutImpl); } else { return setTimeoutImpl; } } return getClearStack; }; getJasmineRequireObj().Clock = function() { /* global process */ var NODE_JS = typeof process !== 'undefined' && process.versions && typeof process.versions.node === 'string'; /** * _Note:_ Do not construct this directly, Jasmine will make one during booting. You can get the current clock with {@link jasmine.clock}. * @class Clock * @classdesc Jasmine's mock clock is used when testing time dependent code. */ function Clock(global, delayedFunctionSchedulerFactory, mockDate) { var self = this, realTimingFunctions = { setTimeout: global.setTimeout, clearTimeout: global.clearTimeout, setInterval: global.setInterval, clearInterval: global.clearInterval }, fakeTimingFunctions = { setTimeout: setTimeout, clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval }, installed = false, delayedFunctionScheduler, timer; self.FakeTimeout = FakeTimeout; /** * Install the mock clock over the built-in methods. * @name Clock#install * @function * @return {Clock} */ self.install = function() { if(!originalTimingFunctionsIntact()) { throw new Error('Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?'); } replace(global, fakeTimingFunctions); timer = fakeTimingFunctions; delayedFunctionScheduler = delayedFunctionSchedulerFactory(); installed = true; return self; }; /** * Uninstall the mock clock, returning the built-in methods to their places. * @name Clock#uninstall * @function */ self.uninstall = function() { delayedFunctionScheduler = null; mockDate.uninstall(); replace(global, realTimingFunctions); timer = realTimingFunctions; installed = false; }; /** * Execute a function with a mocked Clock * * The clock will be {@link Clock#install|install}ed before the function is called and {@link Clock#uninstall|uninstall}ed in a `finally` after the function completes. * @name Clock#withMock * @function * @param {Function} closure The function to be called. */ self.withMock = function(closure) { this.install(); try { closure(); } finally { this.uninstall(); } }; /** * Instruct the installed Clock to also mock the date returned by `new Date()` * @name Clock#mockDate * @function * @param {Date} [initialDate=now] The `Date` to provide. */ self.mockDate = function(initialDate) { mockDate.install(initialDate); }; self.setTimeout = function(fn, delay, params) { return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); }; self.setInterval = function(fn, delay, params) { return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); }; self.clearTimeout = function(id) { return Function.prototype.call.apply(timer.clearTimeout, [global, id]); }; self.clearInterval = function(id) { return Function.prototype.call.apply(timer.clearInterval, [global, id]); }; /** * Tick the Clock forward, running any enqueued timeouts along the way * @name Clock#tick * @function * @param {int} millis The number of milliseconds to tick. */ self.tick = function(millis) { if (installed) { delayedFunctionScheduler.tick(millis, function(millis) { mockDate.tick(millis); }); } else { throw new Error('Mock clock is not installed, use jasmine.clock().install()'); } }; return self; function originalTimingFunctionsIntact() { return global.setTimeout === realTimingFunctions.setTimeout && global.clearTimeout === realTimingFunctions.clearTimeout && global.setInterval === realTimingFunctions.setInterval && global.clearInterval === realTimingFunctions.clearInterval; } function replace(dest, source) { for (var prop in source) { dest[prop] = source[prop]; } } function setTimeout(fn, delay) { if (!NODE_JS) { return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); } var timeout = new FakeTimeout(); delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2), false, timeout); return timeout; } function clearTimeout(id) { return delayedFunctionScheduler.removeFunctionWithId(id); } function setInterval(fn, interval) { if (!NODE_JS) { return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); } var timeout = new FakeTimeout(); delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true, timeout); return timeout; } function clearInterval(id) { return delayedFunctionScheduler.removeFunctionWithId(id); } function argSlice(argsObj, n) { return Array.prototype.slice.call(argsObj, n); } } /** * Mocks Node.js Timeout class */ function FakeTimeout() {} FakeTimeout.prototype.ref = function () { return this; }; FakeTimeout.prototype.unref = function () { return this; }; return Clock; }; getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function DelayedFunctionScheduler() { var self = this; var scheduledLookup = []; var scheduledFunctions = {}; var currentTime = 0; var delayedFnCount = 0; var deletedKeys = []; self.tick = function(millis, tickDate) { millis = millis || 0; var endTime = currentTime + millis; runScheduledFunctions(endTime, tickDate); currentTime = endTime; }; self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { var f; if (typeof(funcToCall) === 'string') { /* jshint evil: true */ f = function() { return eval(funcToCall); }; /* jshint evil: false */ } else { f = funcToCall; } millis = millis || 0; timeoutKey = timeoutKey || ++delayedFnCount; runAtMillis = runAtMillis || (currentTime + millis); var funcToSchedule = { runAtMillis: runAtMillis, funcToCall: f, recurring: recurring, params: params, timeoutKey: timeoutKey, millis: millis }; if (runAtMillis in scheduledFunctions) { scheduledFunctions[runAtMillis].push(funcToSchedule); } else { scheduledFunctions[runAtMillis] = [funcToSchedule]; scheduledLookup.push(runAtMillis); scheduledLookup.sort(function (a, b) { return a - b; }); } return timeoutKey; }; self.removeFunctionWithId = function(timeoutKey) { deletedKeys.push(timeoutKey); for (var runAtMillis in scheduledFunctions) { var funcs = scheduledFunctions[runAtMillis]; var i = indexOfFirstToPass(funcs, function (func) { return func.timeoutKey === timeoutKey; }); if (i > -1) { if (funcs.length === 1) { delete scheduledFunctions[runAtMillis]; deleteFromLookup(runAtMillis); } else { funcs.splice(i, 1); } // intervals get rescheduled when executed, so there's never more // than a single scheduled function with a given timeoutKey break; } } }; return self; function indexOfFirstToPass(array, testFn) { var index = -1; for (var i = 0; i < array.length; ++i) { if (testFn(array[i])) { index = i; break; } } return index; } function deleteFromLookup(key) { var value = Number(key); var i = indexOfFirstToPass(scheduledLookup, function (millis) { return millis === value; }); if (i > -1) { scheduledLookup.splice(i, 1); } } function reschedule(scheduledFn) { self.scheduleFunction(scheduledFn.funcToCall, scheduledFn.millis, scheduledFn.params, true, scheduledFn.timeoutKey, scheduledFn.runAtMillis + scheduledFn.millis); } function forEachFunction(funcsToRun, callback) { for (var i = 0; i < funcsToRun.length; ++i) { callback(funcsToRun[i]); } } function runScheduledFunctions(endTime, tickDate) { tickDate = tickDate || function() {}; if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { tickDate(endTime - currentTime); return; } do { deletedKeys = []; var newCurrentTime = scheduledLookup.shift(); tickDate(newCurrentTime - currentTime); currentTime = newCurrentTime; var funcsToRun = scheduledFunctions[currentTime]; delete scheduledFunctions[currentTime]; forEachFunction(funcsToRun, function(funcToRun) { if (funcToRun.recurring) { reschedule(funcToRun); } }); forEachFunction(funcsToRun, function(funcToRun) { if (j$.util.arrayContains(deletedKeys, funcToRun.timeoutKey)) { // skip a timeoutKey deleted whilst we were running return; } funcToRun.funcToCall.apply(null, funcToRun.params || []); }); deletedKeys = []; } while (scheduledLookup.length > 0 && // checking first if we're out of time prevents setTimeout(0) // scheduled in a funcToRun from forcing an extra iteration currentTime !== endTime && scheduledLookup[0] <= endTime); // ran out of functions to call, but still time left on the clock if (currentTime !== endTime) { tickDate(endTime - currentTime); } } } return DelayedFunctionScheduler; }; getJasmineRequireObj().errors = function() { function ExpectationFailed() {} ExpectationFailed.prototype = new Error(); ExpectationFailed.prototype.constructor = ExpectationFailed; return { ExpectationFailed: ExpectationFailed }; }; getJasmineRequireObj().ExceptionFormatter = function(j$) { var ignoredProperties = ['name', 'message', 'stack', 'fileName', 'sourceURL', 'line', 'lineNumber', 'column', 'description', 'jasmineMessage']; function ExceptionFormatter(options) { var jasmineFile = (options && options.jasmineFile) || j$.util.jasmineFile(); this.message = function(error) { var message = ''; if (error.jasmineMessage) { message += error.jasmineMessage; } else if (error.name && error.message) { message += error.name + ': ' + error.message; } else if (error.message) { message += error.message; } else { message += error.toString() + ' thrown'; } if (error.fileName || error.sourceURL) { message += ' in ' + (error.fileName || error.sourceURL); } if (error.line || error.lineNumber) { message += ' (line ' + (error.line || error.lineNumber) + ')'; } return message; }; this.stack = function(error) { if (!error || !error.stack) { return null; } var stackTrace = new j$.StackTrace(error); var lines = filterJasmine(stackTrace); var result = ''; if (stackTrace.message) { lines.unshift(stackTrace.message); } result += formatProperties(error); result += lines.join('\n'); return result; }; function filterJasmine(stackTrace) { var result = [], jasmineMarker = stackTrace.style === 'webkit' ? '' : ' at '; stackTrace.frames.forEach(function(frame) { if (frame.file && frame.file !== jasmineFile) { result.push(frame.raw); } else if (result[result.length - 1] !== jasmineMarker) { result.push(jasmineMarker); } }); return result; } function formatProperties(error) { if (!(error instanceof Object)) { return; } var result = {}; var empty = true; for (var prop in error) { if (j$.util.arrayContains(ignoredProperties, prop)) { continue; } result[prop] = error[prop]; empty = false; } if (!empty) { return 'error properties: ' + j$.pp(result) + '\n'; } return ''; } } return ExceptionFormatter; }; getJasmineRequireObj().Expectation = function(j$) { var promiseForMessage = { jasmineToString: function() { return 'a promise'; } }; /** * Matchers that come with Jasmine out of the box. * @namespace matchers */ function Expectation(options) { this.expector = new j$.Expector(options); var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); } } /** * Add some context for an {@link expect} * @function * @name matchers#withContext * @param {String} message - Additional context to show when the matcher fails * @return {matchers} */ Expectation.prototype.withContext = function withContext(message) { return addFilter(this, new ContextAddingFilter(message)); }; /** * Invert the matcher following this {@link expect} * @member * @name matchers#not * @type {matchers} * @example * expect(something).not.toBe(true); */ Object.defineProperty(Expectation.prototype, 'not', { get: function() { return addFilter(this, syncNegatingFilter); } }); /** * Asynchronous matchers. * @namespace async-matchers */ function AsyncExpectation(options) { var global = options.global || j$.getGlobal(); this.expector = new j$.Expector(options); if (!global.Promise) { throw new Error('expectAsync is unavailable because the environment does not support promises.'); } if (!j$.isPromiseLike(this.expector.actual)) { throw new Error('Expected expectAsync to be called with a promise.'); } } /** * Add some context for an {@link expectAsync} * @function * @name async-matchers#withContext * @param {String} message - Additional context to show when the async matcher fails * @return {async-matchers} */ AsyncExpectation.prototype.withContext = function withContext(message) { return addFilter(this, new ContextAddingFilter(message)); }; /** * Invert the matcher following this {@link expectAsync} * @member * @name async-matchers#not * @type {async-matchers} * @example * await expectAsync(myPromise).not.toBeResolved(); * @example * return expectAsync(myPromise).not.toBeResolved(); */ Object.defineProperty(AsyncExpectation.prototype, 'not', { get: function() { return addFilter(this, asyncNegatingFilter); } }); function wrapSyncCompare(name, matcherFactory) { return function() { var result = this.expector.compare(name, matcherFactory, arguments); this.expector.processResult(result); }; } function wrapAsyncCompare(name, matcherFactory) { return function() { var self = this; // Capture the call stack here, before we go async, so that it will contain // frames that are relevant to the user instead of just parts of Jasmine. var errorForStack = j$.util.errorWithStack(); return this.expector.compare(name, matcherFactory, arguments).then(function(result) { self.expector.processResult(result, errorForStack, promiseForMessage); }); }; } function addCoreMatchers(prototype, matchers, wrapper) { for (var matcherName in matchers) { var matcher = matchers[matcherName]; prototype[matcherName] = wrapper(matcherName, matcher); } } function addFilter(source, filter) { var result = Object.create(source); result.expector = source.expector.addFilter(filter); return result; } function negatedFailureMessage(result, matcherName, args, util) { if (result.message) { if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; } } args = args.slice(); args.unshift(true); args.unshift(matcherName); return util.buildFailureMessage.apply(null, args); } function negate(result) { result.pass = !result.pass; return result; } var syncNegatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { return negate(matcher.compare.apply(null, arguments)); } return matcher.negativeCompare || defaultNegativeCompare; }, buildFailureMessage: negatedFailureMessage }; var asyncNegatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { return matcher.compare.apply(this, arguments).then(negate); } return defaultNegativeCompare; }, buildFailureMessage: negatedFailureMessage }; function ContextAddingFilter(message) { this.message = message; } ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { return this.message + ': ' + msg; }; return { factory: function(options) { return new Expectation(options || {}); }, addCoreMatchers: function(matchers) { addCoreMatchers(Expectation.prototype, matchers, wrapSyncCompare); }, asyncFactory: function(options) { return new AsyncExpectation(options || {}); }, addAsyncCoreMatchers: function(matchers) { addCoreMatchers(AsyncExpectation.prototype, matchers, wrapAsyncCompare); } }; }; getJasmineRequireObj().ExpectationFilterChain = function() { function ExpectationFilterChain(maybeFilter, prev) { this.filter_ = maybeFilter; this.prev_ = prev; } ExpectationFilterChain.prototype.addFilter = function(filter) { return new ExpectationFilterChain(filter, this); }; ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { return this.callFirst_('selectComparisonFunc', arguments).result; }; ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { return this.callFirst_('buildFailureMessage', arguments).result; }; ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { var result = this.callFirst_('modifyFailureMessage', arguments).result; return result || msg; }; ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { var prevResult; if (this.prev_) { prevResult = this.prev_.callFirst_(fname, args); if (prevResult.found) { return prevResult; } } if (this.filter_ && this.filter_[fname]) { return { found: true, result: this.filter_[fname].apply(this.filter_, args) }; } return {found: false}; }; return ExpectationFilterChain; }; //TODO: expectation result may make more sense as a presentation of an expectation. getJasmineRequireObj().buildExpectationResult = function() { function buildExpectationResult(options) { var messageFormatter = options.messageFormatter || function() {}, stackFormatter = options.stackFormatter || function() {}; /** * @typedef Expectation * @property {String} matcherName - The name of the matcher that was executed for this expectation. * @property {String} message - The failure message for the expectation. * @property {String} stack - The stack trace for the failure if available. * @property {Boolean} passed - Whether the expectation passed or failed. * @property {Object} expected - If the expectation failed, what was the expected value. * @property {Object} actual - If the expectation failed, what actual value was produced. */ var result = { matcherName: options.matcherName, message: message(), stack: stack(), passed: options.passed }; if(!result.passed) { result.expected = options.expected; result.actual = options.actual; } return result; function message() { if (options.passed) { return 'Passed.'; } else if (options.message) { return options.message; } else if (options.error) { return messageFormatter(options.error); } return ''; } function stack() { if (options.passed) { return ''; } var error = options.error; if (!error) { if (options.errorForStack) { error = options.errorForStack; } else if (options.stack) { error = options; } else { try { throw new Error(message()); } catch (e) { error = e; } } } return stackFormatter(error); } } return buildExpectationResult; }; getJasmineRequireObj().Expector = function(j$) { function Expector(options) { this.util = options.util || { buildFailureMessage: function() {} }; this.customEqualityTesters = options.customEqualityTesters || []; this.actual = options.actual; this.addExpectationResult = options.addExpectationResult || function(){}; this.filters = new j$.ExpectationFilterChain(); } Expector.prototype.instantiateMatcher = function(matcherName, matcherFactory, args) { this.matcherName = matcherName; this.args = Array.prototype.slice.call(args, 0); this.expected = this.args.slice(0); this.args.unshift(this.actual); var matcher = matcherFactory(this.util, this.customEqualityTesters); var comparisonFunc = this.filters.selectComparisonFunc(matcher); return comparisonFunc || matcher.compare; }; Expector.prototype.buildMessage = function(result) { var self = this; if (result.pass) { return ''; } var msg = this.filters.buildFailureMessage(result, this.matcherName, this.args, this.util, defaultMessage); return this.filters.modifyFailureMessage(msg || defaultMessage()); function defaultMessage() { if (!result.message) { var args = self.args.slice(); args.unshift(false); args.unshift(self.matcherName); return self.util.buildFailureMessage.apply(null, args); } else if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; } } }; Expector.prototype.compare = function(matcherName, matcherFactory, args) { var matcherCompare = this.instantiateMatcher(matcherName, matcherFactory, args); return matcherCompare.apply(null, this.args); }; Expector.prototype.addFilter = function(filter) { var result = Object.create(this); result.filters = this.filters.addFilter(filter); return result; }; Expector.prototype.processResult = function(result, errorForStack, actualOverride) { this.args[0] = actualOverride || this.args[0]; var message = this.buildMessage(result); if (this.expected.length === 1) { this.expected = this.expected[0]; } this.addExpectationResult( result.pass, { matcherName: this.matcherName, passed: result.pass, message: message, error: errorForStack ? undefined : result.error, errorForStack: errorForStack || undefined, actual: this.actual, expected: this.expected // TODO: this may need to be arrayified/sliced } ); }; return Expector; }; getJasmineRequireObj().formatErrorMsg = function() { function generateErrorMsg(domain, usage) { var usageDefinition = usage ? '\nUsage: ' + usage : ''; return function errorMsg(msg) { return domain + ' : ' + msg + usageDefinition; }; } return generateErrorMsg; }; getJasmineRequireObj().GlobalErrors = function(j$) { function GlobalErrors(global) { var handlers = []; global = global || j$.getGlobal(); var onerror = function onerror() { var handler = handlers[handlers.length - 1]; if (handler) { handler.apply(null, Array.prototype.slice.call(arguments, 0)); } else { throw arguments[0]; } }; this.originalHandlers = {}; this.jasmineHandlers = {}; this.installOne_ = function installOne_(errorType, jasmineMessage) { function taggedOnError(error) { error.jasmineMessage = jasmineMessage + ': ' + error; var handler = handlers[handlers.length - 1]; if (handler) { handler(error); } else { throw error; } } this.originalHandlers[errorType] = global.process.listeners(errorType); this.jasmineHandlers[errorType] = taggedOnError; global.process.removeAllListeners(errorType); global.process.on(errorType, taggedOnError); this.uninstall = function uninstall() { var errorTypes = Object.keys(this.originalHandlers); for (var iType = 0; iType < errorTypes.length; iType++) { var errorType = errorTypes[iType]; global.process.removeListener(errorType, this.jasmineHandlers[errorType]); for (var i = 0; i < this.originalHandlers[errorType].length; i++) { global.process.on(errorType, this.originalHandlers[errorType][i]); } delete this.originalHandlers[errorType]; delete this.jasmineHandlers[errorType]; } }; }; this.install = function install() { if (global.process && global.process.listeners && j$.isFunction_(global.process.on)) { this.installOne_('uncaughtException', 'Uncaught exception'); this.installOne_('unhandledRejection', 'Unhandled promise rejection'); } else { var originalHandler = global.onerror; global.onerror = onerror; this.uninstall = function uninstall() { global.onerror = originalHandler; }; } }; this.pushListener = function pushListener(listener) { handlers.push(listener); }; this.popListener = function popListener() { handlers.pop(); }; } return GlobalErrors; }; getJasmineRequireObj().toBeRejected = function(j$) { /** * Expect a promise to be rejected. * @function * @async * @name async-matchers#toBeRejected * @example * await expectAsync(aPromise).toBeRejected(); * @example * return expectAsync(aPromise).toBeRejected(); */ return function toBeResolved(util) { return { compare: function(actual) { return actual.then( function() { return {pass: false}; }, function() { return {pass: true}; } ); } }; }; }; getJasmineRequireObj().toBeRejectedWith = function(j$) { /** * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. * @function * @async * @name async-matchers#toBeRejectedWith * @param {Object} expected - Value that the promise is expected to be rejected with * @example * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); * @example * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); */ return function toBeRejectedWith(util, customEqualityTesters) { return { compare: function(actualPromise, expectedValue) { function prefix(passed) { return 'Expected a promise ' + (passed ? 'not ' : '') + 'to be rejected with ' + j$.pp(expectedValue); } return actualPromise.then( function() { return { pass: false, message: prefix(false) + ' but it was resolved.' }; }, function(actualValue) { if (util.equals(actualValue, expectedValue, customEqualityTesters)) { return { pass: true, message: prefix(true) + '.' }; } else { return { pass: false, message: prefix(false) + ' but it was rejected with ' + j$.pp(actualValue) + '.' }; } } ); } }; }; }; getJasmineRequireObj().toBeResolved = function(j$) { /** * Expect a promise to be resolved. * @function * @async * @name async-matchers#toBeResolved * @example * await expectAsync(aPromise).toBeResolved(); * @example * return expectAsync(aPromise).toBeResolved(); */ return function toBeResolved(util) { return { compare: function(actual) { return actual.then( function() { return {pass: true}; }, function() { return {pass: false}; } ); } }; }; }; getJasmineRequireObj().toBeResolvedTo = function(j$) { /** * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. * @function * @async * @name async-matchers#toBeResolvedTo * @param {Object} expected - Value that the promise is expected to resolve to * @example * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); * @example * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); */ return function toBeResolvedTo(util, customEqualityTesters) { return { compare: function(actualPromise, expectedValue) { function prefix(passed) { return 'Expected a promise ' + (passed ? 'not ' : '') + 'to be resolved to ' + j$.pp(expectedValue); } return actualPromise.then( function(actualValue) { if (util.equals(actualValue, expectedValue, customEqualityTesters)) { return { pass: true, message: prefix(true) + '.' }; } else { return { pass: false, message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' }; } }, function() { return { pass: false, message: prefix(false) + ' but it was rejected.' }; } ); } }; }; }; getJasmineRequireObj().DiffBuilder = function(j$) { return function DiffBuilder() { var path = new j$.ObjectPath(), mismatches = []; return { record: function (actual, expected, formatter) { formatter = formatter || defaultFormatter; mismatches.push(formatter(actual, expected, path)); }, getMessage: function () { return mismatches.join('\n'); }, withPath: function (pathComponent, block) { var oldPath = path; path = path.add(pathComponent); block(); path = oldPath; } }; function defaultFormatter (actual, expected, path) { return 'Expected ' + path + (path.depth() ? ' = ' : '') + j$.pp(actual) + ' to equal ' + j$.pp(expected) + '.'; } }; }; getJasmineRequireObj().matchersUtil = function(j$) { // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? return { equals: equals, contains: function(haystack, needle, customTesters) { customTesters = customTesters || []; if ((Object.prototype.toString.apply(haystack) === '[object Set]')) { return haystack.has(needle); } if ((Object.prototype.toString.apply(haystack) === '[object Array]') || (!!haystack && !haystack.indexOf)) { for (var i = 0; i < haystack.length; i++) { if (equals(haystack[i], needle, customTesters)) { return true; } } return false; } return !!haystack && haystack.indexOf(needle) >= 0; }, buildFailureMessage: function() { var args = Array.prototype.slice.call(arguments, 0), matcherName = args[0], isNot = args[1], actual = args[2], expected = args.slice(3), englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); var message = 'Expected ' + j$.pp(actual) + (isNot ? ' not ' : ' ') + englishyPredicate; if (expected.length > 0) { for (var i = 0; i < expected.length; i++) { if (i > 0) { message += ','; } message += ' ' + j$.pp(expected[i]); } } return message + '.'; } }; function isAsymmetric(obj) { return obj && j$.isA_('Function', obj.asymmetricMatch); } function asymmetricMatch(a, b, customTesters, diffBuilder) { var asymmetricA = isAsymmetric(a), asymmetricB = isAsymmetric(b), result; if (asymmetricA && asymmetricB) { return undefined; } if (asymmetricA) { result = a.asymmetricMatch(b, customTesters); if (!result) { diffBuilder.record(a, b); } return result; } if (asymmetricB) { result = b.asymmetricMatch(a, customTesters); if (!result) { diffBuilder.record(a, b); } return result; } } function equals(a, b, customTesters, diffBuilder) { customTesters = customTesters || []; diffBuilder = diffBuilder || j$.NullDiffBuilder(); return eq(a, b, [], [], customTesters, diffBuilder); } // Equality function lovingly adapted from isEqual in // [Underscore](http://underscorejs.org) function eq(a, b, aStack, bStack, customTesters, diffBuilder) { var result = true, i; var asymmetricResult = asymmetricMatch(a, b, customTesters, diffBuilder); if (!j$.util.isUndefined(asymmetricResult)) { return asymmetricResult; } for (i = 0; i < customTesters.length; i++) { var customTesterResult = customTesters[i](a, b); if (!j$.util.isUndefined(customTesterResult)) { if (!customTesterResult) { diffBuilder.record(a, b); } return customTesterResult; } } if (a instanceof Error && b instanceof Error) { result = a.message == b.message; if (!result) { diffBuilder.record(a, b); } return result; } // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) { result = a !== 0 || 1 / a == 1 / b; if (!result) { diffBuilder.record(a, b); } return result; } // A strict comparison is necessary because `null == undefined`. if (a === null || b === null) { result = a === b; if (!result) { diffBuilder.record(a, b); } return result; } var className = Object.prototype.toString.call(a); if (className != Object.prototype.toString.call(b)) { diffBuilder.record(a, b); return false; } switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. result = a == String(b); if (!result) { diffBuilder.record(a, b); } return result; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. result = a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b); if (!result) { diffBuilder.record(a, b); } return result; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. result = +a == +b; if (!result) { diffBuilder.record(a, b); } return result; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') { diffBuilder.record(a, b); return false; } var aIsDomNode = j$.isDomNode(a); var bIsDomNode = j$.isDomNode(b); if (aIsDomNode && bIsDomNode) { // At first try to use DOM3 method isEqualNode result = a.isEqualNode(b); if (!result) { diffBuilder.record(a, b); } return result; } if (aIsDomNode || bIsDomNode) { diffBuilder.record(a, b); return false; } var aIsPromise = j$.isPromise(a); var bIsPromise = j$.isPromise(b); if (aIsPromise && bIsPromise) { return a === b; } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) { return bStack[length] == b; } } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0; // Recursively compare objects and arrays. // Compare array lengths to determine if a deep comparison is necessary. if (className == '[object Array]') { var aLength = a.length; var bLength = b.length; diffBuilder.withPath('length', function() { if (aLength !== bLength) { diffBuilder.record(aLength, bLength); result = false; } }); for (i = 0; i < aLength || i < bLength; i++) { var formatter = false; diffBuilder.withPath(i, function() { if (i >= bLength) { diffBuilder.record(a[i], void 0, actualArrayIsLongerFormatter); result = false; } else { result = eq(i < aLength ? a[i] : void 0, i < bLength ? b[i] : void 0, aStack, bStack, customTesters, diffBuilder) && result; } }); } if (!result) { return false; } } else if (j$.isMap(a) && j$.isMap(b)) { if (a.size != b.size) { diffBuilder.record(a, b); return false; } var keysA = []; var keysB = []; a.forEach( function( valueA, keyA ) { keysA.push( keyA ); }); b.forEach( function( valueB, keyB ) { keysB.push( keyB ); }); // For both sets of keys, check they map to equal values in both maps. // Keep track of corresponding keys (in insertion order) in order to handle asymmetric obj keys. var mapKeys = [keysA, keysB]; var cmpKeys = [keysB, keysA]; var mapIter, mapKey, mapValueA, mapValueB; var cmpIter, cmpKey; for (i = 0; result && i < mapKeys.length; i++) { mapIter = mapKeys[i]; cmpIter = cmpKeys[i]; for (var j = 0; result && j < mapIter.length; j++) { mapKey = mapIter[j]; cmpKey = cmpIter[j]; mapValueA = a.get(mapKey); // Only use the cmpKey when one of the keys is asymmetric and the corresponding key matches, // otherwise explicitly look up the mapKey in the other Map since we want keys with unique // obj identity (that are otherwise equal) to not match. if (isAsymmetric(mapKey) || isAsymmetric(cmpKey) && eq(mapKey, cmpKey, aStack, bStack, customTesters, j$.NullDiffBuilder())) { mapValueB = b.get(cmpKey); } else { mapValueB = b.get(mapKey); } result = eq(mapValueA, mapValueB, aStack, bStack, customTesters, j$.NullDiffBuilder()); } } if (!result) { diffBuilder.record(a, b); return false; } } else if (j$.isSet(a) && j$.isSet(b)) { if (a.size != b.size) { diffBuilder.record(a, b); return false; } var valuesA = []; a.forEach( function( valueA ) { valuesA.push( valueA ); }); var valuesB = []; b.forEach( function( valueB ) { valuesB.push( valueB ); }); // For both sets, check they are all contained in the other set var setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; var stackPairs = [[aStack, bStack], [bStack, aStack]]; var baseValues, baseValue, baseStack; var otherValues, otherValue, otherStack; var found; var prevStackSize; for (i = 0; result && i < setPairs.length; i++) { baseValues = setPairs[i][0]; otherValues = setPairs[i][1]; baseStack = stackPairs[i][0]; otherStack = stackPairs[i][1]; // For each value in the base set... for (var k = 0; result && k < baseValues.length; k++) { baseValue = baseValues[k]; found = false; // ... test that it is present in the other set for (var l = 0; !found && l < otherValues.length; l++) { otherValue = otherValues[l]; prevStackSize = baseStack.length; // compare by value equality found = eq(baseValue, otherValue, baseStack, otherStack, customTesters, j$.NullDiffBuilder()); if (!found && prevStackSize !== baseStack.length) { baseStack.splice(prevStackSize); otherStack.splice(prevStackSize); } } result = result && found; } } if (!result) { diffBuilder.record(a, b); return false; } } else { // Objects with different constructors are not equivalent, but `Object`s // or `Array`s from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && isFunction(aCtor) && isFunction(bCtor) && a instanceof aCtor && b instanceof bCtor && !(aCtor instanceof aCtor && bCtor instanceof bCtor)) { diffBuilder.record(a, b, constructorsAreDifferentFormatter); return false; } } // Deep compare objects. var aKeys = keys(a, className == '[object Array]'), key; size = aKeys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (keys(b, className == '[object Array]').length !== size) { diffBuilder.record(a, b, objectKeysAreDifferentFormatter); return false; } for (i = 0; i < size; i++) { key = aKeys[i]; // Deep compare each member if (!j$.util.has(b, key)) { diffBuilder.record(a, b, objectKeysAreDifferentFormatter); result = false; continue; } diffBuilder.withPath(key, function() { if(!eq(a[key], b[key], aStack, bStack, customTesters, diffBuilder)) { result = false; } }); } if (!result) { return false; } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; } function keys(obj, isArray) { var allKeys = Object.keys ? Object.keys(obj) : (function(o) { var keys = []; for (var key in o) { if (j$.util.has(o, key)) { keys.push(key); } } return keys; })(obj); if (!isArray) { return allKeys; } if (allKeys.length === 0) { return allKeys; } var extraKeys = []; for (var i = 0; i < allKeys.length; i++) { if (!/^[0-9]+$/.test(allKeys[i])) { extraKeys.push(allKeys[i]); } } return extraKeys; } function has(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function isFunction(obj) { return typeof obj === 'function'; } function objectKeysAreDifferentFormatter(actual, expected, path) { var missingProperties = j$.util.objectDifference(expected, actual), extraProperties = j$.util.objectDifference(actual, expected), missingPropertiesMessage = formatKeyValuePairs(missingProperties), extraPropertiesMessage = formatKeyValuePairs(extraProperties), messages = []; if (!path.depth()) { path = 'object'; } if (missingPropertiesMessage.length) { messages.push('Expected ' + path + ' to have properties' + missingPropertiesMessage); } if (extraPropertiesMessage.length) { messages.push('Expected ' + path + ' not to have properties' + extraPropertiesMessage); } return messages.join('\n'); } function constructorsAreDifferentFormatter(actual, expected, path) { if (!path.depth()) { path = 'object'; } return 'Expected ' + path + ' to be a kind of ' + j$.fnNameFor(expected.constructor) + ', but was ' + j$.pp(actual) + '.'; } function actualArrayIsLongerFormatter(actual, expected, path) { return 'Unexpected ' + path + (path.depth() ? ' = ' : '') + j$.pp(actual) + ' in array.'; } function formatKeyValuePairs(obj) { var formatted = ''; for (var key in obj) { formatted += '\n ' + key + ': ' + j$.pp(obj[key]); } return formatted; } }; getJasmineRequireObj().nothing = function() { /** * {@link expect} nothing explicitly. * @function * @name matchers#nothing * @example * expect().nothing(); */ function nothing() { return { compare: function() { return { pass: true }; } }; } return nothing; }; getJasmineRequireObj().NullDiffBuilder = function(j$) { return function() { return { withPath: function(_, block) { block(); }, record: function() {} }; }; }; getJasmineRequireObj().ObjectPath = function(j$) { function ObjectPath(components) { this.components = components || []; } ObjectPath.prototype.toString = function() { if (this.components.length) { return '$' + map(this.components, formatPropertyAccess).join(''); } else { return ''; } }; ObjectPath.prototype.add = function(component) { return new ObjectPath(this.components.concat([component])); }; ObjectPath.prototype.depth = function() { return this.components.length; }; function formatPropertyAccess(prop) { if (typeof prop === 'number') { return '[' + prop + ']'; } if (isValidIdentifier(prop)) { return '.' + prop; } return '[\'' + prop + '\']'; } function map(array, fn) { var results = []; for (var i = 0; i < array.length; i++) { results.push(fn(array[i])); } return results; } function isValidIdentifier(string) { return /^[A-Za-z\$_][A-Za-z0-9\$_]*$/.test(string); } return ObjectPath; }; getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { var availableMatchers = [ 'toBeResolved', 'toBeRejected', 'toBeResolvedTo', 'toBeRejectedWith' ], matchers = {}; for (var i = 0; i < availableMatchers.length; i++) { var name = availableMatchers[i]; matchers[name] = jRequire[name](j$); } return matchers; }; getJasmineRequireObj().toBe = function(j$) { /** * {@link expect} the actual value to be `===` to the expected value. * @function * @name matchers#toBe * @param {Object} expected - The expected value to compare against. * @example * expect(thing).toBe(realThing); */ function toBe(util) { var tip = ' Tip: To check for deep equality, use .toEqual() instead of .toBe().'; return { compare: function(actual, expected) { var result = { pass: actual === expected, }; if (typeof expected === 'object') { result.message = util.buildFailureMessage('toBe', result.pass, actual, expected) + tip; } return result; } }; } return toBe; }; getJasmineRequireObj().toBeCloseTo = function() { /** * {@link expect} the actual value to be within a specified precision of the expected value. * @function * @name matchers#toBeCloseTo * @param {Object} expected - The expected value to compare against. * @param {Number} [precision=2] - The number of decimal points to check. * @example * expect(number).toBeCloseTo(42.2, 3); */ function toBeCloseTo() { return { compare: function(actual, expected, precision) { if (precision !== 0) { precision = precision || 2; } if (expected === null || actual === null) { throw new Error('Cannot use toBeCloseTo with null. Arguments evaluated to: ' + 'expect(' + actual + ').toBeCloseTo(' + expected + ').' ); } var pow = Math.pow(10, precision + 1); var delta = Math.abs(expected - actual); var maxDelta = Math.pow(10, -precision) / 2; return { pass: Math.round(delta * pow) / pow <= maxDelta }; } }; } return toBeCloseTo; }; getJasmineRequireObj().toBeDefined = function() { /** * {@link expect} the actual value to be defined. (Not `undefined`) * @function * @name matchers#toBeDefined * @example * expect(result).toBeDefined(); */ function toBeDefined() { return { compare: function(actual) { return { pass: (void 0 !== actual) }; } }; } return toBeDefined; }; getJasmineRequireObj().toBeFalsy = function() { /** * {@link expect} the actual value to be falsy * @function * @name matchers#toBeFalsy * @example * expect(result).toBeFalsy(); */ function toBeFalsy() { return { compare: function(actual) { return { pass: !!!actual }; } }; } return toBeFalsy; }; getJasmineRequireObj().toBeGreaterThan = function() { /** * {@link expect} the actual value to be greater than the expected value. * @function * @name matchers#toBeGreaterThan * @param {Number} expected - The value to compare against. * @example * expect(result).toBeGreaterThan(3); */ function toBeGreaterThan() { return { compare: function(actual, expected) { return { pass: actual > expected }; } }; } return toBeGreaterThan; }; getJasmineRequireObj().toBeGreaterThanOrEqual = function() { /** * {@link expect} the actual value to be greater than or equal to the expected value. * @function * @name matchers#toBeGreaterThanOrEqual * @param {Number} expected - The expected value to compare against. * @example * expect(result).toBeGreaterThanOrEqual(25); */ function toBeGreaterThanOrEqual() { return { compare: function(actual, expected) { return { pass: actual >= expected }; } }; } return toBeGreaterThanOrEqual; }; getJasmineRequireObj().toBeLessThan = function() { /** * {@link expect} the actual value to be less than the expected value. * @function * @name matchers#toBeLessThan * @param {Number} expected - The expected value to compare against. * @example * expect(result).toBeLessThan(0); */ function toBeLessThan() { return { compare: function(actual, expected) { return { pass: actual < expected }; } }; } return toBeLessThan; }; getJasmineRequireObj().toBeLessThanOrEqual = function() { /** * {@link expect} the actual value to be less than or equal to the expected value. * @function * @name matchers#toBeLessThanOrEqual * @param {Number} expected - The expected value to compare against. * @example * expect(result).toBeLessThanOrEqual(123); */ function toBeLessThanOrEqual() { return { compare: function(actual, expected) { return { pass: actual <= expected }; } }; } return toBeLessThanOrEqual; }; getJasmineRequireObj().toBeNaN = function(j$) { /** * {@link expect} the actual value to be `NaN` (Not a Number). * @function * @name matchers#toBeNaN * @example * expect(thing).toBeNaN(); */ function toBeNaN() { return { compare: function(actual) { var result = { pass: (actual !== actual) }; if (result.pass) { result.message = 'Expected actual not to be NaN.'; } else { result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; }; } return result; } }; } return toBeNaN; }; getJasmineRequireObj().toBeNegativeInfinity = function(j$) { /** * {@link expect} the actual value to be `-Infinity` (-infinity). * @function * @name matchers#toBeNegativeInfinity * @example * expect(thing).toBeNegativeInfinity(); */ function toBeNegativeInfinity() { return { compare: function(actual) { var result = { pass: (actual === Number.NEGATIVE_INFINITY) }; if (result.pass) { result.message = 'Expected actual to be -Infinity.'; } else { result.message = function() { return 'Expected ' + j$.pp(actual) + ' not to be -Infinity.'; }; } return result; } }; } return toBeNegativeInfinity; }; getJasmineRequireObj().toBeNull = function() { /** * {@link expect} the actual value to be `null`. * @function * @name matchers#toBeNull * @example * expect(result).toBeNull(); */ function toBeNull() { return { compare: function(actual) { return { pass: actual === null }; } }; } return toBeNull; }; getJasmineRequireObj().toBePositiveInfinity = function(j$) { /** * {@link expect} the actual value to be `Infinity` (infinity). * @function * @name matchers#toBePositiveInfinity * @example * expect(thing).toBePositiveInfinity(); */ function toBePositiveInfinity() { return { compare: function(actual) { var result = { pass: (actual === Number.POSITIVE_INFINITY) }; if (result.pass) { result.message = 'Expected actual to be Infinity.'; } else { result.message = function() { return 'Expected ' + j$.pp(actual) + ' not to be Infinity.'; }; } return result; } }; } return toBePositiveInfinity; }; getJasmineRequireObj().toBeTruthy = function() { /** * {@link expect} the actual value to be truthy. * @function * @name matchers#toBeTruthy * @example * expect(thing).toBeTruthy(); */ function toBeTruthy() { return { compare: function(actual) { return { pass: !!actual }; } }; } return toBeTruthy; }; getJasmineRequireObj().toBeUndefined = function() { /** * {@link expect} the actual value to be `undefined`. * @function * @name matchers#toBeUndefined * @example * expect(result).toBeUndefined(): */ function toBeUndefined() { return { compare: function(actual) { return { pass: void 0 === actual }; } }; } return toBeUndefined; }; getJasmineRequireObj().toContain = function() { /** * {@link expect} the actual value to contain a specific value. * @function * @name matchers#toContain * @param {Object} expected - The value to look for. * @example * expect(array).toContain(anElement); * expect(string).toContain(substring); */ function toContain(util, customEqualityTesters) { customEqualityTesters = customEqualityTesters || []; return { compare: function(actual, expected) { return { pass: util.contains(actual, expected, customEqualityTesters) }; } }; } return toContain; }; getJasmineRequireObj().toEqual = function(j$) { /** * {@link expect} the actual value to be equal to the expected, using deep equality comparison. * @function * @name matchers#toEqual * @param {Object} expected - Expected value * @example * expect(bigObject).toEqual({"foo": ['bar', 'baz']}); */ function toEqual(util, customEqualityTesters) { customEqualityTesters = customEqualityTesters || []; return { compare: function(actual, expected) { var result = { pass: false }, diffBuilder = j$.DiffBuilder(); result.pass = util.equals(actual, expected, customEqualityTesters, diffBuilder); // TODO: only set error message if test fails result.message = diffBuilder.getMessage(); return result; } }; } return toEqual; }; getJasmineRequireObj().toHaveBeenCalled = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalled()'); /** * {@link expect} the actual (a {@link Spy}) to have been called. * @function * @name matchers#toHaveBeenCalled * @example * expect(mySpy).toHaveBeenCalled(); * expect(mySpy).not.toHaveBeenCalled(); */ function toHaveBeenCalled() { return { compare: function(actual) { var result = {}; if (!j$.isSpy(actual)) { throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); } if (arguments.length > 1) { throw new Error(getErrorMsg('Does not take arguments, use toHaveBeenCalledWith')); } result.pass = actual.calls.any(); result.message = result.pass ? 'Expected spy ' + actual.and.identity + ' not to have been called.' : 'Expected spy ' + actual.and.identity + ' to have been called.'; return result; } }; } return toHaveBeenCalled; }; getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalledBefore()'); /** * {@link expect} the actual value (a {@link Spy}) to have been called before another {@link Spy}. * @function * @name matchers#toHaveBeenCalledBefore * @param {Spy} expected - {@link Spy} that should have been called after the `actual` {@link Spy}. * @example * expect(mySpy).toHaveBeenCalledBefore(otherSpy); */ function toHaveBeenCalledBefore() { return { compare: function(firstSpy, latterSpy) { if (!j$.isSpy(firstSpy)) { throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(firstSpy) + '.')); } if (!j$.isSpy(latterSpy)) { throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(latterSpy) + '.')); } var result = { pass: false }; if (!firstSpy.calls.count()) { result.message = 'Expected spy ' + firstSpy.and.identity + ' to have been called.'; return result; } if (!latterSpy.calls.count()) { result.message = 'Expected spy ' + latterSpy.and.identity + ' to have been called.'; return result; } var latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; var first2ndSpyCall = latterSpy.calls.first().invocationOrder; result.pass = latest1stSpyCall < first2ndSpyCall; if (result.pass) { result.message = 'Expected spy ' + firstSpy.and.identity + ' to not have been called before spy ' + latterSpy.and.identity + ', but it was'; } else { var first1stSpyCall = firstSpy.calls.first().invocationOrder; var latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; if(first1stSpyCall < first2ndSpyCall) { result.message = 'Expected latest call to spy ' + firstSpy.and.identity + ' to have been called before first call to spy ' + latterSpy.and.identity + ' (no interleaved calls)'; } else if (latest2ndSpyCall > latest1stSpyCall) { result.message = 'Expected first call to spy ' + latterSpy.and.identity + ' to have been called after latest call to spy ' + firstSpy.and.identity + ' (no interleaved calls)'; } else { result.message = 'Expected spy ' + firstSpy.and.identity + ' to have been called before spy ' + latterSpy.and.identity; } } return result; } }; } return toHaveBeenCalledBefore; }; getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalledTimes()'); /** * {@link expect} the actual (a {@link Spy}) to have been called the specified number of times. * @function * @name matchers#toHaveBeenCalledTimes * @param {Number} expected - The number of invocations to look for. * @example * expect(mySpy).toHaveBeenCalledTimes(3); */ function toHaveBeenCalledTimes() { return { compare: function(actual, expected) { if (!j$.isSpy(actual)) { throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); } var args = Array.prototype.slice.call(arguments, 0), result = { pass: false }; if (!j$.isNumber_(expected)){ throw new Error(getErrorMsg('The expected times failed is a required argument and must be a number.')); } actual = args[0]; var calls = actual.calls.count(); var timesMessage = expected === 1 ? 'once' : expected + ' times'; result.pass = calls === expected; result.message = result.pass ? 'Expected spy ' + actual.and.identity + ' not to have been called ' + timesMessage + '. It was called ' + calls + ' times.' : 'Expected spy ' + actual.and.identity + ' to have been called ' + timesMessage + '. It was called ' + calls + ' times.'; return result; } }; } return toHaveBeenCalledTimes; }; getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect().toHaveBeenCalledWith(...arguments)'); /** * {@link expect} the actual (a {@link Spy}) to have been called with particular arguments at least once. * @function * @name matchers#toHaveBeenCalledWith * @param {...Object} - The arguments to look for * @example * expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2); */ function toHaveBeenCalledWith(util, customEqualityTesters) { return { compare: function() { var args = Array.prototype.slice.call(arguments, 0), actual = args[0], expectedArgs = args.slice(1), result = { pass: false }; if (!j$.isSpy(actual)) { throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); } if (!actual.calls.any()) { result.message = function() { return 'Expected spy ' + actual.and.identity + ' to have been called with ' + j$.pp(expectedArgs) + ' but it was never called.'; }; return result; } if (util.contains(actual.calls.allArgs(), expectedArgs, customEqualityTesters)) { result.pass = true; result.message = function() { return 'Expected spy ' + actual.and.identity + ' not to have been called with ' + j$.pp(expectedArgs) + ' but it was.'; }; } else { result.message = function() { return 'Expected spy ' + actual.and.identity + ' to have been called with ' + j$.pp(expectedArgs) + ' but actual calls were ' + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + '.'; }; } return result; } }; } return toHaveBeenCalledWith; }; getJasmineRequireObj().toHaveClass = function(j$) { /** * {@link expect} the actual value to be a DOM element that has the expected class * @function * @name matchers#toHaveClass * @param {Object} expected - The class name to test for * @example * var el = document.createElement('div'); * el.className = 'foo bar baz'; * expect(el).toHaveClass('bar'); */ function toHaveClass(util, customEqualityTesters) { return { compare: function(actual, expected) { if (!isElement(actual)) { throw new Error(j$.pp(actual) + ' is not a DOM element'); } return { pass: actual.classList.contains(expected) }; } }; } function isElement(maybeEl) { return maybeEl && maybeEl.classList && j$.isFunction_(maybeEl.classList.contains); } return toHaveClass; }; getJasmineRequireObj().toMatch = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect().toMatch( || )'); /** * {@link expect} the actual value to match a regular expression * @function * @name matchers#toMatch * @param {RegExp|String} expected - Value to look for in the string. * @example * expect("my string").toMatch(/string$/); * expect("other string").toMatch("her"); */ function toMatch() { return { compare: function(actual, expected) { if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { throw new Error(getErrorMsg('Expected is not a String or a RegExp')); } var regexp = new RegExp(expected); return { pass: regexp.test(actual) }; } }; } return toMatch; }; getJasmineRequireObj().toThrow = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect(function() {}).toThrow()'); /** * {@link expect} a function to `throw` something. * @function * @name matchers#toThrow * @param {Object} [expected] - Value that should be thrown. If not provided, simply the fact that something was thrown will be checked. * @example * expect(function() { return 'things'; }).toThrow('foo'); * expect(function() { return 'stuff'; }).toThrow(); */ function toThrow(util) { return { compare: function(actual, expected) { var result = { pass: false }, threw = false, thrown; if (typeof actual != 'function') { throw new Error(getErrorMsg('Actual is not a Function')); } try { actual(); } catch (e) { threw = true; thrown = e; } if (!threw) { result.message = 'Expected function to throw an exception.'; return result; } if (arguments.length == 1) { result.pass = true; result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; }; return result; } if (util.equals(thrown, expected)) { result.pass = true; result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; }; } else { result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; }; } return result; } }; } return toThrow; }; getJasmineRequireObj().toThrowError = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'expect(function() {}).toThrowError(, )'); /** * {@link expect} a function to `throw` an `Error`. * @function * @name matchers#toThrowError * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` * @example * expect(function() { return 'things'; }).toThrowError(MyCustomError, 'message'); * expect(function() { return 'things'; }).toThrowError(MyCustomError, /bar/); * expect(function() { return 'stuff'; }).toThrowError(MyCustomError); * expect(function() { return 'other'; }).toThrowError(/foo/); * expect(function() { return 'other'; }).toThrowError(); */ function toThrowError () { return { compare: function(actual) { var errorMatcher = getMatcher.apply(null, arguments), thrown; if (typeof actual != 'function') { throw new Error(getErrorMsg('Actual is not a Function')); } try { actual(); return fail('Expected function to throw an Error.'); } catch (e) { thrown = e; } if (!j$.isError_(thrown)) { return fail(function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; }); } return errorMatcher.match(thrown); } }; function getMatcher() { var expected, errorType; if (arguments[2]) { errorType = arguments[1]; expected = arguments[2]; if (!isAnErrorType(errorType)) { throw new Error(getErrorMsg('Expected error type is not an Error.')); } return exactMatcher(expected, errorType); } else if (arguments[1]) { expected = arguments[1]; if (isAnErrorType(arguments[1])) { return exactMatcher(null, arguments[1]); } else { return exactMatcher(arguments[1], null); } } else { return anyMatcher(); } } function anyMatcher() { return { match: function(error) { return pass('Expected function not to throw an Error, but it threw ' + j$.fnNameFor(error) + '.'); } }; } function exactMatcher(expected, errorType) { if (expected && !isStringOrRegExp(expected)) { if (errorType) { throw new Error(getErrorMsg('Expected error message is not a string or RegExp.')); } else { throw new Error(getErrorMsg('Expected is not an Error, string, or RegExp.')); } } function messageMatch(message) { if (typeof expected == 'string') { return expected == message; } else { return expected.test(message); } } var errorTypeDescription = errorType ? j$.fnNameFor(errorType) : 'an exception'; function thrownDescription(thrown) { var thrownName = errorType ? j$.fnNameFor(thrown.constructor) : 'an exception', thrownMessage = ''; if (expected) { thrownMessage = ' with message ' + j$.pp(thrown.message); } return thrownName + thrownMessage; } function messageDescription() { if (expected === null) { return ''; } else if (expected instanceof RegExp) { return ' with a message matching ' + j$.pp(expected); } else { return ' with message ' + j$.pp(expected); } } function matches(error) { return (errorType === null || error instanceof errorType) && (expected === null || messageMatch(error.message)); } return { match: function(thrown) { if (matches(thrown)) { return pass(function() { return 'Expected function not to throw ' + errorTypeDescription + messageDescription() + '.'; }); } else { return fail(function() { return 'Expected function to throw ' + errorTypeDescription + messageDescription() + ', but it threw ' + thrownDescription(thrown) + '.'; }); } } }; } function isStringOrRegExp(potential) { return potential instanceof RegExp || (typeof potential == 'string'); } function isAnErrorType(type) { if (typeof type !== 'function') { return false; } var Surrogate = function() {}; Surrogate.prototype = type.prototype; return j$.isError_(new Surrogate()); } } function pass(message) { return { pass: true, message: message }; } function fail(message) { return { pass: false, message: message }; } return toThrowError; }; getJasmineRequireObj().toThrowMatching = function(j$) { var usageError = j$.formatErrorMsg('', 'expect(function() {}).toThrowMatching()'); /** * {@link expect} a function to `throw` something matching a predicate. * @function * @name matchers#toThrowMatching * @param {Function} predicate - A function that takes the thrown exception as its parameter and returns true if it matches. * @example * expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; }); */ function toThrowMatching() { return { compare: function(actual, predicate) { var thrown; if (typeof actual !== 'function') { throw new Error(usageError('Actual is not a Function')); } if (typeof predicate !== 'function') { throw new Error(usageError('Predicate is not a Function')); } try { actual(); return fail('Expected function to throw an exception.'); } catch (e) { thrown = e; } if (predicate(thrown)) { return pass('Expected function not to throw an exception matching a predicate.'); } else { return fail(function() { return 'Expected function to throw an exception matching a predicate, ' + 'but it threw ' + thrownDescription(thrown) + '.'; }); } } }; } function thrownDescription(thrown) { if (thrown && thrown.constructor) { return j$.fnNameFor(thrown.constructor) + ' with message ' + j$.pp(thrown.message); } else { return j$.pp(thrown); } } function pass(message) { return { pass: true, message: message }; } function fail(message) { return { pass: false, message: message }; } return toThrowMatching; }; getJasmineRequireObj().MockDate = function() { function MockDate(global) { var self = this; var currentTime = 0; if (!global || !global.Date) { self.install = function() {}; self.tick = function() {}; self.uninstall = function() {}; return self; } var GlobalDate = global.Date; self.install = function(mockDate) { if (mockDate instanceof GlobalDate) { currentTime = mockDate.getTime(); } else { currentTime = new GlobalDate().getTime(); } global.Date = FakeDate; }; self.tick = function(millis) { millis = millis || 0; currentTime = currentTime + millis; }; self.uninstall = function() { currentTime = 0; global.Date = GlobalDate; }; createDateProperties(); return self; function FakeDate() { switch(arguments.length) { case 0: return new GlobalDate(currentTime); case 1: return new GlobalDate(arguments[0]); case 2: return new GlobalDate(arguments[0], arguments[1]); case 3: return new GlobalDate(arguments[0], arguments[1], arguments[2]); case 4: return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]); case 5: return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); case 6: return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); default: return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]); } } function createDateProperties() { FakeDate.prototype = GlobalDate.prototype; FakeDate.now = function() { if (GlobalDate.now) { return currentTime; } else { throw new Error('Browser does not support Date.now()'); } }; FakeDate.toSource = GlobalDate.toSource; FakeDate.toString = GlobalDate.toString; FakeDate.parse = GlobalDate.parse; FakeDate.UTC = GlobalDate.UTC; } } return MockDate; }; getJasmineRequireObj().pp = function(j$) { function PrettyPrinter() { this.ppNestLevel_ = 0; this.seen = []; this.length = 0; this.stringParts = []; } function hasCustomToString(value) { // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. // iframe, web worker) return j$.isFunction_(value.toString) && value.toString !== Object.prototype.toString && (value.toString() !== Object.prototype.toString.call(value)); } PrettyPrinter.prototype.format = function(value) { this.ppNestLevel_++; try { if (j$.util.isUndefined(value)) { this.emitScalar('undefined'); } else if (value === null) { this.emitScalar('null'); } else if (value === 0 && 1/value === -Infinity) { this.emitScalar('-0'); } else if (value === j$.getGlobal()) { this.emitScalar(''); } else if (value.jasmineToString) { this.emitScalar(value.jasmineToString()); } else if (typeof value === 'string') { this.emitString(value); } else if (j$.isSpy(value)) { this.emitScalar('spy on ' + value.and.identity); } else if (value instanceof RegExp) { this.emitScalar(value.toString()); } else if (typeof value === 'function') { this.emitScalar('Function'); } else if (j$.isDomNode(value)) { if (value.tagName) { this.emitDomElement(value); } else { this.emitScalar('HTMLNode'); } } else if (value instanceof Date) { this.emitScalar('Date(' + value + ')'); } else if (j$.isSet(value)) { this.emitSet(value); } else if (j$.isMap(value)) { this.emitMap(value); } else if (j$.isTypedArray_(value)) { this.emitTypedArray(value); } else if (value.toString && typeof value === 'object' && !j$.isArray_(value) && hasCustomToString(value)) { this.emitScalar(value.toString()); } else if (j$.util.arrayContains(this.seen, value)) { this.emitScalar(''); } else if (j$.isArray_(value) || j$.isA_('Object', value)) { this.seen.push(value); if (j$.isArray_(value)) { this.emitArray(value); } else { this.emitObject(value); } this.seen.pop(); } else { this.emitScalar(value.toString()); } } catch (e) { if (this.ppNestLevel_ > 1 || !(e instanceof MaxCharsReachedError)) { throw e; } } finally { this.ppNestLevel_--; } }; PrettyPrinter.prototype.iterateObject = function(obj, fn) { var objKeys = keys(obj, j$.isArray_(obj)); var isGetter = function isGetter(prop) {}; if (obj.__lookupGetter__) { isGetter = function isGetter(prop) { var getter = obj.__lookupGetter__(prop); return !j$.util.isUndefined(getter) && getter !== null; }; } var length = Math.min(objKeys.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); for (var i = 0; i < length; i++) { var property = objKeys[i]; fn(property, isGetter(property)); } return objKeys.length > length; }; PrettyPrinter.prototype.emitScalar = function(value) { this.append(value); }; PrettyPrinter.prototype.emitString = function(value) { this.append('\'' + value + '\''); }; PrettyPrinter.prototype.emitArray = function(array) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { this.append('Array'); return; } var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); this.append('[ '); for (var i = 0; i < length; i++) { if (i > 0) { this.append(', '); } this.format(array[i]); } if(array.length > length){ this.append(', ...'); } var self = this; var first = array.length === 0; var truncated = this.iterateObject(array, function(property, isGetter) { if (first) { first = false; } else { self.append(', '); } self.formatProperty(array, property, isGetter); }); if (truncated) { this.append(', ...'); } this.append(' ]'); }; PrettyPrinter.prototype.emitSet = function(set) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { this.append('Set'); return; } this.append('Set( '); var size = Math.min(set.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); var i = 0; set.forEach( function( value, key ) { if (i >= size) { return; } if (i > 0) { this.append(', '); } this.format(value); i++; }, this ); if (set.size > size){ this.append(', ...'); } this.append(' )'); }; PrettyPrinter.prototype.emitMap = function(map) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { this.append('Map'); return; } this.append('Map( '); var size = Math.min(map.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); var i = 0; map.forEach( function( value, key ) { if (i >= size) { return; } if (i > 0) { this.append(', '); } this.format([key,value]); i++; }, this ); if (map.size > size){ this.append(', ...'); } this.append(' )'); }; PrettyPrinter.prototype.emitObject = function(obj) { var ctor = obj.constructor, constructorName; constructorName = typeof ctor === 'function' && obj instanceof ctor ? j$.fnNameFor(obj.constructor) : 'null'; this.append(constructorName); if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { return; } var self = this; this.append('({ '); var first = true; var truncated = this.iterateObject(obj, function(property, isGetter) { if (first) { first = false; } else { self.append(', '); } self.formatProperty(obj, property, isGetter); }); if (truncated) { this.append(', ...'); } this.append(' })'); }; PrettyPrinter.prototype.emitTypedArray = function(arr) { var constructorName = j$.fnNameFor(arr.constructor), limitedArray = Array.prototype.slice.call(arr, 0, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH), itemsString = Array.prototype.join.call(limitedArray, ', '); if (limitedArray.length !== arr.length) { itemsString += ', ...'; } this.append(constructorName + ' [ ' + itemsString + ' ]'); }; PrettyPrinter.prototype.emitDomElement = function(el) { var tagName = el.tagName.toLowerCase(), attrs = el.attributes, i, len = attrs.length, out = '<' + tagName, attr; for (i = 0; i < len; i++) { attr = attrs[i]; out += ' ' + attr.name; if (attr.value !== '') { out += '="' + attr.value + '"'; } } out += '>'; if (el.childElementCount !== 0 || el.textContent !== '') { out += '...'; } this.append(out); }; PrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) { this.append(property); this.append(': '); if (isGetter) { this.append(''); } else { this.format(obj[property]); } }; PrettyPrinter.prototype.append = function(value) { var result = truncate(value, j$.MAX_PRETTY_PRINT_CHARS - this.length); this.length += result.value.length; this.stringParts.push(result.value); if (result.truncated) { throw new MaxCharsReachedError(); } }; function truncate(s, maxlen) { if (s.length <= maxlen) { return { value: s, truncated: false }; } s = s.substring(0, maxlen - 4) + ' ...'; return { value: s, truncated: true }; } function MaxCharsReachedError() { this.message = 'Exceeded ' + j$.MAX_PRETTY_PRINT_CHARS + ' characters while pretty-printing a value'; } MaxCharsReachedError.prototype = new Error(); function keys(obj, isArray) { var allKeys = Object.keys ? Object.keys(obj) : (function(o) { var keys = []; for (var key in o) { if (j$.util.has(o, key)) { keys.push(key); } } return keys; })(obj); if (!isArray) { return allKeys; } if (allKeys.length === 0) { return allKeys; } var extraKeys = []; for (var i = 0; i < allKeys.length; i++) { if (!/^[0-9]+$/.test(allKeys[i])) { extraKeys.push(allKeys[i]); } } return extraKeys; } return function(value) { var prettyPrinter = new PrettyPrinter(); prettyPrinter.format(value); return prettyPrinter.stringParts.join(''); }; }; getJasmineRequireObj().QueueRunner = function(j$) { function StopExecutionError() {} StopExecutionError.prototype = new Error(); j$.StopExecutionError = StopExecutionError; function once(fn) { var called = false; return function(arg) { if (!called) { called = true; // Direct call using single parameter, because cleanup/next does not need more fn(arg); } return null; }; } function emptyFn() {} function QueueRunner(attrs) { var queueableFns = attrs.queueableFns || []; this.queueableFns = queueableFns.concat(attrs.cleanupFns || []); this.firstCleanupIx = queueableFns.length; this.onComplete = attrs.onComplete || emptyFn; this.clearStack = attrs.clearStack || function(fn) {fn();}; this.onException = attrs.onException || emptyFn; this.userContext = attrs.userContext || new j$.UserContext(); this.timeout = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout}; this.fail = attrs.fail || emptyFn; this.globalErrors = attrs.globalErrors || { pushListener: emptyFn, popListener: emptyFn }; this.completeOnFirstError = !!attrs.completeOnFirstError; this.errored = false; if (typeof(this.onComplete) !== 'function') { throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); } this.deprecated = attrs.deprecated; } QueueRunner.prototype.execute = function() { var self = this; this.handleFinalError = function(error) { self.onException(error); }; this.globalErrors.pushListener(this.handleFinalError); this.run(0); }; QueueRunner.prototype.skipToCleanup = function(lastRanIndex) { if (lastRanIndex < this.firstCleanupIx) { this.run(this.firstCleanupIx); } else { this.run(lastRanIndex + 1); } }; QueueRunner.prototype.clearTimeout = function(timeoutId) { Function.prototype.apply.apply(this.timeout.clearTimeout, [j$.getGlobal(), [timeoutId]]); }; QueueRunner.prototype.setTimeout = function(fn, timeout) { return Function.prototype.apply.apply(this.timeout.setTimeout, [j$.getGlobal(), [fn, timeout]]); }; QueueRunner.prototype.attempt = function attempt(iterativeIndex) { var self = this, completedSynchronously = true, handleError = function handleError(error) { onException(error); next(error); }, cleanup = once(function cleanup() { if (timeoutId !== void 0) { self.clearTimeout(timeoutId); } self.globalErrors.popListener(handleError); }), next = once(function next(err) { cleanup(); if (j$.isError_(err)) { if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { self.fail(err); } self.errored = errored = true; } function runNext() { if (self.completeOnFirstError && errored) { self.skipToCleanup(iterativeIndex); } else { self.run(iterativeIndex + 1); } } if (completedSynchronously) { self.setTimeout(runNext); } else { runNext(); } }), errored = false, queueableFn = self.queueableFns[iterativeIndex], timeoutId; next.fail = function nextFail() { self.fail.apply(null, arguments); self.errored = errored = true; next(); }; self.globalErrors.pushListener(handleError); if (queueableFn.timeout !== undefined) { var timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; timeoutId = self.setTimeout(function() { var error = new Error( 'Timeout - Async callback was not invoked within ' + timeoutInterval + 'ms ' + (queueableFn.timeout ? '(custom timeout)' : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') ); onException(error); next(); }, timeoutInterval); } try { if (queueableFn.fn.length === 0) { var maybeThenable = queueableFn.fn.call(self.userContext); if (maybeThenable && j$.isFunction_(maybeThenable.then)) { maybeThenable.then(next, onPromiseRejection); completedSynchronously = false; return { completedSynchronously: false }; } } else { queueableFn.fn.call(self.userContext, next); completedSynchronously = false; return { completedSynchronously: false }; } } catch (e) { onException(e); self.errored = errored = true; } cleanup(); return { completedSynchronously: true, errored: errored }; function onException(e) { self.onException(e); self.errored = errored = true; } function onPromiseRejection(e) { onException(e); next(); } }; QueueRunner.prototype.run = function(recursiveIndex) { var length = this.queueableFns.length, self = this, iterativeIndex; for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { var result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { return; } self.errored = self.errored || result.errored; if (this.completeOnFirstError && result.errored) { this.skipToCleanup(iterativeIndex); return; } } this.clearStack(function() { self.globalErrors.popListener(self.handleFinalError); self.onComplete(self.errored && new StopExecutionError()); }); }; return QueueRunner; }; getJasmineRequireObj().ReportDispatcher = function(j$) { function ReportDispatcher(methods, queueRunnerFactory) { var dispatchedMethods = methods || []; for (var i = 0; i < dispatchedMethods.length; i++) { var method = dispatchedMethods[i]; this[method] = (function(m) { return function() { dispatch(m, arguments); }; }(method)); } var reporters = []; var fallbackReporter = null; this.addReporter = function(reporter) { reporters.push(reporter); }; this.provideFallbackReporter = function(reporter) { fallbackReporter = reporter; }; this.clearReporters = function() { reporters = []; }; return this; function dispatch(method, args) { if (reporters.length === 0 && fallbackReporter !== null) { reporters.push(fallbackReporter); } var onComplete = args[args.length - 1]; args = j$.util.argsToArray(args).splice(0, args.length - 1); var fns = []; for (var i = 0; i < reporters.length; i++) { var reporter = reporters[i]; addFn(fns, reporter, method, args); } queueRunnerFactory({ queueableFns: fns, onComplete: onComplete, isReporter: true }); } function addFn(fns, reporter, method, args) { var fn = reporter[method]; if (!fn) { return; } var thisArgs = j$.util.cloneArgs(args); if (fn.length <= 1) { fns.push({ fn: function () { return fn.apply(reporter, thisArgs); } }); } else { fns.push({ fn: function (done) { return fn.apply(reporter, thisArgs.concat([done])); } }); } } } return ReportDispatcher; }; getJasmineRequireObj().interface = function(jasmine, env) { var jasmineInterface = { /** * Callback passed to parts of the Jasmine base interface. * * By default Jasmine assumes this function completes synchronously. * If you have code that you need to test asynchronously, you can declare that you receive a `done` callback, return a Promise, or use the `async` keyword if it is supported in your environment. * @callback implementationCallback * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. */ /** * Create a group of specs (often called a suite). * * Calls to `describe` can be nested within other calls to compose your suite as a tree. * @name describe * @function * @global * @param {String} description Textual description of the group * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs */ describe: function(description, specDefinitions) { return env.describe(description, specDefinitions); }, /** * A temporarily disabled [`describe`]{@link describe} * * Specs within an `xdescribe` will be marked pending and not executed * @name xdescribe * @function * @global * @param {String} description Textual description of the group * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs */ xdescribe: function(description, specDefinitions) { return env.xdescribe(description, specDefinitions); }, /** * A focused [`describe`]{@link describe} * * If suites or specs are focused, only those that are focused will be executed * @see fit * @name fdescribe * @function * @global * @param {String} description Textual description of the group * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs */ fdescribe: function(description, specDefinitions) { return env.fdescribe(description, specDefinitions); }, /** * Define a single spec. A spec should contain one or more {@link expect|expectations} that test the state of the code. * * A spec whose expectations all succeed will be passing and a spec with any failures will fail. * @name it * @function * @global * @param {String} description Textual description of what this spec is checking * @param {implementationCallback} [testFunction] Function that contains the code of your test. If not provided the test will be `pending`. * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. * @see async */ it: function() { return env.it.apply(env, arguments); }, /** * A temporarily disabled [`it`]{@link it} * * The spec will report as `pending` and will not be executed. * @name xit * @function * @global * @param {String} description Textual description of what this spec is checking. * @param {implementationCallback} [testFunction] Function that contains the code of your test. Will not be executed. */ xit: function() { return env.xit.apply(env, arguments); }, /** * A focused [`it`]{@link it} * * If suites or specs are focused, only those that are focused will be executed. * @name fit * @function * @global * @param {String} description Textual description of what this spec is checking. * @param {implementationCallback} testFunction Function that contains the code of your test. * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. * @see async */ fit: function() { return env.fit.apply(env, arguments); }, /** * Run some shared setup before each of the specs in the {@link describe} in which it is called. * @name beforeEach * @function * @global * @param {implementationCallback} [function] Function that contains the code to setup your specs. * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeEach. * @see async */ beforeEach: function() { return env.beforeEach.apply(env, arguments); }, /** * Run some shared teardown after each of the specs in the {@link describe} in which it is called. * @name afterEach * @function * @global * @param {implementationCallback} [function] Function that contains the code to teardown your specs. * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterEach. * @see async */ afterEach: function() { return env.afterEach.apply(env, arguments); }, /** * Run some shared setup once before all of the specs in the {@link describe} are run. * * _Note:_ Be careful, sharing the setup from a beforeAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. * @name beforeAll * @function * @global * @param {implementationCallback} [function] Function that contains the code to setup your specs. * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeAll. * @see async */ beforeAll: function() { return env.beforeAll.apply(env, arguments); }, /** * Run some shared teardown once after all of the specs in the {@link describe} are run. * * _Note:_ Be careful, sharing the teardown from a afterAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. * @name afterAll * @function * @global * @param {implementationCallback} [function] Function that contains the code to teardown your specs. * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterAll. * @see async */ afterAll: function() { return env.afterAll.apply(env, arguments); }, /** * Create an expectation for a spec. * @name expect * @function * @global * @param {Object} actual - Actual computed value to test expectations against. * @return {matchers} */ expect: function(actual) { return env.expect(actual); }, /** * Create an asynchronous expectation for a spec. Note that the matchers * that are provided by an asynchronous expectation all return promises * which must be either returned from the spec or waited for using `await` * in order for Jasmine to associate them with the correct spec. * @name expectAsync * @function * @global * @param {Object} actual - Actual computed value to test expectations against. * @return {async-matchers} * @example * await expectAsync(somePromise).toBeResolved(); * @example * return expectAsync(somePromise).toBeResolved(); */ expectAsync: function(actual) { return env.expectAsync(actual); }, /** * Mark a spec as pending, expectation results will be ignored. * @name pending * @function * @global * @param {String} [message] - Reason the spec is pending. */ pending: function() { return env.pending.apply(env, arguments); }, /** * Explicitly mark a spec as failed. * @name fail * @function * @global * @param {String|Error} [error] - Reason for the failure. */ fail: function() { return env.fail.apply(env, arguments); }, /** * Install a spy onto an existing object. * @name spyOn * @function * @global * @param {Object} obj - The object upon which to install the {@link Spy}. * @param {String} methodName - The name of the method to replace with a {@link Spy}. * @returns {Spy} */ spyOn: function(obj, methodName) { return env.spyOn(obj, methodName); }, /** * Install a spy on a property installed with `Object.defineProperty` onto an existing object. * @name spyOnProperty * @function * @global * @param {Object} obj - The object upon which to install the {@link Spy} * @param {String} propertyName - The name of the property to replace with a {@link Spy}. * @param {String} [accessType=get] - The access type (get|set) of the property to {@link Spy} on. * @returns {Spy} */ spyOnProperty: function(obj, methodName, accessType) { return env.spyOnProperty(obj, methodName, accessType); }, /** * Installs spies on all writable and configurable properties of an object. * @name spyOnAllFunctions * @function * @global * @param {Object} obj - The object upon which to install the {@link Spy}s * @returns {Object} the spied object */ spyOnAllFunctions: function(obj) { return env.spyOnAllFunctions(obj); }, jsApiReporter: new jasmine.JsApiReporter({ timer: new jasmine.Timer() }), /** * @namespace jasmine */ jasmine: jasmine }; /** * Add a custom equality tester for the current scope of specs. * * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. * @name jasmine.addCustomEqualityTester * @function * @param {Function} tester - A function which takes two arguments to compare and returns a `true` or `false` comparison result if it knows how to compare them, and `undefined` otherwise. * @see custom_equality */ jasmine.addCustomEqualityTester = function(tester) { env.addCustomEqualityTester(tester); }; /** * Add custom matchers for the current scope of specs. * * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. * @name jasmine.addMatchers * @function * @param {Object} matchers - Keys from this object will be the new matcher names. * @see custom_matcher */ jasmine.addMatchers = function(matchers) { return env.addMatchers(matchers); }; /** * Get the currently booted mock {Clock} for this Jasmine environment. * @name jasmine.clock * @function * @returns {Clock} */ jasmine.clock = function() { return env.clock; }; /** * Create a bare {@link Spy} object. This won't be installed anywhere and will not have any implementation behind it. * @name jasmine.createSpy * @function * @param {String} [name] - Name to give the spy. This will be displayed in failure messages. * @param {Function} [originalFn] - Function to act as the real implementation. * @return {Spy} */ jasmine.createSpy = function(name, originalFn) { return env.createSpy(name, originalFn); }; /** * Create an object with multiple {@link Spy}s as its members. * @name jasmine.createSpyObj * @function * @param {String} [baseName] - Base name for the spies in the object. * @param {String[]|Object} methodNames - Array of method names to create spies for, or Object whose keys will be method names and values the {@link Spy#and#returnValue|returnValue}. * @return {Object} */ jasmine.createSpyObj = function(baseName, methodNames) { return env.createSpyObj(baseName, methodNames); }; /** * Add a custom spy strategy for the current scope of specs. * * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. * @name jasmine.addSpyStrategy * @function * @param {String} name - The name of the strategy (i.e. what you call from `and`) * @param {Function} factory - Factory function that returns the plan to be executed. */ jasmine.addSpyStrategy = function(name, factory) { return env.addSpyStrategy(name, factory); }; return jasmineInterface; }; getJasmineRequireObj().Spy = function (j$) { var nextOrder = (function() { var order = 0; return function() { return order++; }; })(); /** * _Note:_ Do not construct this directly, use {@link spyOn}, {@link spyOnProperty}, {@link jasmine.createSpy}, or {@link jasmine.createSpyObj} * @constructor * @name Spy */ function Spy(name, originalFn, customStrategies) { var numArgs = (typeof originalFn === 'function' ? originalFn.length : 0), wrapper = makeFunc(numArgs, function () { return spy.apply(this, Array.prototype.slice.call(arguments)); }), strategyDispatcher = new SpyStrategyDispatcher({ name: name, fn: originalFn, getSpy: function () { return wrapper; }, customStrategies: customStrategies }), callTracker = new j$.CallTracker(), spy = function () { /** * @name Spy.callData * @property {object} object - `this` context for the invocation. * @property {number} invocationOrder - Order of the invocation. * @property {Array} args - The arguments passed for this invocation. */ var callData = { object: this, invocationOrder: nextOrder(), args: Array.prototype.slice.apply(arguments) }; callTracker.track(callData); var returnValue = strategyDispatcher.exec(this, arguments); callData.returnValue = returnValue; return returnValue; }; function makeFunc(length, fn) { switch (length) { case 1 : return function (a) { return fn.apply(this, arguments); }; case 2 : return function (a,b) { return fn.apply(this, arguments); }; case 3 : return function (a,b,c) { return fn.apply(this, arguments); }; case 4 : return function (a,b,c,d) { return fn.apply(this, arguments); }; case 5 : return function (a,b,c,d,e) { return fn.apply(this, arguments); }; case 6 : return function (a,b,c,d,e,f) { return fn.apply(this, arguments); }; case 7 : return function (a,b,c,d,e,f,g) { return fn.apply(this, arguments); }; case 8 : return function (a,b,c,d,e,f,g,h) { return fn.apply(this, arguments); }; case 9 : return function (a,b,c,d,e,f,g,h,i) { return fn.apply(this, arguments); }; default : return function () { return fn.apply(this, arguments); }; } } for (var prop in originalFn) { if (prop === 'and' || prop === 'calls') { throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon'); } wrapper[prop] = originalFn[prop]; } /** * @member {SpyStrategy} - Accesses the default strategy for the spy. This strategy will be used * whenever the spy is called with arguments that don't match any strategy * created with {@link Spy#withArgs}. * @name Spy#and * @example * spyOn(someObj, 'func').and.returnValue(42); */ wrapper.and = strategyDispatcher.and; /** * Specifies a strategy to be used for calls to the spy that have the * specified arguments. * @name Spy#withArgs * @function * @param {...*} args - The arguments to match * @type {SpyStrategy} * @example * spyOn(someObj, 'func').withArgs(1, 2, 3).and.returnValue(42); * someObj.func(1, 2, 3); // returns 42 */ wrapper.withArgs = function() { return strategyDispatcher.withArgs.apply(strategyDispatcher, arguments); }; wrapper.calls = callTracker; return wrapper; } function SpyStrategyDispatcher(strategyArgs) { var baseStrategy = new j$.SpyStrategy(strategyArgs); var argsStrategies = new StrategyDict(function() { return new j$.SpyStrategy(strategyArgs); }); this.and = baseStrategy; this.exec = function(spy, args) { var strategy = argsStrategies.get(args); if (!strategy) { if (argsStrategies.any() && !baseStrategy.isConfigured()) { throw new Error('Spy \'' + strategyArgs.name + '\' received a call with arguments ' + j$.pp(Array.prototype.slice.call(args)) + ' but all configured strategies specify other arguments.'); } else { strategy = baseStrategy; } } return strategy.exec(spy, args); }; this.withArgs = function() { return { and: argsStrategies.getOrCreate(arguments) }; }; } function StrategyDict(strategyFactory) { this.strategies = []; this.strategyFactory = strategyFactory; } StrategyDict.prototype.any = function() { return this.strategies.length > 0; }; StrategyDict.prototype.getOrCreate = function(args) { var strategy = this.get(args); if (!strategy) { strategy = this.strategyFactory(); this.strategies.push({ args: args, strategy: strategy }); } return strategy; }; StrategyDict.prototype.get = function(args) { var i; for (i = 0; i < this.strategies.length; i++) { if (j$.matchersUtil.equals(args, this.strategies[i].args)) { return this.strategies[i].strategy; } } }; return Spy; }; getJasmineRequireObj().SpyFactory = function(j$) { function SpyFactory(getCustomStrategies) { var self = this; this.createSpy = function(name, originalFn) { return j$.Spy(name, originalFn, getCustomStrategies()); }; this.createSpyObj = function(baseName, methodNames) { var baseNameIsCollection = j$.isObject_(baseName) || j$.isArray_(baseName); if (baseNameIsCollection && j$.util.isUndefined(methodNames)) { methodNames = baseName; baseName = 'unknown'; } var obj = {}; var spiesWereSet = false; if (j$.isArray_(methodNames)) { for (var i = 0; i < methodNames.length; i++) { obj[methodNames[i]] = self.createSpy(baseName + '.' + methodNames[i]); spiesWereSet = true; } } else if (j$.isObject_(methodNames)) { for (var key in methodNames) { if (methodNames.hasOwnProperty(key)) { obj[key] = self.createSpy(baseName + '.' + key); obj[key].and.returnValue(methodNames[key]); spiesWereSet = true; } } } if (!spiesWereSet) { throw 'createSpyObj requires a non-empty array or object of method names to create spies for'; } return obj; }; } return SpyFactory; }; getJasmineRequireObj().SpyRegistry = function(j$) { var getErrorMsg = j$.formatErrorMsg('', 'spyOn(, )'); function SpyRegistry(options) { options = options || {}; var global = options.global || j$.getGlobal(); var createSpy = options.createSpy; var currentSpies = options.currentSpies || function() { return []; }; this.allowRespy = function(allow){ this.respy = allow; }; this.spyOn = function(obj, methodName) { if (j$.util.isUndefined(obj) || obj === null) { throw new Error(getErrorMsg('could not find an object to spy upon for ' + methodName + '()')); } if (j$.util.isUndefined(methodName) || methodName === null) { throw new Error(getErrorMsg('No method name supplied')); } if (j$.util.isUndefined(obj[methodName])) { throw new Error(getErrorMsg(methodName + '() method does not exist')); } if (obj[methodName] && j$.isSpy(obj[methodName]) ) { if ( !!this.respy ){ return obj[methodName]; }else { throw new Error(getErrorMsg(methodName + ' has already been spied upon')); } } var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); if (descriptor && !(descriptor.writable || descriptor.set)) { throw new Error(getErrorMsg(methodName + ' is not declared writable or has no setter')); } var originalMethod = obj[methodName], spiedMethod = createSpy(methodName, originalMethod), restoreStrategy; if (Object.prototype.hasOwnProperty.call(obj, methodName) || (obj === global && methodName === 'onerror')) { restoreStrategy = function() { obj[methodName] = originalMethod; }; } else { restoreStrategy = function() { if (!delete obj[methodName]) { obj[methodName] = originalMethod; } }; } currentSpies().push({ restoreObjectToOriginalState: restoreStrategy }); obj[methodName] = spiedMethod; return spiedMethod; }; this.spyOnProperty = function (obj, propertyName, accessType) { accessType = accessType || 'get'; if (j$.util.isUndefined(obj)) { throw new Error('spyOn could not find an object to spy upon for ' + propertyName + ''); } if (j$.util.isUndefined(propertyName)) { throw new Error('No property name supplied'); } var descriptor = j$.util.getPropertyDescriptor(obj, propertyName); if (!descriptor) { throw new Error(propertyName + ' property does not exist'); } if (!descriptor.configurable) { throw new Error(propertyName + ' is not declared configurable'); } if(!descriptor[accessType]) { throw new Error('Property ' + propertyName + ' does not have access type ' + accessType); } if (j$.isSpy(descriptor[accessType])) { //TODO?: should this return the current spy? Downside: may cause user confusion about spy state throw new Error(propertyName + ' has already been spied upon'); } var originalDescriptor = j$.util.clone(descriptor), spy = createSpy(propertyName, descriptor[accessType]), restoreStrategy; if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { restoreStrategy = function() { Object.defineProperty(obj, propertyName, originalDescriptor); }; } else { restoreStrategy = function() { delete obj[propertyName]; }; } currentSpies().push({ restoreObjectToOriginalState: restoreStrategy }); descriptor[accessType] = spy; Object.defineProperty(obj, propertyName, descriptor); return spy; }; this.spyOnAllFunctions = function(obj) { if (j$.util.isUndefined(obj)) { throw new Error('spyOnAllFunctions could not find an object to spy upon'); } for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop) && obj[prop] instanceof Function) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); if ((descriptor.writable || descriptor.set) && descriptor.configurable) { this.spyOn(obj, prop); } } } return obj; }; this.clearSpies = function() { var spies = currentSpies(); for (var i = spies.length - 1; i >= 0; i--) { var spyEntry = spies[i]; spyEntry.restoreObjectToOriginalState(); } }; } return SpyRegistry; }; getJasmineRequireObj().SpyStrategy = function(j$) { /** * @interface SpyStrategy */ function SpyStrategy(options) { options = options || {}; /** * Get the identifying information for the spy. * @name SpyStrategy#identity * @member * @type {String} */ this.identity = options.name || 'unknown'; this.originalFn = options.fn || function() {}; this.getSpy = options.getSpy || function() {}; this.plan = this._defaultPlan = function() {}; var k, cs = options.customStrategies || {}; for (k in cs) { if (j$.util.has(cs, k) && !this[k]) { this[k] = createCustomPlan(cs[k]); } } } function createCustomPlan(factory) { return function() { var plan = factory.apply(null, arguments); if (!j$.isFunction_(plan)) { throw new Error('Spy strategy must return a function'); } this.plan = plan; return this.getSpy(); }; } /** * Execute the current spy strategy. * @name SpyStrategy#exec * @function */ SpyStrategy.prototype.exec = function(context, args) { return this.plan.apply(context, args); }; /** * Tell the spy to call through to the real implementation when invoked. * @name SpyStrategy#callThrough * @function */ SpyStrategy.prototype.callThrough = function() { this.plan = this.originalFn; return this.getSpy(); }; /** * Tell the spy to return the value when invoked. * @name SpyStrategy#returnValue * @function * @param {*} value The value to return. */ SpyStrategy.prototype.returnValue = function(value) { this.plan = function() { return value; }; return this.getSpy(); }; /** * Tell the spy to return one of the specified values (sequentially) each time the spy is invoked. * @name SpyStrategy#returnValues * @function * @param {...*} values - Values to be returned on subsequent calls to the spy. */ SpyStrategy.prototype.returnValues = function() { var values = Array.prototype.slice.call(arguments); this.plan = function () { return values.shift(); }; return this.getSpy(); }; /** * Tell the spy to throw an error when invoked. * @name SpyStrategy#throwError * @function * @param {Error|String} something Thing to throw */ SpyStrategy.prototype.throwError = function(something) { var error = (something instanceof Error) ? something : new Error(something); this.plan = function() { throw error; }; return this.getSpy(); }; /** * Tell the spy to call a fake implementation when invoked. * @name SpyStrategy#callFake * @function * @param {Function} fn The function to invoke with the passed parameters. */ SpyStrategy.prototype.callFake = function(fn) { if(!(j$.isFunction_(fn) || j$.isAsyncFunction_(fn))) { throw new Error('Argument passed to callFake should be a function, got ' + fn); } this.plan = fn; return this.getSpy(); }; /** * Tell the spy to do nothing when invoked. This is the default. * @name SpyStrategy#stub * @function */ SpyStrategy.prototype.stub = function(fn) { this.plan = function() {}; return this.getSpy(); }; SpyStrategy.prototype.isConfigured = function() { return this.plan !== this._defaultPlan; }; return SpyStrategy; }; getJasmineRequireObj().StackTrace = function(j$) { function StackTrace(error) { var lines = error.stack .split('\n') .filter(function(line) { return line !== ''; }); var extractResult = extractMessage(error.message, lines); if (extractResult) { this.message = extractResult.message; lines = extractResult.remainder; } var parseResult = tryParseFrames(lines); this.frames = parseResult.frames; this.style = parseResult.style; } var framePatterns = [ // PhantomJS on Linux, Node, Chrome, IE, Edge // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" // Note that the "function name" can include a surprisingly large set of // characters, including angle brackets and square brackets. { re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, fnIx: 1, fileLineColIx: 2, style: 'v8' }, // NodeJS alternate form, often mixed in with the Chrome style // e.g. " at /some/path:4320:20 { re: /\s*at (.+)$/, fileLineColIx: 1, style: 'v8' }, // PhantomJS on OS X, Safari, Firefox // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" { re: /^(([^@\s]+)@)?([^\s]+)$/, fnIx: 2, fileLineColIx: 3, style: 'webkit' } ]; // regexes should capture the function name (if any) as group 1 // and the file, line, and column as group 2. function tryParseFrames(lines) { var style = null; var frames = lines.map(function(line) { var convertedLine = first(framePatterns, function(pattern) { var overallMatch = line.match(pattern.re), fileLineColMatch; if (!overallMatch) { return null; } fileLineColMatch = overallMatch[pattern.fileLineColIx].match( /^(.*):(\d+):\d+$/); if (!fileLineColMatch) { return null; } style = style || pattern.style; return { raw: line, file: fileLineColMatch[1], line: parseInt(fileLineColMatch[2], 10), func: overallMatch[pattern.fnIx] }; }); return convertedLine || { raw: line }; }); return { style: style, frames: frames }; } function first(items, fn) { var i, result; for (i = 0; i < items.length; i++) { result = fn(items[i]); if (result) { return result; } } } function extractMessage(message, stackLines) { var len = messagePrefixLength(message, stackLines); if (len > 0) { return { message: stackLines.slice(0, len).join('\n'), remainder: stackLines.slice(len) }; } } function messagePrefixLength(message, stackLines) { if (!stackLines[0].match(/^Error/)) { return 0; } var messageLines = message.split('\n'); var i; for (i = 1; i < messageLines.length; i++) { if (messageLines[i] !== stackLines[i]) { return 0; } } return messageLines.length; } return StackTrace; }; getJasmineRequireObj().Suite = function(j$) { function Suite(attrs) { this.env = attrs.env; this.id = attrs.id; this.parentSuite = attrs.parentSuite; this.description = attrs.description; this.expectationFactory = attrs.expectationFactory; this.asyncExpectationFactory = attrs.asyncExpectationFactory; this.expectationResultFactory = attrs.expectationResultFactory; this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.beforeFns = []; this.afterFns = []; this.beforeAllFns = []; this.afterAllFns = []; this.timer = attrs.timer || j$.noopTimer; this.children = []; /** * @typedef SuiteResult * @property {Int} id - The unique id of this suite. * @property {String} description - The description text passed to the {@link describe} that made this suite. * @property {String} fullName - The full description including all ancestors of this suite. * @property {Expectation[]} failedExpectations - The list of expectations that failed in an {@link afterAll} for this suite. * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred on this suite. * @property {String} status - Once the suite has completed, this string represents the pass/fail status of this suite. * @property {number} duration - The time in ms for Suite execution, including any before/afterAll, before/afterEach. */ this.result = { id: this.id, description: this.description, fullName: this.getFullName(), failedExpectations: [], deprecationWarnings: [], duration: null, }; } Suite.prototype.expect = function(actual) { return this.expectationFactory(actual, this); }; Suite.prototype.expectAsync = function(actual) { return this.asyncExpectationFactory(actual, this); }; Suite.prototype.getFullName = function() { var fullName = []; for (var parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite) { if (parentSuite.parentSuite) { fullName.unshift(parentSuite.description); } } return fullName.join(' '); }; Suite.prototype.pend = function() { this.markedPending = true; }; Suite.prototype.beforeEach = function(fn) { this.beforeFns.unshift(fn); }; Suite.prototype.beforeAll = function(fn) { this.beforeAllFns.push(fn); }; Suite.prototype.afterEach = function(fn) { this.afterFns.unshift(fn); }; Suite.prototype.afterAll = function(fn) { this.afterAllFns.unshift(fn); }; Suite.prototype.startTimer = function() { this.timer.start(); }; Suite.prototype.endTimer = function() { this.result.duration = this.timer.elapsed(); }; function removeFns(queueableFns) { for(var i = 0; i < queueableFns.length; i++) { queueableFns[i].fn = null; } } Suite.prototype.cleanupBeforeAfter = function() { removeFns(this.beforeAllFns); removeFns(this.afterAllFns); removeFns(this.beforeFns); removeFns(this.afterFns); }; Suite.prototype.addChild = function(child) { this.children.push(child); }; Suite.prototype.status = function() { if (this.markedPending) { return 'pending'; } if (this.result.failedExpectations.length > 0) { return 'failed'; } else { return 'passed'; } }; Suite.prototype.canBeReentered = function() { return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0; }; Suite.prototype.getResult = function() { this.result.status = this.status(); return this.result; }; Suite.prototype.sharedUserContext = function() { if (!this.sharedContext) { this.sharedContext = this.parentSuite ? this.parentSuite.clonedSharedUserContext() : new j$.UserContext(); } return this.sharedContext; }; Suite.prototype.clonedSharedUserContext = function() { return j$.UserContext.fromExisting(this.sharedUserContext()); }; Suite.prototype.onException = function() { if (arguments[0] instanceof j$.errors.ExpectationFailed) { return; } var data = { matcherName: '', passed: false, expected: '', actual: '', error: arguments[0] }; var failedExpectation = this.expectationResultFactory(data); if (!this.parentSuite) { failedExpectation.globalErrorType = 'afterAll'; } this.result.failedExpectations.push(failedExpectation); }; Suite.prototype.addExpectationResult = function () { if(isFailure(arguments)) { var data = arguments[1]; this.result.failedExpectations.push(this.expectationResultFactory(data)); if(this.throwOnExpectationFailure) { throw new j$.errors.ExpectationFailed(); } } }; Suite.prototype.addDeprecationWarning = function(deprecation) { if (typeof deprecation === 'string') { deprecation = { message: deprecation }; } this.result.deprecationWarnings.push(this.expectationResultFactory(deprecation)); }; function isFailure(args) { return !args[0]; } return Suite; }; if (typeof window == void 0 && typeof exports == 'object') { /* globals exports */ exports.Suite = jasmineRequire.Suite; } getJasmineRequireObj().Timer = function() { var defaultNow = (function(Date) { return function() { return new Date().getTime(); }; })(Date); function Timer(options) { options = options || {}; var now = options.now || defaultNow, startTime; this.start = function() { startTime = now(); }; this.elapsed = function() { return now() - startTime; }; } return Timer; }; getJasmineRequireObj().noopTimer = function() { return { start: function() {}, elapsed: function() { return 0; } }; }; getJasmineRequireObj().TreeProcessor = function() { function TreeProcessor(attrs) { var tree = attrs.tree, runnableIds = attrs.runnableIds, queueRunnerFactory = attrs.queueRunnerFactory, nodeStart = attrs.nodeStart || function() {}, nodeComplete = attrs.nodeComplete || function() {}, orderChildren = attrs.orderChildren || function(node) { return node.children; }, excludeNode = attrs.excludeNode || function(node) { return false; }, stats = { valid: true }, processed = false, defaultMin = Infinity, defaultMax = 1 - Infinity; this.processTree = function() { processNode(tree, true); processed = true; return stats; }; this.execute = function(done) { if (!processed) { this.processTree(); } if (!stats.valid) { throw 'invalid order'; } var childFns = wrapChildren(tree, 0); queueRunnerFactory({ queueableFns: childFns, userContext: tree.sharedUserContext(), onException: function() { tree.onException.apply(tree, arguments); }, onComplete: done }); }; function runnableIndex(id) { for (var i = 0; i < runnableIds.length; i++) { if (runnableIds[i] === id) { return i; } } } function processNode(node, parentExcluded) { var executableIndex = runnableIndex(node.id); if (executableIndex !== undefined) { parentExcluded = false; } if (!node.children) { var excluded = parentExcluded || excludeNode(node); stats[node.id] = { excluded: excluded, willExecute: !excluded && !node.markedPending, segments: [{ index: 0, owner: node, nodes: [node], min: startingMin(executableIndex), max: startingMax(executableIndex) }] }; } else { var hasExecutableChild = false; var orderedChildren = orderChildren(node); for (var i = 0; i < orderedChildren.length; i++) { var child = orderedChildren[i]; processNode(child, parentExcluded); if (!stats.valid) { return; } var childStats = stats[child.id]; hasExecutableChild = hasExecutableChild || childStats.willExecute; } stats[node.id] = { excluded: parentExcluded, willExecute: hasExecutableChild }; segmentChildren(node, orderedChildren, stats[node.id], executableIndex); if (!node.canBeReentered() && stats[node.id].segments.length > 1) { stats = { valid: false }; } } } function startingMin(executableIndex) { return executableIndex === undefined ? defaultMin : executableIndex; } function startingMax(executableIndex) { return executableIndex === undefined ? defaultMax : executableIndex; } function segmentChildren(node, orderedChildren, nodeStats, executableIndex) { var currentSegment = { index: 0, owner: node, nodes: [], min: startingMin(executableIndex), max: startingMax(executableIndex) }, result = [currentSegment], lastMax = defaultMax, orderedChildSegments = orderChildSegments(orderedChildren); function isSegmentBoundary(minIndex) { return lastMax !== defaultMax && minIndex !== defaultMin && lastMax < minIndex - 1; } for (var i = 0; i < orderedChildSegments.length; i++) { var childSegment = orderedChildSegments[i], maxIndex = childSegment.max, minIndex = childSegment.min; if (isSegmentBoundary(minIndex)) { currentSegment = {index: result.length, owner: node, nodes: [], min: defaultMin, max: defaultMax}; result.push(currentSegment); } currentSegment.nodes.push(childSegment); currentSegment.min = Math.min(currentSegment.min, minIndex); currentSegment.max = Math.max(currentSegment.max, maxIndex); lastMax = maxIndex; } nodeStats.segments = result; } function orderChildSegments(children) { var specifiedOrder = [], unspecifiedOrder = []; for (var i = 0; i < children.length; i++) { var child = children[i], segments = stats[child.id].segments; for (var j = 0; j < segments.length; j++) { var seg = segments[j]; if (seg.min === defaultMin) { unspecifiedOrder.push(seg); } else { specifiedOrder.push(seg); } } } specifiedOrder.sort(function(a, b) { return a.min - b.min; }); return specifiedOrder.concat(unspecifiedOrder); } function executeNode(node, segmentNumber) { if (node.children) { return { fn: function(done) { var onStart = { fn: function(next) { nodeStart(node, next); } }; queueRunnerFactory({ onComplete: function () { var args = Array.prototype.slice.call(arguments, [0]); node.cleanupBeforeAfter(); nodeComplete(node, node.getResult(), function() { done.apply(undefined, args); }); }, queueableFns: [onStart].concat(wrapChildren(node, segmentNumber)), userContext: node.sharedUserContext(), onException: function () { node.onException.apply(node, arguments); } }); } }; } else { return { fn: function(done) { node.execute(done, stats[node.id].excluded); } }; } } function wrapChildren(node, segmentNumber) { var result = [], segmentChildren = stats[node.id].segments[segmentNumber].nodes; for (var i = 0; i < segmentChildren.length; i++) { result.push(executeNode(segmentChildren[i].owner, segmentChildren[i].index)); } if (!stats[node.id].willExecute) { return result; } return node.beforeAllFns.concat(result).concat(node.afterAllFns); } } return TreeProcessor; }; getJasmineRequireObj().UserContext = function(j$) { function UserContext() { } UserContext.fromExisting = function(oldContext) { var context = new UserContext(); for (var prop in oldContext) { if (oldContext.hasOwnProperty(prop)) { context[prop] = oldContext[prop]; } } return context; }; return UserContext; }; getJasmineRequireObj().version = function() { return '3.4.0'; }; ================================================ FILE: lib/require.js ================================================ /* RequireJS 2.1.8 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. Available via the MIT or new BSD license. see: http://github.com/jrburke/requirejs for details */ var requirejs,require,define; (function(Z){function H(b){return"[object Function]"===L.call(b)}function I(b){return"[object Array]"===L.call(b)}function y(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(H(m)){if(this.events.error&&this.map.isDefine||j.onError!==aa)try{e=i.execCb(c,m,b,e)}catch(d){a=d}else e=i.execCb(c,m,b,e);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!== this.exports?e=b.exports:void 0===e&&this.usingExports&&(e=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",v(this.error=a)}else e=m;this.exports=e;if(this.map.isDefine&&!this.ignore&&(r[c]=e,j.onResourceLoad))j.onResourceLoad(i,this.map,this.depMaps);x(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete= !0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=n(a.prefix);this.depMaps.push(d);t(d,"defined",u(this,function(e){var m,d;d=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,h=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(e.normalize&&(d=e.normalize(d,function(a){return c(a,g,!0)})||""),e=n(a.prefix+"!"+d,this.map.parentMap),t(e,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})), d=l(p,e.id)){this.depMaps.push(e);if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else m=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),m.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];F(p,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&x(a.map.id)});v(a)}),m.fromText=u(this,function(e,c){var d=a.name,g=n(d),B=O;c&&(e=c);B&&(O=!1);q(g);s(k.config,b)&&(k.config[d]=k.config[b]);try{j.exec(e)}catch(ca){return v(A("fromtexteval", "fromText eval for "+b+" failed: "+ca,ca,[b]))}B&&(O=!0);this.depMaps.push(g);i.completeLoad(d);h([d],m)}),e.load(a.name,h,m,k)}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){T[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,u(this,function(a,b){var c,e;if("string"===typeof a){a=n(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=l(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;t(a,"defined",u(this,function(a){this.defineDep(b, a);this.check()}));this.errback&&t(a,"error",u(this,this.errback))}c=a.id;e=p[c];!s(N,c)&&(e&&!e.enabled)&&i.enable(a,this)}));F(this.pluginMaps,u(this,function(a){var b=l(p,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:k,contextName:b,registry:p,defined:r,urlFetched:S,defQueue:G,Module:X,makeModuleMap:n, nextTick:j.nextTick,onError:v,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=k.pkgs,c=k.shim,e={paths:!0,config:!0,map:!0};F(a,function(a,b){e[b]?"map"===b?(k.map||(k.map={}),Q(k[b],a,!0,!0)):Q(k[b],a,!0):k[b]=a});a.shim&&(F(a.shim,function(a,b){I(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);c[b]=a}),k.shim=c);a.packages&&(y(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name, location:a.location||a.name,main:(a.main||"main").replace(ja,"").replace(ea,"")}}),k.pkgs=b);F(p,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=n(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(Z,arguments));return b||a.exports&&ba(a.exports)}},makeRequire:function(a,f){function d(e,c,h){var g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(H(c))return v(A("requireargs", "Invalid require call"),h);if(a&&s(N,e))return N[e](p[a.id]);if(j.get)return j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return d}f=f||{};Q(d,{isBrowser:z,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==f&&(!("."===g||".."===g)||1h.attachEvent.toString().indexOf("[native code"))&&!W?(O=!0,h.attachEvent("onreadystatechange",b.onScriptLoad)):(h.addEventListener("load",b.onScriptLoad,!1),h.addEventListener("error", b.onScriptError,!1)),h.src=d,K=h,C?x.insertBefore(h,C):x.appendChild(h),K=null,h;if(da)try{importScripts(d),b.completeLoad(c)}catch(l){b.onError(A("importscripts","importScripts failed for "+c+" at "+d,l,[c]))}};z&&M(document.getElementsByTagName("script"),function(b){x||(x=b.parentNode);if(J=b.getAttribute("data-main"))return q=J,t.baseUrl||(D=q.split("/"),q=D.pop(),fa=D.length?D.join("/")+"/":"./",t.baseUrl=fa),q=q.replace(ea,""),j.jsExtRegExp.test(q)&&(q=J),t.deps=t.deps?t.deps.concat(q):[q],!0}); define=function(b,c,d){var h,j;"string"!==typeof b&&(d=c,c=b,b=null);I(c)||(d=c,c=null);!c&&H(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(h=K))P&&"interactive"===P.readyState||M(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),h=P;h&&(b||(b=h.getAttribute("data-requiremodule")),j=E[h.getAttribute("data-requirecontext")])}(j?j.defQueue: R).push([b,c,d])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(t)}})(this); ================================================ FILE: package.json ================================================ { "name": "js-quantities", "main": "./build/quantities.js", "exports": { ".": { "import": "./build/quantities.mjs", "require": "./build/quantities.js" }, "./esm": "./build/quantities.mjs" }, "readmeFilename": "README.md", "description": "JavaScript library for quantity calculation and unit conversion", "version": "1.8.0", "homepage": "http://gentooboontoo.github.io/js-quantities/", "repository": { "type": "git", "url": "https://github.com/gentooboontoo/js-quantities.git" }, "keywords": [ "conversion", "convert", "imperial", "measure", "measurement", "metric", "parse", "parser", "physical", "quantity", "quantities", "temperature", "unit", "units" ], "author": "Julien Sanchez ", "contributors": [ "Julien Sanchez ", "Rage Shadowman " ], "license": "MIT", "scripts": { "test": "jasmine-node spec/" }, "bugs": { "url": "https://github.com/gentooboontoo/js-quantities/issues" }, "devDependencies": { "eslint": "^7.15.0", "jasmine": "^3.6.3", "rollup": "^2.34.2" } } ================================================ FILE: spec/blns.json ================================================ [ "", "undefined", "undef", "null", "NULL", "(null)", "nil", "NIL", "true", "false", "True", "False", "TRUE", "FALSE", "None", "hasOwnProperty", "\\", "\\\\", "0", "1", "1.00", "$1.00", "1/2", "1E2", "1E02", "1E+02", "-1", "-1.00", "-$1.00", "-1/2", "-1E2", "-1E02", "-1E+02", "1/0", "0/0", "-2147483648/-1", "-9223372036854775808/-1", "-0", "-0.0", "+0", "+0.0", "0.00", "0..0", ".", "0.0.0", "0,00", "0,,0", ",", "0,0,0", "0.0/0", "1.0/0.0", "0.0/0.0", "1,0/0,0", "0,0/0,0", "--1", "-", "-.", "-,", "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", "NaN", "Infinity", "-Infinity", "INF", "1#INF", "-1#IND", "1#QNAN", "1#SNAN", "1#IND", "0x0", "0xffffffff", "0xffffffffffffffff", "0xabad1dea", "123456789012345678901234567890123456789", "1,000.00", "1 000.00", "1'000.00", "1,000,000.00", "1 000 000.00", "1'000'000.00", "1.000,00", "1 000,00", "1'000,00", "1.000.000,00", "1 000 000,00", "1'000'000,00", "01000", "08", "09", "2.2250738585072011e-308", ",./;'[]\\-=", "<>?:\"{}|_+", "!@#$%^&*()`~", "\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f", "€‚ƒ„†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ", "\t\u000b\f …             ​

   ", "­؀؁؂؃؄؅؜۝܏᠎​‌‍‎‏‪‫‬‭‮⁠⁡⁢⁣⁤⁦⁧⁨⁩𑂽𛲠𛲡𛲢𛲣𝅳𝅴𝅵𝅶𝅷𝅸𝅹𝅺󠀁󠀠󠀡󠀢󠀣󠀤󠀥󠀦󠀧󠀨󠀩󠀪󠀫󠀬󠀭󠀮󠀯󠀰󠀱󠀲󠀳󠀴󠀵󠀶󠀷󠀸󠀹󠀺󠀻󠀼󠀽󠀾󠀿󠁀󠁁󠁂󠁃󠁄󠁅󠁆󠁇󠁈󠁉󠁊󠁋󠁌󠁍󠁎󠁏󠁐󠁑󠁒󠁓󠁔󠁕󠁖󠁗󠁘󠁙󠁚󠁛󠁜󠁝󠁞󠁟󠁠󠁡󠁢󠁣󠁤󠁥󠁦󠁧󠁨󠁩󠁪󠁫󠁬󠁭󠁮󠁯󠁰󠁱󠁲󠁳󠁴󠁵󠁶󠁷󠁸󠁹󠁺󠁻󠁼󠁽󠁾󠁿", "", "￾", "Ω≈ç√∫˜µ≤≥÷", "åß∂ƒ©˙∆˚¬…æ", "œ∑´®†¥¨ˆøπ“‘", "¡™£¢∞§¶•ªº–≠", "¸˛Ç◊ı˜Â¯˘¿", "ÅÍÎÏ˝ÓÔÒÚÆ☃", "Œ„´‰ˇÁ¨ˆØ∏”’", "`⁄€‹›fifl‡°·‚—±", "⅛⅜⅝⅞", "ЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя", "٠١٢٣٤٥٦٧٨٩", "⁰⁴⁵", "₀₁₂", "⁰⁴⁵₀₁₂", "ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็", "'", "\"", "''", "\"\"", "'\"'", "\"''''\"'\"", "\"'\"'\"''''\"", "", "", "", "", "田中さんにあげて下さい", "パーティーへ行かないか", "和製漢語", "部落格", "사회과학원 어학연구소", "찦차를 타고 온 펲시맨과 쑛다리 똠방각하", "社會科學院語學研究所", "울란바토르", "𠜎𠜱𠝹𠱓𠱸𠲖𠳏", "Ⱥ", "Ⱦ", "ヽ༼ຈل͜ຈ༽ノ ヽ༼ຈل͜ຈ༽ノ ", "(。◕ ∀ ◕。)", "`ィ(´∀`∩", "__ロ(,_,*)", "・( ̄∀ ̄)・:*:", "゚・✿ヾ╲(。◕‿◕。)╱✿・゚", ",。・:*:・゜’( ☻ ω ☻ )。・:*:・゜’", "(╯°□°)╯︵ ┻━┻)", "(ノಥ益ಥ)ノ ┻━┻", "┬─┬ノ( º _ ºノ)", "( ͡° ͜ʖ ͡°)", "😍", "👩🏽", "👾 🙇 💁 🙅 🙆 🙋 🙎 🙍", "🐵 🙈 🙉 🙊", "❤️ 💔 💌 💕 💞 💓 💗 💖 💘 💝 💟 💜 💛 💚 💙", "✋🏿 💪🏿 👐🏿 🙌🏿 👏🏿 🙏🏿", "🚾 🆒 🆓 🆕 🆖 🆗 🆙 🏧", "0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟", "🇺🇸🇷🇺🇸 🇦🇫🇦🇲🇸", "🇺🇸🇷🇺🇸🇦🇫🇦🇲", "🇺🇸🇷🇺🇸🇦", "123", "١٢٣", "ثم نفس سقطت وبالتحديد،, جزيرتي باستخدام أن دنو. إذ هنا؟ الستار وتنصيب كان. أهّل ايطاليا، بريطانيا-فرنسا قد أخذ. سليمان، إتفاقية بين ما, يذكر الحدود أي بعد, معاملة بولندا، الإطلاق عل إيو.", "בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָאָרֶץ", "הָיְתָהtestالصفحات التّحول", "﷽", "ﷺ", "مُنَاقَشَةُ سُبُلِ اِسْتِخْدَامِ اللُّغَةِ فِي النُّظُمِ الْقَائِمَةِ وَفِيم يَخُصَّ التَّطْبِيقَاتُ الْحاسُوبِيَّةُ، ", "​", " ", "᠎", " ", "", "␣", "␢", "␡", "‪‪test‪", "‫test‫", "
test
", "test⁠test‫", "⁦test⁧", "Ṱ̺̺̕o͞ ̷i̲̬͇̪͙n̝̗͕v̟̜̘̦͟o̶̙̰̠kè͚̮̺̪̹̱̤ ̖t̝͕̳̣̻̪͞h̼͓̲̦̳̘̲e͇̣̰̦̬͎ ̢̼̻̱̘h͚͎͙̜̣̲ͅi̦̲̣̰̤v̻͍e̺̭̳̪̰-m̢iͅn̖̺̞̲̯̰d̵̼̟͙̩̼̘̳ ̞̥̱̳̭r̛̗̘e͙p͠r̼̞̻̭̗e̺̠̣͟s̘͇̳͍̝͉e͉̥̯̞̲͚̬͜ǹ̬͎͎̟̖͇̤t͍̬̤͓̼̭͘ͅi̪̱n͠g̴͉ ͏͉ͅc̬̟h͡a̫̻̯͘o̫̟̖͍̙̝͉s̗̦̲.̨̹͈̣", "̡͓̞ͅI̗̘̦͝n͇͇͙v̮̫ok̲̫̙͈i̖͙̭̹̠̞n̡̻̮̣̺g̲͈͙̭͙̬͎ ̰t͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨o͚̪͡f̘̣̬ ̖̘͖̟͙̮c҉͔̫͖͓͇͖ͅh̵̤̣͚͔á̗̼͕ͅo̼̣̥s̱͈̺̖̦̻͢.̛̖̞̠̫̰", "̗̺͖̹̯͓Ṯ̤͍̥͇͈h̲́e͏͓̼̗̙̼̣͔ ͇̜̱̠͓͍ͅN͕͠e̗̱z̘̝̜̺͙p̤̺̹͍̯͚e̠̻̠͜r̨̤͍̺̖͔̖̖d̠̟̭̬̝͟i̦͖̩͓͔̤a̠̗̬͉̙n͚͜ ̻̞̰͚ͅh̵͉i̳̞v̢͇ḙ͎͟-҉̭̩̼͔m̤̭̫i͕͇̝̦n̗͙ḍ̟ ̯̲͕͞ǫ̟̯̰̲͙̻̝f ̪̰̰̗̖̭̘͘c̦͍̲̞͍̩̙ḥ͚a̮͎̟̙͜ơ̩̹͎s̤.̝̝ ҉Z̡̖̜͖̰̣͉̜a͖̰͙̬͡l̲̫̳͍̩g̡̟̼̱͚̞̬ͅo̗͜.̟", "̦H̬̤̗̤͝e͜ ̜̥̝̻͍̟́w̕h̖̯͓o̝͙̖͎̱̮ ҉̺̙̞̟͈W̷̼̭a̺̪͍į͈͕̭͙̯̜t̶̼̮s̘͙͖̕ ̠̫̠B̻͍͙͉̳ͅe̵h̵̬͇̫͙i̹͓̳̳̮͎̫̕n͟d̴̪̜̖ ̰͉̩͇͙̲͞ͅT͖̼͓̪͢h͏͓̮̻e̬̝̟ͅ ̤̹̝W͙̞̝͔͇͝ͅa͏͓͔̹̼̣l̴͔̰̤̟͔ḽ̫.͕", "Z̮̞̠͙͔ͅḀ̗̞͈̻̗Ḷ͙͎̯̹̞͓G̻O̭̗̮", "˙ɐnbᴉlɐ ɐuƃɐɯ ǝɹolop ʇǝ ǝɹoqɐl ʇn ʇunpᴉpᴉɔuᴉ ɹodɯǝʇ poɯsnᴉǝ op pǝs 'ʇᴉlǝ ƃuᴉɔsᴉdᴉpɐ ɹnʇǝʇɔǝsuoɔ 'ʇǝɯɐ ʇᴉs ɹolop ɯnsdᴉ ɯǝɹo˥", "00˙Ɩ$-", "The quick brown fox jumps over the lazy dog", "𝐓𝐡𝐞 𝐪𝐮𝐢𝐜𝐤 𝐛𝐫𝐨𝐰𝐧 𝐟𝐨𝐱 𝐣𝐮𝐦𝐩𝐬 𝐨𝐯𝐞𝐫 𝐭𝐡𝐞 𝐥𝐚𝐳𝐲 𝐝𝐨𝐠", "𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐 𝖇𝖗𝖔𝖜𝖓 𝖋𝖔𝖝 𝖏𝖚𝖒𝖕𝖘 𝖔𝖛𝖊𝖗 𝖙𝖍𝖊 𝖑𝖆𝖟𝖞 𝖉𝖔𝖌", "𝑻𝒉𝒆 𝒒𝒖𝒊𝒄𝒌 𝒃𝒓𝒐𝒘𝒏 𝒇𝒐𝒙 𝒋𝒖𝒎𝒑𝒔 𝒐𝒗𝒆𝒓 𝒕𝒉𝒆 𝒍𝒂𝒛𝒚 𝒅𝒐𝒈", "𝓣𝓱𝓮 𝓺𝓾𝓲𝓬𝓴 𝓫𝓻𝓸𝔀𝓷 𝓯𝓸𝔁 𝓳𝓾𝓶𝓹𝓼 𝓸𝓿𝓮𝓻 𝓽𝓱𝓮 𝓵𝓪𝔃𝔂 𝓭𝓸𝓰", "𝕋𝕙𝕖 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨𝕟 𝕗𝕠𝕩 𝕛𝕦𝕞𝕡𝕤 𝕠𝕧𝕖𝕣 𝕥𝕙𝕖 𝕝𝕒𝕫𝕪 𝕕𝕠𝕘", "𝚃𝚑𝚎 𝚚𝚞𝚒𝚌𝚔 𝚋𝚛𝚘𝚠𝚗 𝚏𝚘𝚡 𝚓𝚞𝚖𝚙𝚜 𝚘𝚟𝚎𝚛 𝚝𝚑𝚎 𝚕𝚊𝚣𝚢 𝚍𝚘𝚐", "⒯⒣⒠ ⒬⒰⒤⒞⒦ ⒝⒭⒪⒲⒩ ⒡⒪⒳ ⒥⒰⒨⒫⒮ ⒪⒱⒠⒭ ⒯⒣⒠ ⒧⒜⒵⒴ ⒟⒪⒢", "", "<script>alert('123');</script>", "", "", "\">", "'>", ">", "", "< / script >< script >alert(123)< / script >", " onfocus=JaVaSCript:alert(123) autofocus", "\" onfocus=JaVaSCript:alert(123) autofocus", "' onfocus=JaVaSCript:alert(123) autofocus", "<script>alert(123)</script>", "ript>alert(123)ript>", "-->", "\";alert(123);t=\"", "';alert(123);t='", "JavaSCript:alert(123)", ";alert(123);", "src=JaVaSCript:prompt(132)", "\"><\\x3Cscript>javascript:alert(1)", "'`\"><\\x00script>javascript:alert(1)", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "ABC
DEF", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "test", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "`\"'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "\"`'>", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "XXX", "javascript:alert(1)\"` `>", "", "", "<a href=http://foo.bar/#x=`y></a><img alt=\"`><img src=x:x onerror=javascript:alert(1)></a>\">", "<!--[if]><script>javascript:alert(1)</script -->", "<!--[if<img src=x onerror=javascript:alert(1)//]> -->", "<script src=\"/\\%(jscript)s\"></script>", "<script src=\"\\\\%(jscript)s\"></script>", "<IMG \"\"\"><SCRIPT>alert(\"XSS\")</SCRIPT>\">", "<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>", "<IMG SRC=# onmouseover=\"alert('xxs')\">", "<IMG SRC= onmouseover=\"alert('xxs')\">", "<IMG onmouseover=\"alert('xxs')\">", "<IMG SRC=javascript:alert('XSS')>", "<IMG SRC=javascript:alert('XSS')>", "<IMG SRC=javascript:alert('XSS')>", "<IMG SRC=\"jav ascript:alert('XSS');\">", "<IMG SRC=\"jav ascript:alert('XSS');\">", "<IMG SRC=\"jav ascript:alert('XSS');\">", "<IMG SRC=\"jav ascript:alert('XSS');\">", "perl -e 'print \"<IMG SRC=java\\0script:alert(\\\"XSS\\\")>\";' > out", "<IMG SRC=\"  javascript:alert('XSS');\">", "<SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>", "<BODY onload!#$%&()*~+-_.,:;?@[/|\\]^`=alert(\"XSS\")>", "<SCRIPT/SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>", "<<SCRIPT>alert(\"XSS\");//<</SCRIPT>", "<SCRIPT SRC=http://ha.ckers.org/xss.js?< B >", "<SCRIPT SRC=//ha.ckers.org/.j>", "<IMG SRC=\"javascript:alert('XSS')\"", "<iframe src=http://ha.ckers.org/scriptlet.html <", "\\\";alert('XSS');//", "<u oncopy=alert()> Copy me</u>", "<i onwheel=alert(1)> Scroll over me </i>", "<plaintext>", "http://a/%%30%30", "</textarea><script>alert(123)</script>", "1;DROP TABLE users", "1'; DROP TABLE users-- 1", "' OR 1=1 -- 1", "' OR '1'='1", " ", "%", "_", "-", "--", "--version", "--help", "$USER", "/dev/null; touch /tmp/blns.fail ; echo", "`touch /tmp/blns.fail`", "$(touch /tmp/blns.fail)", "@{[system \"touch /tmp/blns.fail\"]}", "eval(\"puts 'hello world'\")", "System(\"ls -al /\")", "`ls -al /`", "Kernel.exec(\"ls -al /\")", "Kernel.exit(1)", "%x('ls -al /')", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]><foo>&xxe;</foo>", "$HOME", "$ENV{'HOME'}", "%d", "%s", "{0}", "%*.*s", "File:///", "../../../../../../../../../../../etc/passwd%00", "../../../../../../../../../../../etc/hosts", "() { 0; }; touch /tmp/blns.shellshock1.fail;", "() { _; } >_[$($())] { touch /tmp/blns.shellshock2.fail; }", "<<< %s(un='%s') = %u", "+++ATH0", "CON", "PRN", "AUX", "CLOCK$", "NUL", "A:", "ZZ:", "COM1", "LPT1", "LPT2", "LPT3", "COM2", "COM3", "COM4", "DCC SEND STARTKEYLOGGER 0 0 0", "Scunthorpe General Hospital", "Penistone Community Church", "Lightwater Country Park", "Jimmy Clitheroe", "Horniman Museum", "shitake mushrooms", "RomansInSussex.co.uk", "http://www.cum.qc.ca/", "Craig Cockburn, Software Specialist", "Linda Callahan", "Dr. Herman I. Libshitz", "magna cum laude", "Super Bowl XXX", "medieval erection of parapets", "evaluate", "mocha", "expression", "Arsenal canal", "classic", "Tyson Gay", "Dick Van Dyke", "basement", "If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you.", "Roses are \u001b[0;31mred\u001b[0m, violets are \u001b[0;34mblue. Hope you enjoy terminal hue", "But now...\u001b[20Cfor my greatest trick...\u001b[8m", "The quic\b\b\b\b\b\bk brown fo\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007\u0007x... [Beeeep]", "Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗" ] ================================================ FILE: spec/quantitiesSpec.js ================================================ /* global __dirname, describe, expect, it, require, beforeEach, afterEach */ var Qty; /* * Needed when run through jasmine-node */ if (typeof window === "undefined") { Qty = require(__dirname + "/../build/quantities"); } describe("js-quantities", function() { describe("initialization", function() { it("should create unit only", function() { var qty = Qty("m"); expect(qty.numerator).toEqual(["<meter>"]); expect(qty.scalar).toBe(1); }); it("should create unitless", function() { var qty = Qty("1"); expect(qty.toFloat()).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); qty = Qty("1.5"); expect(qty.toFloat()).toBe(1.5); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("should create unitless from numbers", function() { var qty = Qty(1.5); expect(qty.toFloat()).toBe(1.5); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("should create from numbers with explicit units", function() { var qty = Qty(1.5, "m"); expect(qty.scalar).toBe(1.5); expect(qty.numerator).toEqual(["<meter>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("temperatures should have base unit in kelvin", function() { var qty = Qty("1 tempK").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("tempK"); qty = Qty("1 tempR").toBase(); expect(qty.scalar).toBe(5 / 9); expect(qty.units()).toBe("tempK"); qty = Qty("0 tempC").toBase(); expect(qty.scalar).toBe(273.15); expect(qty.units()).toBe("tempK"); qty = Qty("0 tempF").toBase(); expect(qty.scalar).toBeCloseTo(255.372, 3); expect(qty.units()).toBe("tempK"); }); it("temperature degrees should have base unit in kelvin", function() { var qty = Qty("1 degK").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("degK"); qty = Qty("1 degR").toBase(); expect(qty.scalar).toBe(5 / 9); expect(qty.units()).toBe("degK"); qty = Qty("1 degC").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("degK"); qty = Qty("1 degF").toBase(); expect(qty.scalar).toBe(5 / 9); expect(qty.units()).toBe("degK"); }); it("should not create temperatures below absolute zero", function() { expect(function() { Qty("-1 tempK"); }).toThrowError("Temperatures must not be less than absolute zero"); expect(function() { Qty("-273.16 tempC"); }).toThrowError("Temperatures must not be less than absolute zero"); expect(function() { Qty("-459.68 tempF"); }).toThrowError("Temperatures must not be less than absolute zero"); expect(function() { Qty("-1 tempR"); }).toThrowError("Temperatures must not be less than absolute zero"); var qty = Qty("1 tempK"); expect(function() { qty.mul("-1"); }).toThrowError("Temperatures must not be less than absolute zero"); qty = Qty("0 tempK"); expect(function() { qty.sub("1 degK"); }).toThrowError("Temperatures must not be less than absolute zero"); qty = Qty("-273.15 tempC"); expect(function() { qty.sub("1 degC"); }).toThrowError("Temperatures must not be less than absolute zero"); qty = Qty("-459.67 tempF"); expect(function() { qty.sub("1 degF"); }).toThrowError("Temperatures must not be less than absolute zero"); qty = Qty("0 tempR"); expect(function() { qty.sub("1 degR"); }).toThrowError("Temperatures must not be less than absolute zero"); }); it("should create simple", function() { var qty = Qty("1m"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<meter>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("should create negative", function() { var qty = Qty("-1m"); expect(qty.scalar).toBe(-1); expect(qty.numerator).toEqual(["<meter>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("should create compound", function() { var qty = Qty("1 N*m"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<newton>", "<meter>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("should create pressure units in term of height of water", function() { var qty = Qty("1 inH2O"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<inh2o>"]); qty = Qty("1 cmH2O"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<cmh2o>"]); }); it("should create with denominator", function() { var qty = Qty("1 m/s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<meter>"]); expect(qty.denominator).toEqual(["<second>"]); }); it("should create with denominator only", function() { var qty = Qty("1 /s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<second>"]); qty = Qty("1 1/s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<second>"]); qty = Qty("1 s^-1"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<second>"]); }); it("should create with powers", function() { var qty = Qty("1 m^2/s^2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<meter>","<meter>"]); expect(qty.denominator).toEqual(["<second>","<second>"]); qty = Qty("1 m^2 kg^2 J^2/s^2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<meter>","<meter>","<kilogram>","<kilogram>","<joule>","<joule>"]); expect(qty.denominator).toEqual(["<second>","<second>"]); qty = Qty("1 m^2/s^2*J^3"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<meter>","<meter>"]); expect(qty.denominator).toEqual(["<second>","<second>","<joule>","<joule>","<joule>"]); }); it("should create with zero power", function() { var qty = Qty("1 m^0"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); it("should create with negative powers", function() { var qty = Qty("1 m^2 s^-2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<meter>","<meter>"]); expect(qty.denominator).toEqual(["<second>","<second>"]); expect(qty.same(Qty("1 m^2/s^2"))).toBe(true); }); it("should accept powers without ^ syntax (simple)", function() { var qty1 = Qty("1 m2"); var qty2 = Qty("1 m^2"); expect(qty1.eq(qty2)).toBe(true); }); it("should accept powers without ^ syntax (negative power)", function() { var qty1 = Qty("1 m-2"); var qty2 = Qty("1 m^-2"); expect(qty1.eq(qty2)).toBe(true); }); it("should accept powers without ^ syntax (compound)", function() { var qty1 = Qty("1 m^2 kg^2 J^2/s^2"); var qty2 = Qty("1 m2 kg2 J2/s2"); expect(qty1.eq(qty2)).toBe(true); }); it("should accept powers without ^ syntax (compound and negative power)", function() { var qty1 = Qty("1 m^2 kg^2 J^2 s^-2"); var qty2 = Qty("1 m2 kg2 J2 s-2"); expect(qty1.eq(qty2)).toBe(true); }); it("should throw when parsing powers greater than 4", function() { // See github issue #73 expect(function() { Qty("593720475cm^4939207503"); }).toThrowError("Unit not recognized"); expect(function() { Qty("593720475cm**4939207503"); }).toThrowError("Unit not recognized"); }); it("should throw 'Unit not recognized' error when initializing with an invalid unit", function() { expect(function() { Qty("aa"); }).toThrowError("Unit not recognized"); expect(function() { Qty("m/aa"); }).toThrowError("Unit not recognized"); expect(function() { Qty("m-"); }).toThrowError("Unit not recognized"); expect(function() { Qty("N*m"); }).not.toThrowError("Unit not recognized"); // mm is millimeter, but mmm is not a valid unit expect(function() { Qty("mmm"); }).toThrowError("Unit not recognized"); // previously this value caused infinitely long regex test when checking if unit is correct expect(function() { Qty("0.11 180°/sec"); }).toThrowError("Unit not recognized"); // Crash-causing strings, See github issue #73 expect(function() { Qty("58261da44b642352442b8060"); }).toThrowError("Unit not recognized"); expect(function() { Qty("A1EB12B4233021311SH"); }).toThrowError("Unit not recognized"); }); if (typeof window === "undefined") { // only test in node.js it("does not crash with potentially dangerous strings", function() { // Multi-byte characters, emoji, etc. // From https://github.com/minimaxir/big-list-of-naughty-strings require("./blns.json").forEach(function(s) { try { Qty(s); } catch (e) {} }); }); } it("should accept empty string as unitless 1", function() { expect(Qty("").same(Qty("1"))).toBe(true); expect(Qty(" ").same(Qty("1"))).toBe(true); }); it("should throw error when passing a null value", function() { expect(function() { Qty(null); }).toThrowError("Only string, number or quantity accepted as single " + "initialization value"); }); it("should throw error when passing NaN", function() { expect( function() { Qty(NaN); } ).toThrowError("Only string, number or quantity accepted as single " + "initialization value"); }); it("should throw 'Unit not recognized' error when initializing with an invalid unit and a 0 exponent", function() { expect(function() { Qty("3p0"); }).toThrowError("Unit not recognized"); expect(function() { Qty("3p-0"); }).toThrowError("Unit not recognized"); }); it("should set baseScalar", function() { var qty = Qty("0.018 MPa"); expect(qty.baseScalar).toBe(18000); qty = Qty("66 cm3"); expect(qty.baseScalar).toBe(0.000066); }); it("should keep init value as is", function() { var initValue = " 66 cm3 "; var qty = Qty(initValue); expect(qty.initValue).toEqual(initValue); }); it("should allow whitespace-wrapped value", function() { expect(function() { Qty(" 2 MPa "); }).not.toThrow(); }); it("should allow whitespaces between sign and scalar", function() { var qty = Qty("- 1m"); expect(qty.scalar).toEqual(-1); expect(qty.units()).toEqual("m"); }); it("should throw an error when parsing negative quantity " + "with no scalar", function() { expect(function() { Qty("-m"); }).toThrowError("Unit not recognized"); }); }); describe("isCompatible", function() { it("should return true with compatible quantities", function() { var qty1 = Qty("1 m*kg/s"); var qty2 = Qty("1 in*pound/min"); expect(qty1.isCompatible(qty2)).toBe(true); qty2 = Qty("1 in/min"); expect(qty1.isCompatible(qty2)).toBe(false); }); it("should return true with dimensionless quantities", function() { var qty1 = Qty("1"); var qty2 = Qty("2"); expect(qty1.isCompatible(qty2)).toBe(true); }); it("should return false with null or undefined", function() { var qty1 = Qty("1 m*kg/s"); expect(qty1.isCompatible(undefined)).toBe(false); expect(qty1.isCompatible(null)).toBe(false); }); it("should return false with non quantities", function() { var qty1 = Qty("1 m*kg/s"); expect(qty1.isCompatible({})).toBe(false); }); }); describe("conversion", function() { it("should convert to base units", function() { var qty = Qty("100 cm"); expect(qty.toBase().scalar).toBe(1); expect(qty.toBase().units()).toBe("m"); qty = Qty("10 cm"); expect(qty.toBase().scalar).toBe(0.1); expect(qty.toBase().units()).toBe("m"); qty = Qty("0.3 mm^2 ms^-2"); expect(qty.toBase().scalar).toBe(0.3); expect(qty.toBase().units()).toBe("m2/s2"); }); it("should convert to compatible units", function() { var qty = Qty("10 cm"); expect(qty.to("ft").scalar).toBe(Qty.divSafe(0.1, 0.3048)); qty = Qty("2m^3"); expect(qty.to("l").scalar).toBe(2000); qty = Qty("10 cm"); expect(qty.to(Qty("m")).scalar).toBe(0.1); expect(qty.to(Qty("20m")).scalar).toBe(0.1); qty = Qty("1 m3"); expect(qty.to("cm3").scalar).toBe(1000000); qty = Qty("1 cm3"); expect(qty.to("mm3").scalar).toBe(1000); qty = Qty("550 cm3"); expect(qty.to("cm^3").scalar).toBe(550); qty = Qty("0.000773 m3"); expect(qty.to("cm^3").scalar).toBe(773); qty = Qty("10 t"); expect(qty.to("kg").scalar).toBe(10000); }); describe("percents", function() { it("should convert from % to unitless", function() { expect(Qty("10 %").to("").same(Qty("0.1"))).toBe(true); }); it("should convert from unitless to %", function() { expect(Qty("0.1").to("%").same(Qty("10 %"))).toBe(true); }); }); it("should convert temperatures to compatible units", function() { var qty = Qty("0 tempK"); expect(qty.to("tempC").scalar).toBe(-273.15); qty = Qty("0 tempF"); expect(qty.to("tempK").scalar).toBeCloseTo(255.372, 3); qty = Qty("32 tempF"); expect(qty.to("tempC").scalar).toBe(0); qty = Qty("0 tempC"); expect(qty.to("tempF").scalar).toBeCloseTo(32, 10); }); it("should convert temperature degrees to compatible units", function() { var qty = Qty("0 degK"); expect(qty.to("degC").scalar).toBe(0); qty = Qty("1 degK/s"); expect(qty.to("degC/min").scalar).toBe(60); qty = Qty("100 cm/degF"); expect(qty.to("m/degF").scalar).toBe(1); qty = Qty("10 degC"); expect(qty.to("degF").scalar).toBe(18); }); it("should convert temperature degrees to temperatures", function() { // according to ruby-units, deg -> temp conversion adds the degress to 0 kelvin before converting var qty = Qty("100 degC"); expect(qty.to("tempC").scalar).toBeCloseTo(-173.15, 10); qty = Qty("273.15 degC"); expect(qty.to("tempC").scalar).toBe(0); qty = Qty("460.67 degF"); expect(qty.to("tempF").scalar).toBeCloseTo(1, 10); }); it("should convert temperatures to temperature degrees", function() { // according to ruby-units, temp -> deg conversion always uses the 0 relative degrees var qty = Qty("100 tempC"); expect(qty.to("degC").scalar).toBe(100); qty = Qty("0 tempK"); expect(qty.to("degC").scalar).toBe(0); qty = Qty("0 tempF"); expect(qty.to("degK").scalar).toBe(0); qty = Qty("18 tempF"); expect(qty.to("degC").scalar).toBe(10); qty = Qty("10 tempC"); expect(qty.to("degF").scalar).toBe(18); }); it("should calculate inverses", function() { var qty = Qty("1 ohm"); var result = qty.to("siemens"); expect(result.scalar).toBe(1); expect(result.kind()).toBe("conductance"); qty = Qty("10 ohm"); result = qty.to("siemens"); expect(result.scalar).toBe(0.1); expect(result.kind()).toBe("conductance"); qty = Qty("10 siemens"); result = qty.to("ohm"); expect(result.scalar).toBe(0.1); expect(result.kind()).toBe("resistance"); qty = Qty("10 siemens"); result = qty.inverse(); expect(result.eq(".1 ohm")).toBe(true); expect(result.kind()).toBe("resistance"); // cannot inverse a quantity with a 0 scalar qty = Qty("0 ohm"); expect(function() { qty.inverse(); }).toThrowError("Divide by zero"); qty = Qty("10 ohm").inverse(); result = qty.to("S"); expect(result.scalar).toBe(0.1); expect(result.kind()).toBe("conductance"); qty = Qty("12 in").inverse(); // TODO: Swap toBeCloseTo with toBe once divSafe is fixed expect(qty.to("ft").scalar).toBeCloseTo(1, 10); }); it("should return itself if target units are the same", function() { var qty = Qty("123 cm3"); expect(qty.to("cm3")).toBe(qty); expect(qty.to("cm^3")).toBe(qty); qty = Qty("123 mcg"); expect(qty.to("ug")).toBe(qty); }); it("should be cached", function() { var qty = Qty("100 m"); var converted = qty.to("ft"); expect(qty.to("ft") === converted).toBe(true); }); }); describe("comparison", function() { it("should return true when comparing equal quantities", function() { var qty1 = Qty("1cm"); var qty2 = Qty("10mm"); expect(qty1.eq(qty2)).toBe(true); }); it("should compare compatible quantities", function() { var qty1 = Qty("1cm"); var qty2 = Qty("1mm"); var qty3 = Qty("10mm"); var qty4 = Qty("28A"); expect(qty1.compareTo(qty2)).toBe(1); expect(qty2.compareTo(qty1)).toBe(-1); expect(qty1.compareTo(qty3)).toBe(0); expect(function() { qty1.compareTo(qty4); }).toThrowError("Incompatible units: cm and A"); expect(qty1.lt(qty2)).toBe(false); expect(qty1.lt(qty3)).toBe(false); expect(qty1.lte(qty3)).toBe(true); expect(qty1.gte(qty3)).toBe(true); expect(qty1.gt(qty2)).toBe(true); expect(qty2.gt(qty1)).toBe(false); }); it("should compare identical quantities", function() { var qty1 = Qty("1cm"); var qty2 = Qty("1cm"); var qty3 = Qty("10mm"); expect(qty1.same(qty2)).toBe(true); expect(qty1.same(qty3)).toBe(false); }); it("should accept strings as parameter", function() { var qty = Qty("1 cm"); expect(qty.lt("0.5 cm")).toBe(false); expect(qty.lte("1 cm")).toBe(true); expect(qty.gte("3 mm")).toBe(true); expect(qty.gt("5 m")).toBe(false); }); }); describe("non-ASCII character", function() { describe("µ", function() { it("should be supported as prefix", function() { // µ as greek letter expect(Qty("1 \u03BCm").eq(Qty("1 um"))).toBe(true); // µ as micro sign expect(Qty("1 \u00B5m").eq(Qty("1 um"))).toBe(true); }); }); describe("Ω", function() { it("should be accepted as unit for ohm", function() { // Ω as greek letter expect(Qty("1 \u03A9").eq(Qty("1 ohm"))).toBe(true); // Ω as ohm sign expect(Qty("1 \u2126").eq(Qty("1 ohm"))).toBe(true); }); }); }); describe("math", function() { it("should add quantities", function() { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); expect(qty1.add(qty2).scalar).toBe(5.5); expect(qty1.add("3m").scalar).toBe(5.5); qty2 = Qty("3cm"); var result = qty1.add(qty2); expect(result.scalar).toBe(2.53); expect(result.units()).toBe("m"); result = qty2.add(qty1); expect(result.scalar).toBe(253); expect(result.units()).toBe("cm"); // make sure adding 2 of the same non-base units work result = Qty("5cm").add("3cm"); expect(result.scalar).toBe(8); expect(result.units()).toBe("cm"); }); it("should fail to add unlike quantities", function() { var qty1 = Qty("3m"); var qty2 = Qty("2s"); expect(function() { qty1.add(qty2); }).toThrowError("Incompatible units: m and s"); expect(function() { qty2.add(qty1); }).toThrowError("Incompatible units: s and m"); }); it("should fail to add inverse quantities", function() { var qty1 = Qty("10S"); var qty2 = qty1.inverse(); expect(function() { qty1.add(qty2); }).toThrowError("Incompatible units: S and 1/S"); expect(function() { qty2.add(qty1); }).toThrowError("Incompatible units: 1/S and S"); qty1 = Qty("10S"); qty2 = Qty("0.1ohm"); expect(function() { qty1.add(qty2); }).toThrowError("Incompatible units: S and Ohm"); expect(function() { qty2.add(qty1); }).toThrowError("Incompatible units: Ohm and S"); }); it("should subtract quantities", function() { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); expect(qty1.sub(qty2).scalar).toBe(-0.5); expect(qty1.sub("2m").scalar).toBe(0.5); expect(qty1.sub("-2m").scalar).toBe(4.5); qty2 = Qty("3cm"); var result = qty1.sub(qty2); expect(result.scalar).toBe(2.47); expect(result.units()).toBe("m"); result = qty2.sub(qty1); expect(result.scalar).toBe(-247); expect(result.units()).toBe("cm"); }); it("should fail to subtract unlike quantities", function() { var qty1 = Qty("3m"); var qty2 = Qty("2s"); expect(function() { qty1.sub(qty2); }).toThrowError("Incompatible units: m and s"); expect(function() { qty2.sub(qty1); }).toThrowError("Incompatible units: s and m"); }); it("should fail to subtract inverse quantities", function() { var qty1 = Qty("10S"); var qty2 = qty1.inverse(); expect(function() { qty1.sub(qty2); }).toThrowError("Incompatible units: S and 1/S"); expect(function() { qty2.sub(qty1); }).toThrowError("Incompatible units: 1/S and S"); qty1 = Qty("10S"); qty2 = Qty("0.1ohm"); expect(function() { qty1.sub(qty2); }).toThrowError("Incompatible units: S and Ohm"); expect(function() { qty2.sub(qty1); }).toThrowError("Incompatible units: Ohm and S"); }); it("should multiply quantities", function() { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); var result = qty1.mul(qty2); expect(result.scalar).toBe(7.5); expect(result.units()).toBe("m2"); expect(result.kind()).toBe("area"); qty2 = Qty("3cm"); result = qty1.mul(qty2); expect(result.scalar).toBe(0.075); expect(result.units()).toBe("m2"); result = qty2.mul(qty1); expect(result.scalar).toBe(750); expect(result.units()).toBe("cm2"); result = qty1.mul(3.5); expect(result.scalar).toBe(8.75); expect(result.units()).toBe("m"); result = qty1.mul(0); expect(result.scalar).toBe(0); expect(result.units()).toBe("m"); result = qty1.mul(Qty("0m")); expect(result.scalar).toBe(0); expect(result.units()).toBe("m2"); qty2 = Qty("1.458 m"); result = qty1.mul(qty2); expect(result.scalar).toBe(3.645); expect(result.units()).toBe("m2"); }); it("should multiply unlike quantities", function() { var qty1 = Qty("2.5 m"); var qty2 = Qty("3 N"); var result = qty1.mul(qty2); expect(result.scalar).toBe(7.5); qty1 = Qty("2.5 m^2"); qty2 = Qty("3 kg/m^2"); result = qty1.mul(qty2); expect(result.scalar).toBe(7.5); expect(result.units()).toBe("kg"); }); it("should multiply inverse quantities", function() { var qty1 = Qty("10S"); var qty2 = Qty(".5S").inverse(); // 2/S var qty3 = qty1.inverse(); // .1/S var result = qty1.mul(qty2); expect(result.scalar).toBe(20); expect(result.isUnitless()).toBe(true); expect(result.units()).toBe(""); // swapping operands should give the same outcome result = qty2.mul(qty1); expect(result.scalar).toBe(20); expect(result.isUnitless()).toBe(true); expect(result.units()).toBe(""); result = qty1.mul(qty3); expect(result.scalar).toBe(1); expect(result.isUnitless()).toBe(true); expect(result.units()).toBe(""); // swapping operands should give the same outcome result = qty3.mul(qty1); expect(result.scalar).toBe(1); expect(result.isUnitless()).toBe(true); expect(result.units()).toBe(""); }); it("should multiply quantities and their inverses with prefixes", function() { var qty1 = Qty("3m"); var qty2 = Qty("4 1/km"); var result = qty1.mul(qty2); expect(result.scalar).toBe(0.012); expect(result.isUnitless()).toBe(true); qty1 = Qty("3 A/km"); qty2 = Qty("4 m"); result = qty1.mul(qty2); expect(result.scalar).toBe(0.012); expect(result.units()).toBe("A"); qty1 = Qty("3 1/km2"); qty2 = Qty("4 m"); result = qty1.mul(qty2); expect(result.scalar).toBe(0.012); expect(result.units()).toBe("1/km"); qty1 = Qty("4 m"); qty2 = Qty("3 1/km2"); result = qty1.mul(qty2); expect(result.scalar).toBe(0.000012); expect(result.units()).toBe("1/m"); }); it("should divide quantities", function() { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); var qty3 = Qty("0m"); expect(function() { qty1.div(qty3); }).toThrowError("Divide by zero"); expect(function() { qty1.div(0); }).toThrowError("Divide by zero"); expect(qty3.div(qty1).scalar).toBe(0); var result = qty1.div(qty2); expect(result.scalar).toBe(2.5 / 3); expect(result.units()).toBe(""); expect(result.kind()).toBe("unitless"); var qty4 = Qty("3cm"); result = qty1.div(qty4); expect(result.scalar).toBe(2.5 / 0.03); expect(result.units()).toBe(""); result = qty4.div(qty1); expect(result.scalar).toBe(0.012); expect(result.units()).toBe(""); result = qty1.div(3.5); expect(result.scalar).toBe(2.5 / 3.5); expect(result.units()).toBe("m"); }); it("should divide unlike quantities", function() { var qty1 = Qty("7.5kg"); var qty2 = Qty("2.5m^2"); var result = qty1.div(qty2); expect(result.scalar).toBe(3); expect(result.units()).toBe("kg/m2"); }); it("should divide inverse quantities", function() { var qty1 = Qty("10 S"); var qty2 = Qty(".5 S").inverse(); // 2/S var qty3 = qty1.inverse(); // .1/S var result = qty1.div(qty2); expect(result.scalar).toBe(5); expect(result.units()).toBe("S2"); result = qty2.div(qty1); expect(result.scalar).toBe(0.2); expect(result.units()).toBe("1/S2"); result = qty1.div(qty3); expect(result.scalar).toBe(100); expect(result.units()).toBe("S2"); result = qty3.div(qty1); expect(result.scalar).toBe(0.01); expect(result.units()).toBe("1/S2"); }); it("should divide quantities and their inverses with prefixes", function() { var qty1 = Qty("3m*A"); var qty2 = Qty("4 km"); var result = qty1.div(qty2); expect(result.scalar).toBe(0.00075); expect(result.units()).toBe("A"); qty1 = Qty("3 m"); qty2 = Qty("4 km*A"); result = qty1.div(qty2); expect(result.scalar).toBe(0.00075); expect(result.units()).toBe("1/A"); qty1 = Qty("3 m"); qty2 = Qty("4 km*cA"); result = qty1.div(qty2); expect(result.scalar).toBe(0.00075); expect(result.units()).toBe("1/cA"); }); }); describe("math with temperatures", function() { it("should add temperature degrees", function() { var qty = Qty("2degC"); expect(qty.add("3degF").scalar).toBeCloseTo(11 / 3, 10); expect(qty.add("-1degC").scalar).toBe(1); qty = Qty("2 degC"); var result = qty.add("2 degF"); expect(result.scalar).toBe(28 / 9); expect(result.units()).toBe("degC"); qty = Qty("2degK"); result = qty.add("3degC"); expect(result.scalar).toBe(5); expect(result.units()).toBe("degK"); qty = Qty("2degC"); result = qty.add("2degK"); expect(result.scalar).toBe(4); expect(result.units()).toBe("degC"); }); it("should not add two temperatures", function() { var qty = Qty("2tempC"); expect(function() { qty.add("1 tempF"); }).toThrowError("Cannot add two temperatures"); expect(function() { qty.add("1 tempC"); }).toThrowError("Cannot add two temperatures"); }); it("should add temperatures to degrees", function() { var qty = Qty("2degC"); var result = qty.add("3tempF"); expect(result.scalar).toBe(33 / 5); expect(result.units()).toBe("tempF"); result = qty.add("-1tempC"); expect(result.scalar).toBe(1); expect(result.units()).toBe("tempC"); qty = Qty("2 tempC"); result = qty.add("2 degF"); expect(result.scalar).toBe(28 / 9); expect(result.units()).toBe("tempC"); }); it("should subtract degrees from degrees", function() { var qty = Qty("2degC"); expect(qty.sub("1.5degK").scalar).toBe(0.5); expect(qty.sub("-2degC").scalar).toBe(4); expect(qty.sub("1degF").scalar).toBe(2 - 5 / 9); expect(qty.sub("-1degC").scalar).toBe(3); var result = qty.sub("degC"); expect(result.scalar).toBe(1); expect(result.units()).toBe("degC"); }); it("should subtract degrees from temperatures", function() { var qty = Qty("2tempC"); expect(qty.sub("1.5degK").scalar).toBe(0.5); expect(qty.sub("-2degC").scalar).toBe(4); expect(qty.sub("1degF").scalar).toBe(2 - 5 / 9); expect(qty.sub("-1degC").scalar).toBe(3); var result = qty.sub("degC"); expect(result.scalar).toBe(1); expect(result.units()).toBe("tempC"); }); it("should subtract temperatures from temperatures", function() { var qty = Qty("2tempC"); var result = qty.sub("1.5tempK"); expect(result.scalar).toBe(273.65); expect(result.units()).toBe("degC"); result = qty.sub("-2tempC"); expect(result.scalar).toBe(4); expect(result.units()).toBe("degC"); result = qty.sub("32tempF"); expect(result.scalar).toBe(2); expect(result.units()).toBe("degC"); }); it("should not subtract temperatures from degrees", function() { var qty = Qty("2degC"); expect(function() { qty.sub("1 tempF"); }).toThrowError("Cannot subtract a temperature from a differential degree unit"); expect(function() { qty.sub("1 tempC"); }).toThrowError("Cannot subtract a temperature from a differential degree unit"); }); it("should multiply temperature degrees", function() { var qty = Qty("2degF"); var result = qty.mul(3); expect(result.scalar).toBe(6); expect(result.units()).toBe("degF"); result = qty.mul("3degF"); expect(result.scalar).toBe(6); expect(result.units()).toBe("degF2"); // TODO: Should we convert degrees ("2 degK" to "degC") before we do the math? qty = Qty("2degC"); result = qty.mul("2degK"); expect(result.scalar).toBe(4); expect(result.units()).toBe("degC*degK"); qty = Qty("2degC"); result = qty.mul("degF"); expect(result.scalar).toBe(2); expect(result.units()).toBe("degC*degF"); }); it("should not multiply temperatures except by scalar", function() { var qty = Qty("2tempF"); expect(function() { qty.mul("1 tempC"); }).toThrowError("Cannot multiply by temperatures"); expect(function() { qty.mul("1 degC"); }).toThrowError("Cannot multiply by temperatures"); expect(function() { Qty("1 tempC*s"); }).toThrowError("Cannot multiply by temperatures"); var result = qty.mul(2); expect(result.scalar).toBe(4); expect(result.units()).toBe("tempF"); result = Qty("2").mul(qty); expect(result.scalar).toBe(4); expect(result.units()).toBe("tempF"); }); it("should multiply temperature degrees with unlike quantities", function() { var qty1 = Qty("2.5 degF"); var qty2 = Qty("3 m"); var result = qty1.mul(qty2); expect(result.scalar).toBe(7.5); qty1 = Qty("2.5 degF"); qty2 = Qty("3 kg/degF"); result = qty1.mul(qty2); expect(result.scalar).toBe(7.5); expect(result.units()).toBe("kg"); }); it("should divide temperature degrees with unlike quantities", function() { var qty1 = Qty("7.5degF"); var qty2 = Qty("2.5m^2"); var result = qty1.div(qty2); expect(result.scalar).toBe(3); expect(result.units()).toBe("degF/m2"); }); it("should divide temperature degree quantities", function() { var qty = Qty("2.5 degF"); expect(function() { qty.div("0 degF"); }).toThrowError("Divide by zero"); expect(function() { qty.div(0); }).toThrowError("Divide by zero"); expect(Qty("0 degF").div(qty).scalar).toBe(0); expect(Qty("0 degF").div(qty).units()).toBe(""); var result = qty.div("3 degF"); expect(result.scalar).toBe(2.5 / 3); expect(result.units()).toBe(""); expect(result.kind()).toBe("unitless"); result = qty.div(3); expect(result.scalar).toBe(2.5 / 3); expect(result.units()).toBe("degF"); expect(result.kind()).toBe("temperature"); // TODO: Should we convert "2 degC" to "degF" before we do the math? result = qty.div("2 degC"); expect(result.scalar).toBe(1.25); expect(result.units()).toBe("degF/degC"); }); it("should not divide with temperatures except by scalar", function() { expect(function() { Qty("tempF").div("1 tempC"); }).toThrowError("Cannot divide with temperatures"); expect(function() { Qty("tempF").div("1 degC"); }).toThrowError("Cannot divide with temperatures"); expect(function() { Qty("2").div("tempF"); }).toThrowError("Cannot divide with temperatures"); expect(function() { Qty("2 tempF/s"); }).toThrowError("Cannot divide with temperatures"); expect(function() { Qty("2 s/tempF"); }).toThrowError("Cannot divide with temperatures"); // inverse is division: 1/x expect(function() { Qty("tempF").inverse(); }).toThrowError("Cannot divide with temperatures"); var result = Qty("4 tempF").div(2); expect(result.scalar).toBe(2); expect(result.units()).toBe("tempF"); }); }); describe("errors", function() { it("should be instance of Qty.Error", function() { try { Qty("aa"); } catch (e) { expect(e instanceof Qty.Error).toBeTruthy(); } }); }); describe("utility methods", function() { it("should accept string as parameter for compatibility tests", function() { var qty = Qty("1 mm"); expect(qty.isCompatible("2 mm")).toBe(true); expect(qty.isCompatible("2 mm^3")).toBe(false); }); it("should return kind", function() { var qty = Qty("1 mm"); expect(qty.kind()).toBe("length"); qty = Qty("1 N"); expect(qty.kind()).toBe("force"); }); it("should know if a quantity is in base units", function() { var qty = Qty("100 cm"); expect(qty.isBase()).toBe(false); qty = Qty("1m"); expect(qty.isBase()).toBe(true); }); it("should return unit part of quantities", function() { var qty = Qty("1"); expect(qty.units()).toBe(""); qty = Qty("1 /s"); expect(qty.units()).toBe("1/s"); qty = Qty("100 cm"); expect(qty.units()).toBe("cm"); qty = Qty("100 cm/s"); expect(qty.units()).toBe("cm/s"); qty = Qty("1 cm^2"); expect(qty.units()).toBe("cm2"); qty = Qty("1 cm^2/s^2"); expect(qty.units()).toBe("cm2/s2"); qty = Qty("1 cm^2*J^3/s^2*A^2"); expect(qty.units()).toBe("cm2*J3/s2*A2"); }); }); describe("toString", function() { it("should generate readable human output", function() { var qty = Qty("2m"); expect(qty.toString()).toBe("2 m"); expect(qty.toString("cm")).toBe("200 cm"); expect(qty.toString("km")).toBe("0.002 km"); expect(function() { qty.toString("A"); }).toThrowError("Incompatible units: m and A"); qty = Qty("24.5m/s"); expect(qty.toString()).toBe("24.5 m/s"); expect(function() { qty.toString("m"); }).toThrowError("Incompatible units: m/s and m"); expect(qty.toString("km/h")).toBe("88.2 km/h"); qty = Qty("254kg/m^2"); expect(qty.toString()).toBe("254 kg/m2"); qty = Qty("2"); expect(qty.toString()).toBe("2"); }); it("should round readable human output when max decimals is specified", function() { var qty = (Qty("2m")).div(3); expect(qty.toString("cm", 2)).toBe("66.67 cm"); qty = Qty("2.8m"); expect(qty.toString("m", 0)).toBe("3 m"); expect(qty.toString("cm", 0)).toBe("280 cm"); qty = Qty("2.818m"); expect(qty.toString("cm", 0)).toBe("282 cm"); }); it("should round to max decimals", function() { var qty = (Qty("2.987654321 m")); expect(qty.toString(3)).toBe("2.988 m"); expect(qty.toString(0)).toBe("3 m"); }); it("should round according to precision passed as quantity", function() { var qty = Qty("5.17 ft"); expect(qty.toString(Qty("ft"))).toBe("5 ft"); expect(qty.toString(Qty("2 ft"))).toBe("6 ft"); expect(qty.toString(Qty("0.5 ft"))).toBe("5 ft"); expect(qty.toString(Qty("0.1 ft"))).toBe("5.2 ft"); expect(qty.toString(Qty("0.05 ft"))).toBe("5.15 ft"); expect(qty.toString(Qty("0.01 ft"))).toBe("5.17 ft"); expect(qty.toString(Qty("0.0001 ft"))).toBe("5.17 ft"); }); it("should return same output with successive calls", function() { var qty = Qty("123 cm3"); expect(qty.toString("cm3", 0)).toBe("123 cm3"); expect(qty.toString("cm3", 0)).toBe("123 cm3"); }); it("should return identical output when called with no parameters or same units", function() { var qty = Qty("123 cm3"); expect(qty.toString()).toBe(qty.toString("cm3")); }); }); describe("format", function() { describe("provided default formatter", function() { it("should be applied to output", function() { var qty = (Qty("2.987654321 m")); expect(qty.format()).toBe("2.987654321 m"); }); }); describe("custom formatter", function() { var roundingFormatter = function(maxDecimals) { return function(scalar, units) { var pow = Math.pow(10, maxDecimals); var rounded = Math.round(scalar * pow) / pow; return rounded + " " + units; }; }; it("should be applied to output", function() { var qty = (Qty("2.987654321 m")); expect(qty.format(roundingFormatter(3))).toBe("2.988 m"); expect(qty.format(roundingFormatter(0))).toBe("3 m"); }); it("should be applied after conversion to target units", function() { var qty = (Qty("2m")).div(3); expect(qty.format("cm", roundingFormatter(2))).toBe("66.67 cm"); var intRoundingFormatter = roundingFormatter(0); qty = Qty("2.8m"); expect(qty.format("m", intRoundingFormatter)).toBe("3 m"); expect(qty.format("cm", intRoundingFormatter)).toBe("280 cm"); qty = Qty("2.818m"); expect(qty.format("cm", intRoundingFormatter)).toBe("282 cm"); }); describe("globally set as default formatter", function() { var previousFormatter; beforeEach(function() { previousFormatter = Qty.formatter; Qty.formatter = roundingFormatter(3); }); afterEach(function() { // Restore previous formatter Qty.formatter = previousFormatter; }); it("should be applied when no formatter is passed", function() { var qty = (Qty("2.987654321 m")); expect(qty.format()).toBe("2.988 m"); }); }); }); }); describe("precision rounding", function() { it("should round according to precision passed as quantity with same units", function() { var qty = Qty("5.17 ft"); expect(qty.toPrec(Qty("ft")).toString()).toBe("5 ft"); expect(qty.toPrec(Qty("2 ft")).toString()).toBe("6 ft"); expect(qty.toPrec(Qty("10 ft")).toString()).toBe("10 ft"); expect(qty.toPrec(Qty("0.5 ft")).toString()).toBe("5 ft"); expect(qty.toPrec(Qty("0.1 ft")).toString()).toBe("5.2 ft"); expect(qty.toPrec(Qty("0.05 ft")).toString()).toBe("5.15 ft"); expect(qty.toPrec(Qty("0.01 ft")).toString()).toBe("5.17 ft"); expect(qty.toPrec(Qty("0.0001 ft")).toString()).toBe("5.17 ft"); expect(qty.toPrec(Qty("0.25 ft")).toString()).toBe("5.25 ft"); }); it("should allow string as precision parameter", function() { var qty = Qty("5.17 ft"); expect(qty.toPrec("ft").toString()).toBe("5 ft"); expect(qty.toPrec("0.5 ft").toString()).toBe("5 ft"); expect(qty.toPrec("0.05 ft").toString()).toBe("5.15 ft"); }); it("should round according to precision passed as quantity with different prefixes", function() { var qty = Qty("6.3782 m"); expect(qty.toPrec(Qty("dm")).toString()).toBe("6.4 m"); expect(qty.toPrec(Qty("cm")).toString()).toBe("6.38 m"); expect(qty.toPrec(Qty("mm")).toString()).toBe("6.378 m"); expect(qty.toPrec(Qty("5 cm")).toString()).toBe("6.4 m"); }); it("should round according to precision passed as quantity with different compatible units", function() { var qty = Qty("1.146 MPa"); expect(qty.toPrec(Qty("0.1 bar")).toString()).toBe("1.15 MPa"); expect(qty.toPrec(Qty("0.01 MPa")).toString()).toBe("1.15 MPa"); expect(qty.toPrec(Qty("dbar")).toString()).toBe("1.15 MPa"); // Tests below are mainly a safety net because not sure if there is // any usefulness to do things like that qty = Qty("5.171234568 ft"); expect(qty.toPrec(Qty("m")).toString()).toBe("6.561679790026248 ft"); expect(qty.toPrec(Qty("dm")).toString()).toBe("5.249343832020998 ft"); expect(qty.toPrec(Qty("cm")).toString()).toBe("5.183727034120736 ft"); expect(qty.toPrec(Qty("mm")).toString()).toBe("5.170603674540684 ft"); }); }); describe("mulSafe", function() { it("should multiply while trying to avoid numerical errors", function() { expect(Qty.mulSafe(0.1, 0.1)).toBe(0.01); expect(Qty.mulSafe(1e-11, 123.456789)).toBe(1.23456789e-9); expect(Qty.mulSafe(6e-12, 100000)).toBe(6e-7); }); }); describe("divSafe", function() { it("should divide while trying to avoid numerical errors", function() { expect(Qty.divSafe(0.000773, 0.000001)).toBe(773); // TODO uncomment and fix //expect(Qty.divSafe(24.5, 0.2777777777777778)).toBe(88.2); }); }); describe("Qty.parse", function() { it("should throw if parsed argument is not a string", function() { expect(function() { Qty.parse(5); }).toThrowError("Argument should be a string"); }); it("should not throw if parsed argument is a string", function() { expect(function() { Qty.parse("foo"); }).not.toThrowError("Argument should be a string"); }); it("should return parsed quantity when passing a valid quantity", function() { expect((Qty.parse("2.5 m") instanceof Qty)).toBe(true); }); it("should return null when passing an invalid quantity", function() { expect(Qty.parse("aa")).toBeNull(); }); it("should work", function() { expect(function() { Qty.parse("VL170111115924"); }).not.toThrow(); }); }); describe("Qty.swiftConverter", function() { it("should return a function", function() { expect(typeof Qty.swiftConverter("m/h", "ft/s")).toBe("function"); }); it("should throw when passing incompatible units", function() { expect(function() { Qty.swiftConverter("m", "s"); }).toThrowError("Incompatible units: m and s"); }); describe("converter", function() { describe("single value", function() { it("should convert value", function() { // TODO Same test but with m/h -> ft/s triggers rounding issue // (For the sake of speed, converter does not check and fix rounding issues) var converter = Qty.swiftConverter("m/h", "m/s"); expect(converter(2500)).toEqual(Qty("2500 m/h").to("m/s").scalar); }); it("should returned value unchanged when units are identical", function() { var converter = Qty.swiftConverter("m/h", "m/h"); expect(converter(2500)).toEqual(2500); }); it("should convert temperatures", function() { var converter = Qty.swiftConverter("tempF", "tempC"); expect(converter(32)).toEqual(0); }); it("should convert degrees", function() { var converter = Qty.swiftConverter("degC", "degF"); expect(converter(10)).toEqual(18); }); }); describe("array of values", function() { it("should be converted", function() { var converter = Qty.swiftConverter("MPa", "bar"); var values = [250, 10, 15]; var expected = [2500, 100, 150]; expect(converter(values)).toEqual(expected); }); }); }); }); describe("Qty.getKinds", function() { it("should return an array of kind names", function() { expect(Qty.getKinds()).toContain("resistance"); }); it("should not contain duplicate kind names", function() { var kinds = Qty.getKinds(); var map = {}; kinds.forEach(function(kind) { map[kind] = 1; }); expect(kinds.length).toEqual(Object.keys(map).length); }); }); describe("Qty.getUnits", function() { it("should return an array of units of kind", function() { expect(Qty.getUnits("currency")).toContain("dollar"); }); it("should return correct units for molar_concentration", function() { expect(Qty.getUnits("molar_concentration")).toContain("molar"); expect(Qty.getUnits("molar_concentration")).toContain("wtpercent"); }); it("should return an array of all units without arg", function() { expect(Qty.getUnits()).toContain("sievert"); }); it("should throw unknown kind", function() { expect(function() { Qty.getUnits("bogusKind"); }).toThrowError("Kind not recognized"); }); }); describe("Qty.getAliases", function() { it("should return array of alternative names for unit", function() { expect(Qty.getAliases("m")).toContain("meter"); expect(Qty.getAliases("meter")).toContain("metre"); expect(Qty.getAliases("N")).toContain("newton"); }); }); describe("information", function() { describe("bits and bytes", function() { it("should have 'information' as kind", function() { expect(Qty("3 b").kind()).toBe("information"); expect(Qty("5 B").kind()).toBe("information"); }); it("could be pluralized", function() { expect(Qty("3 bits").eq(Qty("3 b"))).toBe(true); expect(Qty("5 bytes").eq(Qty("5 B"))).toBe(true); }); }); describe("rate", function() { it("should accept bps and Bps aliases", function() { expect(Qty("3 bps").eq(Qty("3 b/s"))).toBe(true); expect(Qty("5 Bps").eq(Qty("5 B/s"))).toBe(true); }); it("should be parsed when prefixed", function() { expect(Qty("3 kbps").eq(Qty("3 kb/s"))).toBe(true); expect(Qty("5 MBps").eq(Qty("5 MB/s"))).toBe(true); }); it("should have 'information_rate' as kind", function() { expect(Qty("3 bps").kind()).toBe("information_rate"); expect(Qty("5 Bps").kind()).toBe("information_rate"); }); }); }); describe("non regression tests", function() { describe("Wh (#38)", function() { it("should be parsed", function() { expect(Qty("Wh").eq(Qty("3600 J"))).toBe(true); }); it("should be parsed when prefixed", function() { expect(Qty("kWh").eq(Qty("1000 Wh"))).toBe(true); }); }); describe("Ah (#25)", function() { it("should be parsed", function() { expect(Qty("Ah").eq(Qty("3600 C"))).toBe(true); }); it("should be parsed when prefixed", function() { expect(Qty("mAh").eq(Qty("3.6 C"))).toBe(true); }); }); describe("Farad (#67)", function() { it("should be equal to its definition", function() { expect(Qty("1 F").eq(Qty("1 C").div(Qty("1 V")))).toBe(true); }); it("should not be defined as base unit", function() { var qty = Qty("F"); expect(qty.isBase()).toBe(false); expect(qty.toBase().units()).toEqual("s4*A2/m2*kg"); }); it("should be parsed when prefixed", function() { var qty = Qty("100 nF"); expect(qty.eq(Qty("100 F").div(1e9))).toBe(true); expect(qty.baseScalar).toEqual(1e-7); }); }); describe("elementary charge (#141)", function() { it("should be parsed", function() { expect(Qty("e").eq(Qty("1.602176634e-19 C"))).toBe(true); expect(Qty("1e").eq(Qty("1.602176634e-19 C"))).toBe(true); expect(Qty("1 e").eq(Qty("1.602176634e-19 C"))).toBe(true); expect(Qty(1, "e").eq(Qty("1.602176634e-19 C"))).toBe(true); expect(Qty("e2").isCompatible(Qty("C^2"))).toBe(true); }); it("should match electronvolt (eV) definition", function() { expect((Qty("1 e").mul(Qty("1 V"))).eq(Qty("1 eV"))).toBe(true); }); it("should not impact exponent notation", function() { expect(Qty("1e2").eq(Qty("100"))).toBe(true); expect(Qty("3e8 m/s").eq(Qty("300000 km/s"))).toBe(true); }); }); describe("Square foot definition (#146)", function() { it("should not be equal to square meter", function() { expect(Qty("1 sqft").eq(Qty("1 m2"))).toBe(false); }); it("should be correctly defined", function() { expect(Qty("1 sqft").eq(Qty("1 ft").mul(Qty("1 ft")))).toBe(true); expect(Qty(1, "sqft").to("m2").format()).toBe("0.09290304 m2"); }); }); }); }); ================================================ FILE: spec/support/jasmine.json ================================================ { "spec_dir": "spec", "spec_files": [ "**/*[sS]pec.js" ], "helpers": [ "helpers/**/*.js" ], "stopSpecOnExpectationFailure": false, "random": false } ================================================ FILE: src/quantities/comparators.js ================================================ import Qty from "./constructor.js"; import { assign, isString } from "./utils.js"; import { throwIncompatibleUnits } from "./error.js"; assign(Qty.prototype, { 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); }, // 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(this.units(), other.units()); } 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()); } }); ================================================ FILE: src/quantities/constructor.js ================================================ import { UNITY_ARRAY } from "./definitions.js"; import { unitSignature } from "./signature.js"; import parse from "./parse.js"; import QtyError from "./error.js"; import { compareArray, isNumber, isString } from "./utils.js"; /** * Tests if a value is a Qty instance * * @param {*} value - Value to test * * @returns {boolean} true if value is a Qty instance, false otherwise */ export function isQty(value) { return value instanceof Qty; } export default function Qty(initValue, initUnits) { assertValidConstructorArgs.apply(null, arguments); if (!(isQty(this))) { return new Qty(initValue, initUnits); } 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 if (initUnits) { parse.call(this, initUnits); this.scalar = initValue; } 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"); } } Qty.prototype = { // Properly set up constructor constructor: Qty, }; /** * Asserts constructor arguments are valid * * @param {*} value - Value to test * @param {string} [units] - Optional units when value is passed as a number * * @returns {void} * @throws {QtyError} if constructor arguments are invalid */ function assertValidConstructorArgs(value, units) { if (units) { if (!(isNumber(value) && isString(units))) { throw new QtyError("Only number accepted as initialization value " + "when units are explicitly provided"); } } else { if (!(isString(value) || isNumber(value) || isQty(value) || isDefinitionObject(value))) { throw new QtyError("Only string, number or quantity accepted as " + "single initialization value"); } } } /** * Tests if a value is a Qty definition object * * @param {*} value - Value to test * * @returns {boolean} true if value is a definition object, false otherwise */ function isDefinitionObject(value) { return value && typeof value === "object" && value.hasOwnProperty("scalar"); } function updateBaseScalar() { 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; } } ================================================ FILE: src/quantities/conversion.js ================================================ import Qty from "./constructor.js"; import { PREFIX_VALUES, UNIT_VALUES } from "./definitions.js"; import {toDegrees, toTemp, toTempK } from "./temperature.js"; import { assign, divSafe, identity, isNumber, isString, mulSafe } from "./utils.js"; import QtyError, { throwIncompatibleUnits } from "./error.js"; assign(Qty.prototype, { /** * 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 === undefined || other === null) { return this; } if (!isString(other)) { return this.to(other.units()); } cached = this._conversionCache[other]; if (cached) { return cached; } // Instantiating target to normalize units target = Qty(other); if (target.units() === this.units()) { return this; } if (!this.isCompatible(target)) { if (this.isInverse(target)) { target = this.inverse().to(other); } else { throwIncompatibleUnits(this.units(), target.units()); } } else { if (target.isTemperature()) { target = toTemp(this,target); } else if (target.isDegrees()) { target = toDegrees(this,target); } else { var q = divSafe(this.baseScalar, target.baseScalar); target = Qty({"scalar": q, "numerator": target.numerator, "denominator": target.denominator}); } } this._conversionCache[other] = target; return target; }, // 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); }, // 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 the nearest multiple of quantity passed as * precision * * @param {(Qty|string|number)} precQuantity - 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(this.units(), precQuantity.units()); } 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()); } }); /** * 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); * */ export 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; } }; } var baseUnitCache = {}; function toBaseUnits(numerator,denominator) { var num = []; var den = []; var q = 1; var unit; for (var i = 0; i < numerator.length; i++) { unit = numerator[i]; if (PREFIX_VALUES[unit]) { // workaround to fix // 0.1 * 0.1 => 0.010000000000000002 q = mulSafe(q, PREFIX_VALUES[unit]); } else { if (UNIT_VALUES[unit]) { q *= UNIT_VALUES[unit].scalar; if (UNIT_VALUES[unit].numerator) { num.push(UNIT_VALUES[unit].numerator); } if (UNIT_VALUES[unit].denominator) { den.push(UNIT_VALUES[unit].denominator); } } } } for (var j = 0; j < denominator.length; j++) { unit = denominator[j]; if (PREFIX_VALUES[unit]) { q /= PREFIX_VALUES[unit]; } else { if (UNIT_VALUES[unit]) { q /= UNIT_VALUES[unit].scalar; if (UNIT_VALUES[unit].numerator) { den.push(UNIT_VALUES[unit].numerator); } if (UNIT_VALUES[unit].denominator) { num.push(UNIT_VALUES[unit].denominator); } } } } // Flatten num = num.reduce(function(a,b) { return a.concat(b); }, []); den = den.reduce(function(a,b) { return a.concat(b); }, []); return Qty({"scalar": q, "numerator": num, "denominator": den}); } ================================================ FILE: src/quantities/definitions.js ================================================ import { isNumber } from "./utils.js"; import QtyError from "./error.js"; export 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","\u03BC"/*µ as greek letter*/,"\u00B5"/*µ as micro sign*/,"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","naut-mile"], 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", "redshift"], 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>"]], "<datamile>" : [["DM","datamile"], 1828.8, "length", ["<meter>"]], /* mass */ "<kilogram>" : [["kg","kilogram","kilograms"], 1.0, "mass", ["<kilogram>"]], "<AMU>" : [["u","AMU","amu"], 1.660538921e-27, "mass", ["<kilogram>"]], "<dalton>" : [["Da","Dalton","Daltons","dalton","daltons"], 1.660538921e-27, "mass", ["<kilogram>"]], "<slug>" : [["slug","slugs"], 14.5939029, "mass", ["<kilogram>"]], "<short-ton>" : [["tn","ton","short-ton"], 907.18474, "mass", ["<kilogram>"]], "<metric-ton>":[["t","tonne","metric-ton"], 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"], 0.09290304, "area", ["<foot>","<foot>"]], /* volume */ "<liter>" : [["l","L","liter","liters","litre","litres"], 0.001, "volume", ["<meter>","<meter>","<meter>"]], "<gallon>": [["gal","gallon","gallons"], 0.0037854118, "volume", ["<meter>","<meter>","<meter>"]], "<gallon-imp>": [["galimp","gallon-imp","gallons-imp"], 0.0045460900, "volume", ["<meter>","<meter>","<meter>"]], "<quart>": [["qt","quart","quarts"], 0.00094635295, "volume", ["<meter>","<meter>","<meter>"]], "<pint>": [["pt","pint","pints"], 0.000473176475, "volume", ["<meter>","<meter>","<meter>"]], "<pint-imp>": [["ptimp","pint-imp","pints-imp"], 5.6826125e-4, "volume", ["<meter>","<meter>","<meter>"]], "<cup>": [["cu","cup","cups"], 0.000236588238, "volume", ["<meter>","<meter>","<meter>"]], "<fluid-ounce>": [["floz","fluid-ounce","fluid-ounces"], 2.95735297e-5, "volume", ["<meter>","<meter>","<meter>"]], "<fluid-ounce-imp>": [["flozimp", "floz-imp","fluid-ounce-imp","fluid-ounces-imp"], 2.84130625e-5, "volume", ["<meter>","<meter>","<meter>"]], "<tablespoon>": [["tb","tbsp","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>"]], "<oilbarrel>": [["bbl","oilbarrel", "oilbarrels", "oil-barrel","oil-barrels"], 0.158987294928, "volume", ["<meter>","<meter>","<meter>"]], "<beerbarrel>": [["bl","bl-us","beerbarrel", "beerbarrels", "beer-barrel","beer-barrels"], 0.1173477658, "volume", ["<meter>","<meter>","<meter>"]], "<beerbarrel-imp>": [["blimp","bl-imp","beerbarrel-imp", "beerbarrels-imp", "beer-barrel-imp","beer-barrels-imp"], 0.16365924, "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>"]], "<Gal>" : [["Gal"], 1e-2, "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","temp-K"], 1.0, "temperature", ["<temp-K>"]], "<temp-C>" : [["tempC","temp-C"], 1.0, "temperature", ["<temp-K>"]], "<temp-F>" : [["tempF","temp-F"], 5 / 9, "temperature", ["<temp-K>"]], "<temp-R>" : [["tempR","temp-R"], 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","cmh2o"], 98.0638, "pressure", ["<kilogram>"],["<meter>","<second>","<second>"]], "<inh2o>" : [["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>"]], /* molar_concentration */ "<molar>" : [["M","molar"], 1000, "molar_concentration", ["<mole>"], ["<meter>","<meter>","<meter>"]], "<wtpercent>" : [["wt%","wtpercent"], 10, "molar_concentration", ["<kilogram>"], ["<meter>","<meter>","<meter>"]], /* activity */ "<katal>" : [["kat","katal","Katal"], 1.0, "activity", ["<mole>"], ["<second>"]], "<unit>" : [["U","enzUnit","unit"], 16.667e-16, "activity", ["<mole>"], ["<second>"]], /* capacitance */ "<farad>" : [["F","farad","Farad"], 1.0, "capacitance", ["<second>","<second>","<second>","<second>","<ampere>","<ampere>"], ["<meter>", "<meter>", "<kilogram>"]], /* charge */ "<coulomb>" : [["C","coulomb","Coulomb"], 1.0, "charge", ["<ampere>","<second>"]], "<Ah>" : [["Ah"], 3600, "charge", ["<ampere>","<second>"]], "<elementary-charge>" : [["e"], 1.602176634e-19, "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","\u03A9"/*Ω as greek letter*/,"\u2126"/*Ω as ohm sign*/], 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","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","therm-US"], 105480400, "energy",["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]], "<Wh>" : [["Wh"], 3600, "energy",["<meter>","<meter>","<kilogram>"], ["<second>","<second>"]], "<electronvolt>" : [["eV", "electronvolt", "electronvolts"], 1.602176634E-19, "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>"]], "<kilogram-force>" : [["kgf","kilogram-force", "kilopond", "kp"], 9.80665, "force", ["<kilogram>","<meter>"], ["<second>","<second>"]], "<gram-force>" : [["gf","gram-force"], 9.80665E-3, "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>"]], "<arcminute>" :[["arcmin","arcminute","arcminutes"], Math.PI / 10800.0, "angle", ["<radian>"]], "<arcsecond>" :[["arcsec","arcsecond","arcseconds"], Math.PI / 648000.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>"]], /* information */ "<byte>" :[["B","byte","bytes"], 1.0, "information", ["<byte>"]], "<bit>" :[["b","bit","bits"], 0.125, "information", ["<byte>"]], /* information rate */ "<Bps>" : [["Bps"], 1.0, "information_rate", ["<byte>"], ["<second>"]], "<bps>" : [["bps"], 0.125, "information_rate", ["<byte>"], ["<second>"]], /* 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>"]], "<volt-ampere>" : [["VA","volt-ampere"], 1.0, "power", ["<kilogram>","<meter>","<meter>"], ["<second>","<second>","<second>"]], "<volt-ampere-reactive>" : [["var","Var","VAr","VAR","volt-ampere-reactive"], 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","becquerel","becquerels"], 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","base-pair"], 1.0, "counting", ["<each>"]], "<nucleotide>" : [["nt","nucleotide"], 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>"]], "<ppb>" : [["ppb"],1e-9, "prefix_only", ["<1>"]], "<ppt>" : [["ppt"],1e-12, "prefix_only", ["<1>"]], "<ppq>" : [["ppq"],1e-15, "prefix_only", ["<1>"]], "<gross>" : [["gr","gross"],144.0, "prefix_only", ["<dozen>","<dozen>"]], "<decibel>" : [["dB","decibel","decibels"], 1.0, "logarithmic", ["<decibel>"]] }; export var BASE_UNITS = ["<meter>","<kilogram>","<second>","<mole>", "<ampere>","<radian>","<kelvin>","<temp-K>","<byte>","<dollar>","<candela>","<each>","<steradian>","<decibel>"]; export var UNITY = "<1>"; export var UNITY_ARRAY = [UNITY]; // Setup /** * Asserts unit definition is valid * * @param {string} unitDef - Name of unit to test * @param {Object} definition - Definition of unit to test * * @returns {void} * @throws {QtyError} if unit definition is not valid */ function validateUnitDefinition(unitDef, definition) { var scalar = definition[1]; var numerator = definition[3] || []; var denominator = definition[4] || []; if (!isNumber(scalar)) { throw new QtyError(unitDef + ": Invalid unit definition. " + "'scalar' must be a number"); } numerator.forEach(function(unit) { if (UNITS[unit] === undefined) { throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'numerator' is not recognized"); } }); denominator.forEach(function(unit) { if (UNITS[unit] === undefined) { throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'denominator' is not recognized"); } }); } export var PREFIX_VALUES = {}; export var PREFIX_MAP = {}; export var UNIT_VALUES = {}; export var UNIT_MAP = {}; export var OUTPUT_MAP = {}; for (var unitDef in UNITS) { if (UNITS.hasOwnProperty(unitDef)) { var definition = UNITS[unitDef]; if (definition[2] === "prefix") { PREFIX_VALUES[unitDef] = definition[1]; for (var i = 0; i < definition[0].length; i++) { PREFIX_MAP[definition[0][i]] = unitDef; } } else { validateUnitDefinition(unitDef, definition); UNIT_VALUES[unitDef] = { scalar: definition[1], numerator: definition[3], denominator: definition[4] }; for (var j = 0; j < definition[0].length; j++) { UNIT_MAP[definition[0][j]] = unitDef; } } OUTPUT_MAP[unitDef] = definition[0][0]; } } /** * Returns a list of available units of kind * * @param {string} [kind] - kind of units * @returns {array} names of units * @throws {QtyError} if kind is unknown */ export function getUnits(kind) { var i; var units = []; var unitKeys = Object.keys(UNITS); if (typeof kind === "undefined") { for (i = 0; i < unitKeys.length; i++) { if (["", "prefix"].indexOf(UNITS[unitKeys[i]][2]) === -1) { units.push(unitKeys[i].substr(1, unitKeys[i].length - 2)); } } } else if (this.getKinds().indexOf(kind) === -1) { throw new QtyError("Kind not recognized"); } else { for (i = 0; i < unitKeys.length; i++) { if (UNITS[unitKeys[i]][2] === kind) { units.push(unitKeys[i].substr(1, unitKeys[i].length - 2)); } } } return units.sort(function(a, b) { if (a.toLowerCase() < b.toLowerCase()) { return -1; } if (a.toLowerCase() > b.toLowerCase()) { return 1; } return 0; }); } /** * Returns a list of alternative names for a unit * * @param {string} unitName - name of unit * @returns {string[]} aliases for unit * @throws {QtyError} if unit is unknown */ export function getAliases(unitName) { if (!UNIT_MAP[unitName]) { throw new QtyError("Unit not recognized"); } return UNITS[UNIT_MAP[unitName]][0]; } ================================================ FILE: src/quantities/error.js ================================================ /** * Custom error type definition * @constructor */ export default function QtyError() { var err; if (!this) { // Allows to instantiate QtyError without new() err = Object.create(QtyError.prototype); QtyError.apply(err, arguments); return err; } err = Error.apply(this, arguments); this.name = "QtyError"; this.message = err.message; this.stack = err.stack; } QtyError.prototype = Object.create(Error.prototype, {constructor: { value: QtyError }}); /* * Throws incompatible units error * @param {string} left - units * @param {string} right - units incompatible with first argument * @throws "Incompatible units" error */ export function throwIncompatibleUnits(left, right) { throw new QtyError("Incompatible units: " + left + " and " + right); } ================================================ FILE: src/quantities/format.js ================================================ import Qty, { isQty } from "./constructor.js"; import { PREFIX_VALUES, OUTPUT_MAP, UNITY_ARRAY } from "./definitions.js"; import { assign, compareArray, isNumber, isString, round } from "./utils.js"; import NestedMap from "./nested-map.js"; /** * Default formatter * * @param {number} scalar - scalar value * @param {string} units - units as string * * @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; assign(Qty.prototype, { // 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); var denIsUnity = compareArray(this.denominator, UNITY_ARRAY); if (numIsUnity && denIsUnity) { this._units = ""; return this._units; } var numUnits = stringifyUnits(this.numerator); var denUnits = stringifyUnits(this.denominator); this._units = numUnits + (denIsUnity ? "" : ("/" + denUnits)); return 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()); } }); var stringifiedUnitsCache = new NestedMap(); /** * Returns a string representing a normalized unit array * * @param {string[]} units Normalized unit array * @returns {string} String representing passed normalized unit array and * suitable for output * */ function stringifyUnits(units) { var stringified = stringifiedUnitsCache.get(units); if (stringified) { return stringified; } var isUnity = compareArray(units, UNITY_ARRAY); if (isUnity) { stringified = "1"; } else { stringified = simplify(getOutputNames(units)).join("*"); } // Cache result stringifiedUnitsCache.set(units, stringified); return stringified; } function getOutputNames(units) { var unitNames = [], token, tokenNext; for (var i = 0; i < units.length; i++) { token = units[i]; tokenNext = units[i + 1]; if (PREFIX_VALUES[token]) { unitNames.push(OUTPUT_MAP[token] + OUTPUT_MAP[tokenNext]); i++; } else { unitNames.push(OUTPUT_MAP[token]); } } return unitNames; } function simplify(units) { // this turns ['s','m','s'] into ['s2','m'] var unitCounts = units.reduce(function(acc, unit) { var unitCounter = acc[unit]; if (!unitCounter) { acc.push(unitCounter = acc[unit] = [unit, 0]); } unitCounter[1]++; return acc; }, []); return unitCounts.map(function(unitCount) { return unitCount[0] + (unitCount[1] > 1 ? unitCount[1] : ""); }); } ================================================ FILE: src/quantities/global-api.js ================================================ import { globalParse } from "./parse.js"; import { divSafe, mulSafe } from "./utils.js"; import { getAliases, getUnits } from "./definitions.js"; import { getKinds } from "./kind.js"; import { swiftConverter } from "./conversion.js"; import QtyError from "./error.js"; import Qty from "./constructor.js"; Qty.parse = globalParse; Qty.getUnits = getUnits; Qty.getAliases = getAliases; Qty.mulSafe = mulSafe; Qty.divSafe = divSafe; Qty.getKinds = getKinds; Qty.swiftConverter = swiftConverter; Qty.Error = QtyError; ================================================ FILE: src/quantities/kind.js ================================================ import Qty from "./constructor.js"; import { uniq } from "./utils.js"; var KINDS = { "-312078": "elastance", "-312058": "resistance", "-312038": "inductance", "-152058": "potential", "-152040": "magnetism", "-152038": "magnetism", "-7997": "specific_volume", "-79": "snap", "-59": "jolt", "-39": "acceleration", "-38": "radiation", "-20": "frequency", "-19": "speed", "-18": "viscosity", "-17": "volumetric_flow", "-1": "wavenumber", "0": "unitless", "1": "length", "2": "area", "3": "volume", "20": "time", "400": "temperature", "7941": "yank", "7942": "power", "7959": "pressure", "7961": "force", "7962": "energy", "7979": "viscosity", "7981": "momentum", "7982": "angular_momentum", "7997": "density", "7998": "area_density", "8000": "mass", "152020": "radiation_exposure", "159999": "magnetism", "160000": "current", "160020": "charge", "312058": "conductance", "312078": "capacitance", "3199980": "activity", "3199997": "molar_concentration", "3200000": "substance", "63999998": "illuminance", "64000000": "luminous_power", "1280000000": "currency", "25599999980": "information_rate", "25600000000": "information", "511999999980": "angular_velocity", "512000000000": "angle" }; /** * Returns the list of available well-known kinds of units, e.g. * "radiation" or "length". * * @returns {string[]} names of kinds of units */ export function getKinds() { return uniq(Object.keys(KINDS).map(function(knownSignature) { return KINDS[knownSignature]; })); } Qty.prototype.kind = function() { return KINDS[this.signature.toString()]; }; ================================================ FILE: src/quantities/nested-map.js ================================================ export default function NestedMap() {} NestedMap.prototype.get = function(keys) { // Allows to pass key1, key2, ... instead of [key1, key2, ...] if (arguments.length > 1) { // Slower with Firefox but faster with Chrome than // Array.prototype.slice.call(arguments) // See http://jsperf.com/array-apply-versus-array-prototype-slice-call keys = Array.apply(null, arguments); } return keys.reduce(function(map, key, index) { if (map) { var childMap = map[key]; if (index === keys.length - 1) { return childMap ? childMap.data : undefined; } else { return childMap; } } }, this); }; NestedMap.prototype.set = function(keys, value) { if (arguments.length > 2) { keys = Array.prototype.slice.call(arguments, 0, -1); value = arguments[arguments.length - 1]; } return keys.reduce(function(map, key, index) { var childMap = map[key]; if (childMap === undefined) { childMap = map[key] = {}; } if (index === keys.length - 1) { childMap.data = value; return value; } else { return childMap; } }, this); }; ================================================ FILE: src/quantities/operators.js ================================================ import Qty from "./constructor.js"; import QtyError, { throwIncompatibleUnits } from "./error.js"; import { PREFIX_VALUES, UNITY, UNITY_ARRAY } from "./definitions.js"; import { assign, isNumber, isString, mulSafe, divSafe } from "./utils.js"; import { addTempDegrees, subtractTempDegrees, subtractTemperatures } from "./temperature.js"; assign(Qty.prototype, { // Returns new instance with units of this add: function(other) { if (isString(other)) { other = Qty(other); } if (!this.isCompatible(other)) { throwIncompatibleUnits(this.units(), other.units()); } if (this.isTemperature() && other.isTemperature()) { throw new QtyError("Cannot add two temperatures"); } else if (this.isTemperature()) { return addTempDegrees(this, other); } else if (other.isTemperature()) { return addTempDegrees(other, this); } return Qty({"scalar": this.scalar + other.to(this).scalar, "numerator": this.numerator, "denominator": this.denominator}); }, sub: function(other) { if (isString(other)) { other = Qty(other); } if (!this.isCompatible(other)) { throwIncompatibleUnits(this.units(), other.units()); } if (this.isTemperature() && other.isTemperature()) { return subtractTemperatures(this,other); } else if (this.isTemperature()) { return subtractTempDegrees(this,other); } else if (other.isTemperature()) { throw new QtyError("Cannot subtract a temperature from a differential degree unit"); } return Qty({"scalar": this.scalar - other.to(this).scalar, "numerator": this.numerator, "denominator": this.denominator}); }, mul: function(other) { if (isNumber(other)) { return Qty({"scalar": mulSafe(this.scalar, other), "numerator": this.numerator, "denominator": this.denominator}); } else if (isString(other)) { other = Qty(other); } if ((this.isTemperature() || other.isTemperature()) && !(this.isUnitless() || other.isUnitless())) { throw new QtyError("Cannot multiply by temperatures"); } // Quantities should be multiplied with same units if compatible, with base units else var op1 = this; var op2 = other; // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC" if (op1.isCompatible(op2) && op1.signature !== 400) { op2 = op2.to(op1); } var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.numerator, op2.denominator); return Qty({"scalar": mulSafe(op1.scalar, op2.scalar, numdenscale[2]), "numerator": numdenscale[0], "denominator": numdenscale[1]}); }, div: function(other) { if (isNumber(other)) { if (other === 0) { throw new QtyError("Divide by zero"); } return Qty({"scalar": this.scalar / other, "numerator": this.numerator, "denominator": this.denominator}); } else if (isString(other)) { other = Qty(other); } if (other.scalar === 0) { throw new QtyError("Divide by zero"); } if (other.isTemperature()) { throw new QtyError("Cannot divide with temperatures"); } else if (this.isTemperature() && !other.isUnitless()) { throw new QtyError("Cannot divide with temperatures"); } // Quantities should be multiplied with same units if compatible, with base units else var op1 = this; var op2 = other; // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC" if (op1.isCompatible(op2) && op1.signature !== 400) { op2 = op2.to(op1); } var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.denominator, op2.numerator); return Qty({"scalar": mulSafe(op1.scalar, numdenscale[2]) / op2.scalar, "numerator": numdenscale[0], "denominator": numdenscale[1]}); }, // 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}); } }); function cleanTerms(num1, den1, num2, den2) { function notUnity(val) { return val !== UNITY; } num1 = num1.filter(notUnity); num2 = num2.filter(notUnity); den1 = den1.filter(notUnity); den2 = den2.filter(notUnity); var combined = {}; function combineTerms(terms, direction) { var k; var prefix; var prefixValue; for (var i = 0; i < terms.length; i++) { if (PREFIX_VALUES[terms[i]]) { k = terms[i + 1]; prefix = terms[i]; prefixValue = PREFIX_VALUES[prefix]; i++; } else { k = terms[i]; prefix = null; prefixValue = 1; } if (k && k !== UNITY) { if (combined[k]) { combined[k][0] += direction; var combinedPrefixValue = combined[k][2] ? PREFIX_VALUES[combined[k][2]] : 1; combined[k][direction === 1 ? 3 : 4] *= divSafe(prefixValue, combinedPrefixValue); } else { combined[k] = [direction, k, prefix, 1, 1]; } } } } combineTerms(num1, 1); combineTerms(den1, -1); combineTerms(num2, 1); combineTerms(den2, -1); var num = []; var den = []; var scale = 1; for (var prop in combined) { if (combined.hasOwnProperty(prop)) { var item = combined[prop]; var n; if (item[0] > 0) { for (n = 0; n < item[0]; n++) { num.push(item[2] === null ? item[1] : [item[2], item[1]]); } } else if (item[0] < 0) { for (n = 0; n < -item[0]; n++) { den.push(item[2] === null ? item[1] : [item[2], item[1]]); } } scale *= divSafe(item[3], item[4]); } } if (num.length === 0) { num = UNITY_ARRAY; } if (den.length === 0) { den = UNITY_ARRAY; } // Flatten num = num.reduce(function(a,b) { return a.concat(b); }, []); den = den.reduce(function(a,b) { return a.concat(b); }, []); return [num, den, scale]; } ================================================ FILE: src/quantities/parse.js ================================================ import { isString } from "./utils.js"; import QtyError from "./error.js"; import { PREFIX_MAP, UNIT_MAP } from "./definitions.js"; 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}"; // Allow unit powers representing scalar, length, area, volume; 4 is for some // special case representations in SI base units. var SAFE_POWER = "[01234]"; var TOP_REGEX = new RegExp ("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(-?" + SAFE_POWER + "(?![a-zA-Z]))"); var BOTTOM_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(" + SAFE_POWER + "(?![a-zA-Z]))"); /* 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 */ export default function parse(val) { if (!isString(val)) { val = val.toString(); } val = val.trim(); 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); } if (top) { this.numerator = parseUnits(top.trim()); } if (bottom) { this.denominator = parseUnits(bottom.trim()); } } var PREFIX_REGEX = Object.keys(PREFIX_MAP).sort(function(a, b) { return b.length - a.length; }).join("|"); var UNIT_REGEX = Object.keys(UNIT_MAP).sort(function(a, b) { return b.length - a.length; }).join("|"); /* * Minimal boundary regex to support units with Unicode characters * \b only works for ASCII */ var BOUNDARY_REGEX = "\\b|$"; var UNIT_MATCH = "(" + PREFIX_REGEX + ")??(" + UNIT_REGEX + ")(?:" + BOUNDARY_REGEX + ")"; var UNIT_TEST_REGEX = new RegExp("^\\s*(" + UNIT_MATCH + "[\\s\\*]*)+$"); var UNIT_MATCH_REGEX = new RegExp(UNIT_MATCH, "g"); // g flag for multiple occurences var parsedUnitsCache = {}; /** * Parses and converts units string to normalized unit array. * Result is cached to speed up next calls. * * @param {string} units Units string * @returns {string[]} Array of normalized units * * @example * // Returns ["<second>", "<meter>", "<second>"] * parseUnits("s m s"); * */ function parseUnits(units) { var cached = parsedUnitsCache[units]; if (cached) { return cached; } var unitMatch, normalizedUnits = []; // Scan if (!UNIT_TEST_REGEX.test(units)) { throw new QtyError("Unit not recognized"); } while ((unitMatch = UNIT_MATCH_REGEX.exec(units))) { normalizedUnits.push(unitMatch.slice(1)); } normalizedUnits = normalizedUnits.map(function(item) { return PREFIX_MAP[item[0]] ? [PREFIX_MAP[item[0]], UNIT_MAP[item[1]]] : [UNIT_MAP[item[1]]]; }); // Flatten and remove null elements normalizedUnits = normalizedUnits.reduce(function(a,b) { return a.concat(b); }, []); normalizedUnits = normalizedUnits.filter(function(item) { return item; }); parsedUnitsCache[units] = normalizedUnits; return normalizedUnits; } /** * 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 */ export function globalParse(value) { if (!isString(value)) { throw new QtyError("Argument should be a string"); } try { return this(value); } catch (e) { return null; } } ================================================ FILE: src/quantities/predicates.js ================================================ import Qty, { isQty } from "./constructor.js"; import { BASE_UNITS, UNITY, UNITY_ARRAY } from "./definitions.js"; import { assign, compareArray, isString } from "./utils.js"; assign(Qty.prototype, { // returns true if no associated units // false, even if the units are "unitless" like 'radians, each, etc' isUnitless: function() { return [this.numerator, this.denominator].every(function(item) { return compareArray(item, 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); }, // 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; } }); ================================================ FILE: src/quantities/signature.js ================================================ import { UNITS } from "./definitions.js"; var SIGNATURE_VECTOR = ["length", "time", "temperature", "mass", "current", "substance", "luminosity", "currency", "information", "angle"]; /* 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. */ export function unitSignature() { 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 function unitSignatureVector() { 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; } ================================================ FILE: src/quantities/temperature.js ================================================ import Qty from "./constructor.js"; import { UNITY_ARRAY } from "./definitions.js"; import QtyError from "./error.js"; import { assign, compareArray } from "./utils.js"; assign(Qty.prototype, { 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]>/); } }); export function subtractTemperatures(lhs,rhs) { var lhsUnits = lhs.units(); var rhsConverted = rhs.to(lhsUnits); var dstDegrees = Qty(getDegreeUnits(lhsUnits)); return Qty({"scalar": lhs.scalar - rhsConverted.scalar, "numerator": dstDegrees.numerator, "denominator": dstDegrees.denominator}); } export function subtractTempDegrees(temp,deg) { var tempDegrees = deg.to(getDegreeUnits(temp.units())); return Qty({"scalar": temp.scalar - tempDegrees.scalar, "numerator": temp.numerator, "denominator": temp.denominator}); } export function addTempDegrees(temp,deg) { var tempDegrees = deg.to(getDegreeUnits(temp.units())); return Qty({"scalar": temp.scalar + tempDegrees.scalar, "numerator": temp.numerator, "denominator": temp.denominator}); } function getDegreeUnits(units) { if (units === "tempK") { return "degK"; } else if (units === "tempC") { return "degC"; } else if (units === "tempF") { return "degF"; } else if (units === "tempR") { return "degR"; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } } export function toDegrees(src,dst) { var srcDegK = toDegK(src); var dstUnits = dst.units(); var dstScalar; if (dstUnits === "degK") { dstScalar = srcDegK.scalar; } else if (dstUnits === "degC") { dstScalar = srcDegK.scalar ; } else if (dstUnits === "degF") { dstScalar = srcDegK.scalar * 9 / 5; } else if (dstUnits === "degR") { dstScalar = srcDegK.scalar * 9 / 5; } else { throw new QtyError("Unknown type for degree conversion to: " + dstUnits); } return Qty({"scalar": dstScalar, "numerator": dst.numerator, "denominator": dst.denominator}); } function toDegK(qty) { var units = qty.units(); var q; if (units.match(/(deg)[CFRK]/)) { q = qty.baseScalar; } else if (units === "tempK") { q = qty.scalar; } else if (units === "tempC") { q = qty.scalar; } else if (units === "tempF") { q = qty.scalar * 5 / 9; } else if (units === "tempR") { q = qty.scalar * 5 / 9; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } return Qty({"scalar": q, "numerator": ["<kelvin>"], "denominator": UNITY_ARRAY}); } export function toTemp(src,dst) { var dstUnits = dst.units(); var dstScalar; if (dstUnits === "tempK") { dstScalar = src.baseScalar; } else if (dstUnits === "tempC") { dstScalar = src.baseScalar - 273.15; } else if (dstUnits === "tempF") { dstScalar = (src.baseScalar * 9 / 5) - 459.67; } else if (dstUnits === "tempR") { dstScalar = src.baseScalar * 9 / 5; } else { throw new QtyError("Unknown type for temp conversion to: " + dstUnits); } return Qty({"scalar": dstScalar, "numerator": dst.numerator, "denominator": dst.denominator}); } export function toTempK(qty) { var units = qty.units(); var q; if (units.match(/(deg)[CFRK]/)) { q = qty.baseScalar; } else if (units === "tempK") { q = qty.scalar; } else if (units === "tempC") { q = qty.scalar + 273.15; } else if (units === "tempF") { q = (qty.scalar + 459.67) * 5 / 9; } else if (units === "tempR") { q = qty.scalar * 5 / 9; } else { throw new QtyError("Unknown type for temp conversion from: " + units); } return Qty({"scalar": q, "numerator": ["<temp-K>"], "denominator": UNITY_ARRAY}); } ================================================ FILE: src/quantities/utils.js ================================================ /** * Tests if a value is a string * * @param {*} value - Value to test * * @returns {boolean} true if value is a string, false otherwise */ export function isString(value) { return typeof value === "string" || value instanceof String; } /* * Prefer stricter Number.isFinite if currently supported. * To be dropped when ES6 is finalized. Obsolete browsers will * have to use ES6 polyfills. */ var isFiniteImpl = Number.isFinite || window.isFinite; /** * Tests if a value is a number * * @param {*} value - Value to test * * @returns {boolean} true if value is a number, false otherwise */ export function isNumber(value) { // Number.isFinite allows not to consider NaN or '1' as numbers return isFiniteImpl(value); } /* * Identity function */ export function identity(value) { return value; } /** * Returns unique strings from list * * @param {string[]} strings - array of strings * * * @returns {string[]} a new array of strings without duplicates */ export function uniq(strings) { var seen = {}; return strings.filter(function(item) { return seen.hasOwnProperty(item) ? false : (seen[item] = true); }); } export function compareArray(array1, array2) { if (array2.length !== array1.length) { return false; } for (var i = 0; i < array1.length; i++) { if (array2[i].compareArray) { if (!array2[i].compareArray(array1[i])) { return false; } } if (array2[i] !== array1[i]) { return false; } } return true; } export function assign(target, properties) { Object.keys(properties).forEach(function(key) { target[key] = properties[key]; }); } /** * Safely multiplies numbers while avoiding floating errors * like 0.1 * 0.1 => 0.010000000000000002 * * @param {...number} numbers - numbers to multiply * * @returns {number} result */ export function mulSafe() { var result = 1, decimals = 0; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; decimals = decimals + getFractional(arg); result *= arg; } return decimals !== 0 ? round(result, decimals) : result; } /** * Safely divides two numbers while avoiding floating errors * like 0.3 / 0.05 => 5.999999999999999 * * @returns {number} result * @param {number} num Numerator * @param {number} den Denominator */ export function divSafe(num, den) { if (den === 0) { throw new Error("Divide by zero"); } var factor = Math.pow(10, getFractional(den)); var invDen = factor / (factor * den); return mulSafe(num, invDen); } /** * Rounds value at the specified number of decimals * * @param {number} val - value to round * @param {number} decimals - number of decimals * * @returns {number} rounded number */ export function round(val, decimals) { return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals); } function getFractional(num) { // Check for NaNs or Infinities if (!isFinite(num)) { return 0; } // Faster than parsing strings // http://jsperf.com/count-decimals/2 var count = 0; while (num % 1 !== 0) { num *= 10; count++; } return count; } ================================================ FILE: src/quantities.js ================================================ import Qty from "./quantities/constructor.js"; import "./quantities/global-api.js"; import "./quantities/operators.js"; import "./quantities/comparators.js"; import "./quantities/predicates.js"; import "./quantities/conversion.js"; import "./quantities/format.js"; Qty.version = "1.8.0"; export default Qty;