diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index be8533f00..c116c078f 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -9,10 +9,8 @@ For items that are not-applicable, mark "N/A" and ✔.
- [ ] Tests are included and test edge cases
- [ ] Tests have been run locally and pass
- [ ] Code coverage has not gone down and all code touched or added is covered.
-- [ ] Code passes lint and prettier (hint: use `npm run test:plus` to run tests, lint, and prettier)
+- [ ] Code passes lint and prettier (hint: use `npm run check` to run tests, lint, and prettier)
- [ ] All dependent libraries are appropriately updated or have a corresponding PR related to this change
-- [ ] `cql4browsers.js` built with `npm run build:browserify` if source changed.
-
**Reviewer:**
Name:
diff --git a/.github/workflows/ci-workflow.yml b/.github/workflows/ci-workflow.yml
index 19c1d0f3f..950e63480 100644
--- a/.github/workflows/ci-workflow.yml
+++ b/.github/workflows/ci-workflow.yml
@@ -12,15 +12,6 @@ jobs:
with:
node-version: 24.x
- run: npm audit --omit=dev
- cql4browsers:
- name: Check cql4browsers
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v6
- - uses: actions/setup-node@v6
- with:
- node-version: 24.x
- - run: ./bin/validate_cql4browsers.sh
lint:
name: Check lint and prettier
runs-on: ubuntu-latest
@@ -38,7 +29,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- node: [18.x, 22.x, 24.x]
+ node: [20.x, 22.x, 24.x]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
@@ -73,3 +64,24 @@ jobs:
working-directory: test-server
- run: npm run check
working-directory: test-server
+ examples:
+ name: Check examples
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 24.x
+ - run: npm ci
+ - run: npm ci
+ working-directory: examples/browser
+ - run: npm test
+ working-directory: examples/browser
+ - run: npm ci
+ working-directory: examples/node
+ - run: npm test
+ working-directory: examples/node
+ - run: npm ci
+ working-directory: examples/typescript
+ - run: npm test
+ working-directory: examples/typescript
diff --git a/.gitignore b/.gitignore
index ece924247..1b2192b03 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,12 @@
lib
lib-test
+dist
node_modules
.DS_Store
.nyc_output
-.vscode
+.vscode/*
+!.vscode/extensions.json
+!.vscode/settings.sample.json
coverage
*.original.coffee
yarn-error.log
diff --git a/.mocharc.json b/.mocharc.json
index 01cb5176f..5340a4ff4 100644
--- a/.mocharc.json
+++ b/.mocharc.json
@@ -1,5 +1,5 @@
{
"ignore": ["test/spec-tests/*.js"],
"extension": ["ts"],
- "require": ["ts-node/register", "./test/should-extensions.ts"]
+ "require": ["tsx/cjs", "./test/should-extensions.ts"]
}
diff --git a/.npmignore b/.npmignore
index fd9764d59..b31fee955 100644
--- a/.npmignore
+++ b/.npmignore
@@ -6,3 +6,4 @@
/test
/test-server
/CQL_Execution_Features.xlsx
+/examples
diff --git a/.oxlintrc.json b/.oxlintrc.json
new file mode 100644
index 000000000..7742f07ce
--- /dev/null
+++ b/.oxlintrc.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "env": {
+ "builtin": true,
+ "es6": true,
+ "mocha": true,
+ "node": true
+ },
+ "ignorePatterns": [
+ "**/lib",
+ "**/lib-test",
+ "**/dist",
+ "test-server/**"
+ ],
+ "rules": {
+ "no-loss-of-precision": "off",
+ "no-unused-vars": [
+ "error",
+ {
+ "argsIgnorePattern": "^_"
+ }
+ ],
+ "no-var": "error",
+ "prefer-const": "error",
+ "prefer-rest-params": "error",
+ "prefer-spread": "error",
+ "curly": "error",
+ "no-console": [
+ "warn",
+ {
+ "allow": [
+ "warn",
+ "error"
+ ]
+ }
+ ]
+ },
+ "overrides": [
+ {
+ "files": [
+ "test/elm/**/*.js"
+ ],
+ "rules": {
+ "unicorn/no-empty-file": "off"
+ }
+ }
+ ]
+}
diff --git a/.prettierignore b/.prettierignore
index ca3150c8a..823ca7344 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -1,10 +1,10 @@
lib
lib-test
+dist
node_modules
.nyc_output
.vscode
coverage
-cql4browsers.js
# the following uses its own prettier config
test-server
# the following are generated by the test generator
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 000000000..cda89e97e
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,7 @@
+{
+ "recommendations": [
+ // recommended for lint and code formatting
+ "oxc.oxc-vscode",
+ "esbenp.prettier-vscode"
+ ]
+}
\ No newline at end of file
diff --git a/.vscode/settings.sample.json b/.vscode/settings.sample.json
new file mode 100644
index 000000000..c7129b4a5
--- /dev/null
+++ b/.vscode/settings.sample.json
@@ -0,0 +1,10 @@
+{
+ "[javascript][typescript][typescriptreact]": {
+ "editor.formatOnSave": true,
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
+ },
+ "[json]": {
+ "editor.formatOnSave": true,
+ "editor.defaultFormatter": "vscode.json-language-features"
+ }
+}
\ No newline at end of file
diff --git a/DEPENDENCY_NOTES.md b/DEPENDENCY_NOTES.md
index 291a77ba9..84fd7e513 100644
--- a/DEPENDENCY_NOTES.md
+++ b/DEPENDENCY_NOTES.md
@@ -3,5 +3,4 @@ The following notes about the app's dependencies should be revisited and resolve
As of 2026-07-27:
- `@types/node`: Consider updating to `26.x` in the future, but for now `24.x` still has plent of time in LTS.
-- `typescript`: `7.x` uses a new native compiler without a native API. Libraries like `ts-node` and `typescript-eslint` do not yet support it.
- `tslog` (test-server only): `5.x` is ESM-only and replaces v4's flat logger settings such as `hideLogPositionForProduction` and `prettyLogTemplate`. Updating will require some migration.
diff --git a/README.md b/README.md
index 5cc8320d5..396fb83e1 100644
--- a/README.md
+++ b/README.md
@@ -63,13 +63,13 @@ To use this project, you should perform the following steps:
1. Install [Node.js](http://nodejs.org/) LTS*
2. Execute the following from the root directory: `npm install`
-* This project is primarily developed and tested using Node 24.x, but all versions >= 18.x are expected to work. Since Node 18.x has reached end-of-life, developers should consider this project's support for Node 18.x to be _deprecated_.
+* This project is primarily developed and tested using Node 24.x, but all versions >= 20.x are expected to work. Since Node 18.x reached end-of-life over a year ago, this project no longer supports it.
# To Execute Your CQL
Please note that while the CQL Execution library supports many aspects of CQL, it does not support
everything in the CQL specification. You should check to see what is implemented (by referencing
-the unit tests) before expecting it to work! For a working example, see `examples`.
+the unit tests) before expecting it to work! For working examples, see the `examples` directory.
There are several steps involved to execute CQL. First, you must create a JSON representation of
the ELM. For the easiest integration, we will generate a JSON file using cql-to-elm:
@@ -82,10 +82,9 @@ the ELM. For the easiest integration, we will generate a JSON file using cql-to-
4. `./gradlew :cql-to-elm-cli:installDist`
5. `./cql-to-elm-cli/build/install/cql-to-elm-cli/bin/cql-to-elm-cli --format=JSON --input ${path_to_cql} --output ${path_to_cql-execution}/customCQL`
-The above example puts the example CQL into a subfolder of the `cql-execution` project to make the
-relative paths to `cql-execution` libraries easier, but it doesn't _have_ to go there. If you put
-it elsewhere, you'll need to modify the examples below so that the `require` statements point to
-the correct location of the `cql` export.
+This repository contains self-contained Node.js and TypeScript mini-projects under `examples`.
+They depend on the repository's local `cql-execution` package; projects outside this repository
+should install `cql-execution` from npm instead.
In the rest of the examples, we'll assume an `age.cql` file with the following contents. This
follows the example already in the "examples" folder (but of course you can use your own CQL):
@@ -110,12 +109,11 @@ define InDemographic:
Next, we can create a TypeScript file to execute the above CQL. This file will need to contain (or
`import`) JSON patient representations for testing as well. Our example CQL uses a "Simple"
data model developed only for demonstration and testing purposes. In this model, each patient is
-represented using a simple JSON object. For ease of use, let's put the file in the `customCQL`
-directory:
+represented using a simple JSON object.
``` typescript
-import cql from '../../src/cql';
-import * as measure from './age.json'; // Requires the "resolveJsonModule" compiler option to be "true"
+import cql from 'cql-execution';
+import measure from './age.json'; // Requires the "resolveJsonModule" compiler option to be "true"
const lib = new cql.Library(measure);
const executor = new cql.Executor(lib);
@@ -125,14 +123,14 @@ const psource = new cql.PatientSource([
recordType: 'Patient',
name: 'John Smith',
gender: 'M',
- birthDate: '1980-02-17T06:15'
+ birthDate: '1980-02-17'
},
{
id: '2',
recordType: 'Patient',
name: 'Sally Smith',
gender: 'F',
- birthDate: '2007-08-02T11:47'
+ birthDate: '2007-08-02'
}
]);
@@ -151,30 +149,27 @@ In the above file, we've assumed the JSON ELM JSON file for the measure is calle
also assumed a couple of very simple patients. Let's call the file we just created
`exec-age.ts`.
-Now we can execute the measure using [ts-node](https://www.npmjs.com/package/ts-node):
+The complete TypeScript example has its own dependencies, scripts, and tests. Run it with:
-``` bash
-npx ts-node -O '{ "resolveJsonModule": true }' --files ${path_to_cql-execution}/customCQL/exec-age.ts
+```bash
+cd examples/typescript
+npm install
+npm start
```
If all is well, it should print the result object to standard out.
## JavaScript Example
-For usage in regular JavaScript, we can refer to the compiled JavaScript in the `lib` directory.
-Ensure that this JavaScript is present by running `npm run build` before continuing on to the example.
-We will follow the same steps as the above TypeScript example, but our JavaScript code must use `require`
-instead of `import`, and will load the `cql-execution` library from the `lib` directory. As before,
-let's put the file in the `customCQL` directory:
+For regular JavaScript, we use `require` to load the installed `cql-execution` package:
Next, create a JavaScript file to execute the CQL above. This file will need to contain (or
`require`) JSON patient representations for testing as well. Our example CQL uses a "Simple"
data model developed only for demonstration and testing purposes. In this model, each patient is
-represented using a simple JSON object. For ease of use, let's put the file in the `customCQL`
-directory:
+represented using a simple JSON object.
```js
-const cql = require('../lib/cql');
+const cql = require('cql-execution');
const measure = require('./age.json');
const lib = new cql.Library(measure);
@@ -184,13 +179,13 @@ const psource = new cql.PatientSource([ {
'recordType' : 'Patient',
'name': 'John Smith',
'gender': 'M',
- 'birthDate' : '1980-02-17T06:15'
+ 'birthDate' : '1980-02-17'
}, {
'id' : '2',
'recordType' : 'Patient',
'name': 'Sally Smith',
'gender': 'F',
- 'birthDate' : '2007-08-02T11:47'
+ 'birthDate' : '2007-08-02'
} ]);
executor
@@ -207,10 +202,12 @@ executor
The above file has the same assumptions as the TypeScript example above. Let's call the file we just created
`exec-age.js`.
-Now we can execute the measure using Node.js:
+The complete Node.js example has its own dependencies, scripts, and tests. Run it with:
```shell
-node ${path_to_cql-execution}/customCQL/exec-age.js
+cd examples/node
+npm install
+npm start
```
If all is well, it should print the result object to standard out, and the output should be identical to that of the TypeScript example.
@@ -351,12 +348,3 @@ execute `npm run watch:test-data`.
# Using the Test Server and CQL Tests Runner
See [test-server/README.md](test-server/README.md).
-
-# Pull Requests
-
-If TypeScript source code is modified, `cql4browsers.js` needs to be included in the pull request,
-otherwise GitHub Actions CI will fail. To generate this file, run:
-
-```
-npm run build:browserify
-```
diff --git a/bin/browserify.js b/bin/browserify.js
deleted file mode 100755
index 57b1b0ac3..000000000
--- a/bin/browserify.js
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env node
-
-/* eslint-disable no-console */
-
-// We cannot use browserify CLI because there is no way to pass options into presets
-
-const path = require('path');
-const fs = require('fs');
-const browserify = require('browserify');
-
-console.log('Browserifying cql4browsers...');
-const c4bpath = path.join(__dirname, '..', 'examples', 'browser', 'cql4browsers.js');
-const outputJsFile = fs.createWriteStream(c4bpath);
-browserify(path.join(__dirname, '..', 'examples', 'browser', 'simple-browser-support.js'))
- .bundle()
- .pipe(outputJsFile);
-outputJsFile.on('finish', () => {
- console.log(`Done! Output to ${path.relative('.', c4bpath)}`);
-});
diff --git a/bin/validate_cql4browsers.sh b/bin/validate_cql4browsers.sh
deleted file mode 100755
index baa02fe33..000000000
--- a/bin/validate_cql4browsers.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/bin/bash
-
-mkdir -p tmp/dist/
-git status --porcelain | grep cql4browsers.js
-if [ $? == 0 ]; then
- echo "cql4browsers.js has uncommitted changes. Reset or commit them before continuing."
- exit 1
-fi
-
-cp ./examples/browser/cql4browsers.js ./examples/browser/cql4browsers.js.original
-
-if [ $? != 0 ]; then
- echo "cql4browsers.js not found. Run this script from the base repository directory."
- exit 1
-fi
-npm ci
-
-# comm -3 only returns lines that differ between the two files. If none are different, diff will be empty
-diff=`diff ./examples/browser/cql4browsers.js.original ./examples/browser/cql4browsers.js`
-
-mv ./examples/browser/cql4browsers.js.original ./examples/browser/cql4browsers.js
-
-# Exit with a non-zero code if the diff isn't empty
-if [ "$diff" != "" ]; then
- echo "cql4browsers.js is out of date. Please run 'npm install' locally and commit/push the result"
- exit 1
-fi
-
-echo "cql4browsers.js is up to date"
diff --git a/eslint.config.mjs b/eslint.config.mjs
deleted file mode 100644
index 996fd60bb..000000000
--- a/eslint.config.mjs
+++ /dev/null
@@ -1,59 +0,0 @@
-import { defineConfig, globalIgnores } from 'eslint/config';
-import globals from 'globals';
-import tsParser from '@typescript-eslint/parser';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import js from '@eslint/js';
-import { FlatCompat } from '@eslint/eslintrc';
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-const compat = new FlatCompat({
- baseDirectory: __dirname,
- recommendedConfig: js.configs.recommended,
- allConfig: js.configs.all
-});
-
-export default defineConfig([
- globalIgnores([
- '**/.eslintrc.json',
- '**/lib',
- '**/lib-test',
- 'test-server',
- 'examples/browser/cql4browsers.js',
- 'test/elm/library/data-with-namespace.js'
- ]),
- {
- extends: compat.extends('plugin:@typescript-eslint/recommended', 'prettier'),
- languageOptions: {
- globals: {
- ...globals.node,
- ...globals.mocha
- },
- parser: tsParser,
- ecmaVersion: 6,
- sourceType: 'module',
- parserOptions: {
- ecmaFeatures: { experimentalObjectRestSpread: true }
- }
- },
- rules: {
- '@typescript-eslint/no-require-imports': 'off',
- '@typescript-eslint/no-explicit-any': 'off',
- 'no-unused-vars': 'off', // redundant to rule below
- '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
- indent: ['error', 2, { SwitchCase: 1 }],
- 'no-console': ['warn', { allow: ['warn', 'error'] }],
- 'no-loss-of-precision': 'off',
- quotes: ['error', 'single', { allowTemplateLiterals: true, avoidEscape: true }],
- semi: ['error', 'always'],
- curly: 'error'
- }
- },
- {
- files: ['test/**/*.{js,ts}', 'examples/**/*.js', 'bin/**/*.js'],
- rules: {
- '@typescript-eslint/no-var-requires': 'off'
- }
- }
-]);
diff --git a/examples/browser/README.md b/examples/browser/README.md
index 29b1a3344..46b98464b 100644
--- a/examples/browser/README.md
+++ b/examples/browser/README.md
@@ -1,11 +1,24 @@
-This example demonstrates a static html page running a _browserified_ version of the
-CQL execution engine. It currently only supports CQL using the System datatypes. It
-does not support other data models or execution on patients.
+This mini-project demonstrates the CQL execution engine in a static browser page. It
+uses the same `AgeAtMP` CQL and example patients as the Node.js and TypeScript
+mini-projects. It depends on the repository's local `cql-execution` package and owns
+its browser build tooling and generated output. The bundle assigns the example patients
+to `window.patients`, which is used by both the execution code and the page's patient
+table.
-The browserified code is checked into source control, but if you need to update it,
-you can follow these steps:
+From the repository root, install and build `cql-execution`:
-1. Install [Node.js](http://nodejs.org/) (Note: `npm` version `6.x.x` recommended)
-2. Execute the following from the _cql-execution_ directory:
- 1. `npm install`
- 2. `npm run build:all`
+```sh
+npm install
+```
+
+Then install and build the browser example:
+
+```sh
+cd examples/browser
+npm install
+npm run build
+```
+
+Open `index.html` in a browser to run the example. For development, `npm run dev`
+builds the bundle, serves this directory, and rebuilds when its inputs change. Run
+`npm test` to build the bundle and verify both patients' `InDemographic` results.
diff --git a/examples/browser/age.cql b/examples/browser/age.cql
new file mode 100644
index 000000000..c1b9b57ac
--- /dev/null
+++ b/examples/browser/age.cql
@@ -0,0 +1,12 @@
+library AgeAtMP version '1'
+
+// NOTE: This example uses a custom data model that is very simplistic and suitable only for
+// demonstration and testing purposes. Real-world CQL should use a more appropriate model.
+using Simple version '1.0.0'
+
+parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1, 0, 0, 0, 0), DateTime(2014, 1, 1, 0, 0, 0, 0))
+
+context Patient
+
+define InDemographic:
+ AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
diff --git a/examples/browser/age.json b/examples/browser/age.json
new file mode 100644
index 000000000..fce744d7b
--- /dev/null
+++ b/examples/browser/age.json
@@ -0,0 +1,182 @@
+{
+ "library" : {
+ "annotation" : [ {
+ "translatorOptions" : "",
+ "type" : "CqlToElmInfo"
+ } ],
+ "identifier" : {
+ "id" : "AgeAtMP",
+ "version" : "1"
+ },
+ "schemaIdentifier" : {
+ "id" : "urn:hl7-org:elm",
+ "version" : "r1"
+ },
+ "usings" : {
+ "def" : [ {
+ "localIdentifier" : "System",
+ "uri" : "urn:hl7-org:elm-types:r1"
+ }, {
+ "localIdentifier" : "Simple",
+ "uri" : "https://github.com/cqframework/cql-execution/simple",
+ "version" : "1.0.0"
+ } ]
+ },
+ "parameters" : {
+ "def" : [ {
+ "name" : "MeasurementPeriod",
+ "accessLevel" : "Public",
+ "default" : {
+ "lowClosed" : true,
+ "highClosed" : false,
+ "type" : "Interval",
+ "low" : {
+ "type" : "DateTime",
+ "year" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "2013",
+ "type" : "Literal"
+ },
+ "month" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "1",
+ "type" : "Literal"
+ },
+ "day" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "1",
+ "type" : "Literal"
+ },
+ "hour" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ },
+ "minute" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ },
+ "second" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ },
+ "millisecond" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ }
+ },
+ "high" : {
+ "type" : "DateTime",
+ "year" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "2014",
+ "type" : "Literal"
+ },
+ "month" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "1",
+ "type" : "Literal"
+ },
+ "day" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "1",
+ "type" : "Literal"
+ },
+ "hour" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ },
+ "minute" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ },
+ "second" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ },
+ "millisecond" : {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "0",
+ "type" : "Literal"
+ }
+ }
+ }
+ } ]
+ },
+ "statements" : {
+ "def" : [ {
+ "name" : "Patient",
+ "context" : "Patient",
+ "expression" : {
+ "type" : "SingletonFrom",
+ "operand" : {
+ "dataType" : "{https://github.com/cqframework/cql-execution/simple}Patient",
+ "type" : "Retrieve"
+ }
+ }
+ }, {
+ "name" : "InDemographic",
+ "context" : "Patient",
+ "accessLevel" : "Public",
+ "expression" : {
+ "type" : "And",
+ "operand" : [ {
+ "type" : "GreaterOrEqual",
+ "operand" : [ {
+ "precision" : "Year",
+ "type" : "CalculateAgeAt",
+ "operand" : [ {
+ "path" : "birthDate",
+ "type" : "Property",
+ "source" : {
+ "name" : "Patient",
+ "type" : "ExpressionRef"
+ }
+ }, {
+ "type" : "Start",
+ "operand" : {
+ "name" : "MeasurementPeriod",
+ "type" : "ParameterRef"
+ }
+ } ]
+ }, {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "2",
+ "type" : "Literal"
+ } ]
+ }, {
+ "type" : "Less",
+ "operand" : [ {
+ "precision" : "Year",
+ "type" : "CalculateAgeAt",
+ "operand" : [ {
+ "path" : "birthDate",
+ "type" : "Property",
+ "source" : {
+ "name" : "Patient",
+ "type" : "ExpressionRef"
+ }
+ }, {
+ "type" : "Start",
+ "operand" : {
+ "name" : "MeasurementPeriod",
+ "type" : "ParameterRef"
+ }
+ } ]
+ }, {
+ "valueType" : "{urn:hl7-org:elm-types:r1}Integer",
+ "value" : "18",
+ "type" : "Literal"
+ } ]
+ } ]
+ }
+ } ]
+ }
+ }
+}
diff --git a/examples/browser/cql4browsers.html b/examples/browser/cql4browsers.html
deleted file mode 100644
index d30ccfeac..000000000
--- a/examples/browser/cql4browsers.html
+++ /dev/null
@@ -1,134 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/examples/browser/cql4browsers.js b/examples/browser/cql4browsers.js
deleted file mode 100644
index 878f2df31..000000000
--- a/examples/browser/cql4browsers.js
+++ /dev/null
@@ -1,30995 +0,0 @@
-(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 1) {
- const rep = new window.cql.Repository(elm);
- lib = rep.resolve(libraryName, version);
- } else {
- lib = new window.cql.Library(elm[0]);
- }
- } else {
- lib = new window.cql.Library(elm);
- }
-
- const codeService = new window.cql.CodeService(valueSets);
- const executor = new window.cql.Executor(lib, codeService, parameters);
- return executor.exec(patientSource, executionDateTime);
-};
-
-},{"../../lib/cql":4}],2:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.CodeService = void 0;
-const datatypes_1 = require("./datatypes/datatypes");
-class CodeService {
- constructor(valueSetsJson = {}) {
- this.valueSets = {};
- for (const oid in valueSetsJson) {
- this.valueSets[oid] = {};
- for (const version in valueSetsJson[oid]) {
- const codes = valueSetsJson[oid][version].map((code) => new datatypes_1.Code(code.code, code.system, code.version, code.display));
- this.valueSets[oid][version] = new datatypes_1.ValueSet(oid, version, codes);
- }
- }
- }
- findValueSetsByOid(oid) {
- return this.valueSets[oid] ? Object.values(this.valueSets[oid]) : [];
- }
- findValueSet(oid, version) {
- if (version != null) {
- return this.valueSets[oid] != null ? this.valueSets[oid][version] : null;
- }
- else {
- const results = this.findValueSetsByOid(oid);
- if (results.length === 0) {
- return null;
- }
- else {
- return results.reduce((a, b) => {
- if (a.version > b.version) {
- return a;
- }
- else {
- return b;
- }
- });
- }
- }
- }
-}
-exports.CodeService = CodeService;
-
-},{"./datatypes/datatypes":7}],3:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.PatientSource = exports.Patient = exports.Record = void 0;
-const DT = __importStar(require("./datatypes/datatypes"));
-const elmTypes_1 = require("./util/elmTypes");
-class Record {
- constructor(json) {
- this.json = json;
- this.id = this.json.id;
- }
- _is(typeSpecifier) {
- return this._typeHierarchy().some(t => t.type === typeSpecifier.type && t.name == typeSpecifier.name);
- }
- _typeHierarchy() {
- return [
- {
- name: `{https://github.com/cqframework/cql-execution/simple}${this.json.recordType}`,
- type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER
- },
- {
- name: '{https://github.com/cqframework/cql-execution/simple}Record',
- type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER
- },
- { name: elmTypes_1.ELM_ANY_TYPE, type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER }
- ];
- }
- _recursiveGet(field) {
- if (field != null && field.indexOf('.') >= 0) {
- const [root, rest] = field.split('.', 2);
- return new Record(this._recursiveGet(root))._recursiveGet(rest);
- }
- return this.json[field];
- }
- get(field) {
- // the model should return the correct type for the field. For this simple model example,
- // we just cheat and use the shape of the value to determine it. Real implementations should
- // have a more sophisticated approach
- const value = this._recursiveGet(field);
- if (typeof value === 'string' && /\d{4}-\d{2}-\d{2}(T[\d\-.]+)?/.test(value)) {
- return this.getDate(field);
- }
- if (value != null && typeof value === 'object' && value.code != null && value.system != null) {
- return this.getCode(field);
- }
- if (value != null && typeof value === 'object' && (value.low != null || value.high != null)) {
- return this.getInterval(field);
- }
- return value;
- }
- getId() {
- return this.id;
- }
- getDate(field) {
- const val = this._recursiveGet(field);
- if (val != null) {
- return DT.DateTime.parse(val);
- }
- else {
- return null;
- }
- }
- getInterval(field) {
- const val = this._recursiveGet(field);
- if (val != null && typeof val === 'object') {
- const low = val.low != null ? DT.DateTime.parse(val.low) : null;
- const high = val.high != null ? DT.DateTime.parse(val.high) : null;
- return new DT.Interval(low, high);
- }
- }
- getDateOrInterval(field) {
- const val = this._recursiveGet(field);
- if (val != null && typeof val === 'object') {
- return this.getInterval(field);
- }
- else {
- return this.getDate(field);
- }
- }
- getCode(field) {
- const val = this._recursiveGet(field);
- if (val != null) {
- if (Array.isArray(val)) {
- return val.map(v => new DT.Code(v.code, v.system, v.version, v.display));
- }
- else if (typeof val === 'object') {
- return new DT.Code(val.code, val.system, val.version, val.display);
- }
- }
- }
-}
-exports.Record = Record;
-class Patient extends Record {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.gender = json.gender;
- this.birthDate = json.birthDate != null ? DT.DateTime.parse(json.birthDate) : undefined;
- this.records = {};
- (json.records || []).forEach((r) => {
- if (this.records[r.recordType] == null) {
- this.records[r.recordType] = [];
- }
- this.records[r.recordType].push(new Record(r));
- });
- }
- findRecords(profile) {
- if (profile == null) {
- return [];
- }
- const match = profile.match(/(\{https:\/\/github\.com\/cqframework\/cql-execution\/simple\})?(.*)/);
- if (match == null) {
- return [];
- }
- const recordType = match[2];
- if (recordType === 'Patient') {
- return [this];
- }
- else {
- return this.records[recordType] || [];
- }
- }
-}
-exports.Patient = Patient;
-class PatientSource {
- constructor(patients) {
- this.patients = patients;
- this.nextPatient();
- }
- currentPatient() {
- return this.current;
- }
- nextPatient() {
- const currentJSON = this.patients.shift();
- this.current = currentJSON ? new Patient(currentJSON) : undefined;
- return this.current;
- }
-}
-exports.PatientSource = PatientSource;
-
-},{"./datatypes/datatypes":7,"./util/elmTypes":55}],4:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ValueSet = exports.CQLValueSet = exports.Ratio = exports.Quantity = exports.Interval = exports.DateTime = exports.Date = exports.Concept = exports.CodeSystem = exports.Code = exports.CodeService = exports.PatientSource = exports.Patient = exports.NullMessageListener = exports.ConsoleMessageListener = exports.Results = exports.Executor = exports.UnfilteredContext = exports.PatientContext = exports.Context = exports.Expression = exports.Repository = exports.Library = exports.AnnotatedError = void 0;
-// Library-related classes
-const library_1 = require("./elm/library");
-Object.defineProperty(exports, "Library", { enumerable: true, get: function () { return library_1.Library; } });
-const repository_1 = require("./runtime/repository");
-Object.defineProperty(exports, "Repository", { enumerable: true, get: function () { return repository_1.Repository; } });
-const expression_1 = require("./elm/expression");
-Object.defineProperty(exports, "Expression", { enumerable: true, get: function () { return expression_1.Expression; } });
-// Execution-related classes
-const context_1 = require("./runtime/context");
-Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_1.Context; } });
-Object.defineProperty(exports, "PatientContext", { enumerable: true, get: function () { return context_1.PatientContext; } });
-Object.defineProperty(exports, "UnfilteredContext", { enumerable: true, get: function () { return context_1.UnfilteredContext; } });
-const executor_1 = require("./runtime/executor");
-Object.defineProperty(exports, "Executor", { enumerable: true, get: function () { return executor_1.Executor; } });
-const results_1 = require("./runtime/results");
-Object.defineProperty(exports, "Results", { enumerable: true, get: function () { return results_1.Results; } });
-const messageListeners_1 = require("./runtime/messageListeners");
-Object.defineProperty(exports, "ConsoleMessageListener", { enumerable: true, get: function () { return messageListeners_1.ConsoleMessageListener; } });
-Object.defineProperty(exports, "NullMessageListener", { enumerable: true, get: function () { return messageListeners_1.NullMessageListener; } });
-// PatientSource-related classes
-const cql_patient_1 = require("./cql-patient");
-Object.defineProperty(exports, "Patient", { enumerable: true, get: function () { return cql_patient_1.Patient; } });
-Object.defineProperty(exports, "PatientSource", { enumerable: true, get: function () { return cql_patient_1.PatientSource; } });
-// TerminologyService-related classes
-const cql_code_service_1 = require("./cql-code-service");
-Object.defineProperty(exports, "CodeService", { enumerable: true, get: function () { return cql_code_service_1.CodeService; } });
-// DataType classes
-const datatypes_1 = require("./datatypes/datatypes");
-Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return datatypes_1.Code; } });
-Object.defineProperty(exports, "CodeSystem", { enumerable: true, get: function () { return datatypes_1.CodeSystem; } });
-Object.defineProperty(exports, "Concept", { enumerable: true, get: function () { return datatypes_1.Concept; } });
-Object.defineProperty(exports, "Date", { enumerable: true, get: function () { return datatypes_1.Date; } });
-Object.defineProperty(exports, "DateTime", { enumerable: true, get: function () { return datatypes_1.DateTime; } });
-Object.defineProperty(exports, "Interval", { enumerable: true, get: function () { return datatypes_1.Interval; } });
-Object.defineProperty(exports, "Quantity", { enumerable: true, get: function () { return datatypes_1.Quantity; } });
-Object.defineProperty(exports, "Ratio", { enumerable: true, get: function () { return datatypes_1.Ratio; } });
-Object.defineProperty(exports, "CQLValueSet", { enumerable: true, get: function () { return datatypes_1.CQLValueSet; } });
-Object.defineProperty(exports, "ValueSet", { enumerable: true, get: function () { return datatypes_1.ValueSet; } });
-const customErrors_1 = require("./util/customErrors");
-Object.defineProperty(exports, "AnnotatedError", { enumerable: true, get: function () { return customErrors_1.AnnotatedError; } });
-// Custom Types
-__exportStar(require("./types"), exports);
-exports.default = {
- AnnotatedError: customErrors_1.AnnotatedError,
- Library: library_1.Library,
- Repository: repository_1.Repository,
- Expression: expression_1.Expression,
- Context: context_1.Context,
- PatientContext: context_1.PatientContext,
- UnfilteredContext: context_1.UnfilteredContext,
- Executor: executor_1.Executor,
- Results: results_1.Results,
- ConsoleMessageListener: messageListeners_1.ConsoleMessageListener,
- NullMessageListener: messageListeners_1.NullMessageListener,
- Patient: cql_patient_1.Patient,
- PatientSource: cql_patient_1.PatientSource,
- CodeService: cql_code_service_1.CodeService,
- Code: datatypes_1.Code,
- CodeSystem: datatypes_1.CodeSystem,
- Concept: datatypes_1.Concept,
- Date: datatypes_1.Date,
- DateTime: datatypes_1.DateTime,
- Interval: datatypes_1.Interval,
- Quantity: datatypes_1.Quantity,
- Ratio: datatypes_1.Ratio,
- CQLValueSet: datatypes_1.CQLValueSet,
- ValueSet: datatypes_1.ValueSet
-};
-
-},{"./cql-code-service":2,"./cql-patient":3,"./datatypes/datatypes":7,"./elm/expression":23,"./elm/library":28,"./runtime/context":43,"./runtime/executor":44,"./runtime/messageListeners":45,"./runtime/repository":46,"./runtime/results":47,"./types":50,"./util/customErrors":54}],5:[function(require,module,exports){
-"use strict";
-// By default, BigInt throws a TypeError if you attempt to JSON.stringify it.
-// You can avoid the TypeError by defining a `toJSON()` function for BigInt.
-// We will use the same serialization approach as FHIR uses for integer64: a string.
-// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json
-// See: https://hl7.org/fhir/R5/json.html#primitive
-Object.defineProperty(exports, "__esModule", { value: true });
-if (BigInt.prototype.toJSON === undefined) {
- BigInt.prototype.toJSON = function () {
- return this.toString();
- };
-}
-
-},{}],6:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ValueSet = exports.CQLValueSet = exports.CodeSystem = exports.Vocabulary = exports.Concept = exports.Code = void 0;
-const util_1 = require("../util/util");
-class Code {
- constructor(code, system, version, display) {
- this.code = code;
- this.system = system;
- this.version = version;
- this.display = display;
- }
- get isCode() {
- return true;
- }
- hasMatch(code) {
- if (typeof code === 'string') {
- // the specific behavior for this is not in the specification. Matching codesystem behavior.
- return code === this.code;
- }
- else {
- return codesInList(toCodeList(code), [this]);
- }
- }
-}
-exports.Code = Code;
-class Concept {
- constructor(codes, display) {
- this.codes = codes;
- this.display = display;
- this.codes || (this.codes = []);
- }
- get isConcept() {
- return true;
- }
- hasMatch(code) {
- return codesInList(toCodeList(code), this.codes);
- }
-}
-exports.Concept = Concept;
-class Vocabulary {
- constructor(id, version, name) {
- this.id = id;
- this.version = version;
- this.name = name;
- }
-}
-exports.Vocabulary = Vocabulary;
-class CodeSystem extends Vocabulary {
- constructor(id, version, name) {
- super(id, version, name);
- this.id = id;
- this.version = version;
- this.name = name;
- }
- hasMatch(_code) {
- throw new Error('In CodeSystem operation not yet supported.');
- }
-}
-exports.CodeSystem = CodeSystem;
-class CQLValueSet extends Vocabulary {
- constructor(id, version, name, codesystems) {
- super(id, version, name);
- this.id = id;
- this.version = version;
- this.name = name;
- this.codesystems = codesystems;
- }
- get isValueSet() {
- return true;
- }
-}
-exports.CQLValueSet = CQLValueSet;
-class ValueSet {
- constructor(oid, version, codes = []) {
- this.oid = oid;
- this.version = version;
- this.codes = codes;
- }
- /**
- * Determines if the provided code matches any code in the current set.
- * If the input is a single string, it checks for a direct match with the
- * codes in the set, ensuring all code systems are consistent. Throws an
- * error if multiple code systems exist and a match is found, indicating
- * ambiguity. For other inputs, it checks for any matching codes using
- * the `codesInList` function. Used for the `code in valueset` operation.
- *
- * @param code - The code to be checked for a match, which can be a string
- * or an object containing codes.
- * @returns {boolean} True if a match is found, otherwise false.
- * @throws {Error} If a match is found with multiple code systems present.
- */
- hasMatch(code) {
- const codesList = toCodeList(code);
- // InValueSet String Overload
- if (codesList.length === 1 && typeof codesList[0] === 'string') {
- let matchFound = false;
- let multipleCodeSystemsExist = false;
- for (const codeItem of this.codes) {
- // Confirm all code systems match
- if (codeItem.system !== this.codes[0].system) {
- multipleCodeSystemsExist = true;
- }
- if (codeItem.code === codesList[0]) {
- matchFound = true;
- }
- if (multipleCodeSystemsExist && matchFound) {
- throw new Error('In (valueset) is ambiguous -- multiple codes with multiple code systems exist in value set.');
- }
- }
- return matchFound;
- }
- else {
- return codesInList(codesList, this.codes);
- }
- }
- /**
- * Expands the current set of codes by returning a list of unique `Code` objects.
- * This method filters out duplicate codes from the `codes` array, ensuring each
- * code appears only once in the returned list. Use for the ExpandValueset operator
- *
- * @returns {Code[]} An array of unique `Code` objects.
- */
- expand() {
- const expanded = [];
- this.codes.forEach(code => {
- const foundUniqueCode = expanded.find(uniqueCode => {
- if (uniqueCode == null || code == null) {
- return true;
- }
- return (uniqueCode.code === code.code &&
- uniqueCode.system == code.system &&
- uniqueCode.version == code.version &&
- uniqueCode.display == code.display);
- });
- if (!foundUniqueCode) {
- expanded.push(code);
- }
- });
- return expanded;
- }
-}
-exports.ValueSet = ValueSet;
-function toCodeList(c) {
- if (c == null) {
- return [];
- }
- else if ((0, util_1.typeIsArray)(c)) {
- let list = [];
- for (const c2 of c) {
- list = list.concat(toCodeList(c2));
- }
- return list;
- }
- else if ((0, util_1.typeIsArray)(c.codes)) {
- return c.codes;
- }
- else {
- return [c];
- }
-}
-function codesInList(cl1, cl2) {
- // test each code in c1 against each code in c2 looking for a match
- return cl1.some((c1) => cl2.some((c2) => {
- // only the left argument (cl1) can contain strings. cl2 will only contain codes.
- if (typeof c1 === 'string') {
- // for "string in codesystem" this should compare the string to
- // the code's "code" field according to the specification.
- return c1 === c2.code;
- }
- else {
- return codesMatch(c1, c2);
- }
- }));
-}
-function codesMatch(code1, code2) {
- return code1.code === code2.code && code1.system === code2.system;
-}
-
-},{"../util/util":60}],7:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-__exportStar(require("./bigint"), exports);
-__exportStar(require("./logic"), exports);
-__exportStar(require("./clinical"), exports);
-__exportStar(require("./uncertainty"), exports);
-__exportStar(require("./datetime"), exports);
-__exportStar(require("./interval"), exports);
-__exportStar(require("./quantity"), exports);
-__exportStar(require("./ratio"), exports);
-
-},{"./bigint":5,"./clinical":6,"./datetime":8,"./interval":10,"./logic":11,"./quantity":12,"./ratio":13,"./uncertainty":14}],8:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.MAX_TIME_VALUE = exports.MIN_TIME_VALUE = exports.MAX_DATE_VALUE = exports.MIN_DATE_VALUE = exports.MAX_DATETIME_VALUE = exports.MIN_DATETIME_VALUE = exports.Date = exports.DateTime = void 0;
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-const uncertainty_1 = require("./uncertainty");
-const util_1 = require("../util/util");
-const luxon_1 = require("luxon");
-const limits_1 = require("../util/limits");
-// It's easiest and most performant to organize formats by length of the supported strings.
-// This way we can test strings only against the formats that have a chance of working.
-// NOTE: Formats use Luxon formats, documented here: https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens
-const LENGTH_TO_DATE_FORMAT_MAP = (() => {
- const ltdfMap = new Map();
- ltdfMap.set(4, 'yyyy');
- ltdfMap.set(7, 'yyyy-MM');
- ltdfMap.set(10, 'yyyy-MM-dd');
- return ltdfMap;
-})();
-const LENGTH_TO_DATETIME_FORMATS_MAP = (() => {
- const formats = {
- yyyy: '2012',
- 'yyyy-MM': '2012-01',
- 'yyyy-MM-dd': '2012-01-31',
- "yyyy-MM-dd'T''Z'": '2012-01-31TZ',
- "yyyy-MM-dd'T'ZZ": '2012-01-31T-04:00',
- "yyyy-MM-dd'T'HH": '2012-01-31T12',
- "yyyy-MM-dd'T'HH'Z'": '2012-01-31T12Z',
- "yyyy-MM-dd'T'HHZZ": '2012-01-31T12-04:00',
- "yyyy-MM-dd'T'HH:mm": '2012-01-31T12:30',
- "yyyy-MM-dd'T'HH:mm'Z'": '2012-01-31T12:30Z',
- "yyyy-MM-dd'T'HH:mmZZ": '2012-01-31T12:30-04:00',
- "yyyy-MM-dd'T'HH:mm:ss": '2012-01-31T12:30:59',
- "yyyy-MM-dd'T'HH:mm:ss'Z'": '2012-01-31T12:30:59Z',
- "yyyy-MM-dd'T'HH:mm:ssZZ": '2012-01-31T12:30:59-04:00',
- "yyyy-MM-dd'T'HH:mm:ss.SSS": '2012-01-31T12:30:59.000',
- "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'": '2012-01-31T12:30:59.000Z',
- "yyyy-MM-dd'T'HH:mm:ss.SSSZZ": '2012-01-31T12:30:59.000-04:00'
- };
- const ltdtfMap = new Map();
- Object.keys(formats).forEach(k => {
- const example = formats[k];
- if (!ltdtfMap.has(example.length)) {
- ltdtfMap.set(example.length, [k]);
- }
- else {
- ltdtfMap.get(example.length).push(k);
- }
- });
- return ltdtfMap;
-})();
-function wholeLuxonDuration(duration, unit) {
- const value = duration.get(unit);
- return value >= 0 ? Math.floor(value) : Math.ceil(value);
-}
-function truncateLuxonDateTime(luxonDT, unit) {
- // Truncating by week (to the previous Sunday) requires different logic than the rest
- if (unit === DateTime.Unit.WEEK) {
- // Sunday is ISO weekday 7
- if (luxonDT.weekday !== 7) {
- luxonDT = luxonDT.set({ weekday: 7 }).minus({ weeks: 1 });
- }
- unit = DateTime.Unit.DAY;
- }
- return luxonDT.startOf(unit);
-}
-/*
- * Base class for Date and DateTime to extend from
- * Implements shared functions by both classes
- * TODO: we can probably iterate on this more to improve the accessing of "FIELDS" and the overall structure
- * TODO: we can also investigate if it's reasonable for DateTime to extend Date directly instead
- */
-class AbstractDate {
- constructor(year = null, month = null, day = null) {
- this.year = year;
- this.month = month;
- this.day = day;
- }
- // Shared functions
- isPrecise() {
- // @ts-ignore
- return this.constructor.FIELDS.every(field => this[field] != null);
- }
- isImprecise() {
- return !this.isPrecise();
- }
- isMorePrecise(other) {
- // @ts-ignore
- if (typeof other === 'string' && this.constructor.FIELDS.includes(other)) {
- // @ts-ignore
- if (this[other] == null) {
- return false;
- }
- }
- else {
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // @ts-ignore
- if (other[field] != null && this[field] == null) {
- return false;
- }
- }
- }
- return !this.isSamePrecision(other);
- }
- // This function can take another Date-ish object, or a precision string (e.g. 'month')
- isLessPrecise(other) {
- return !this.isSamePrecision(other) && !this.isMorePrecise(other);
- }
- // This function can take another Date-ish object, or a precision string (e.g. 'month')
- isSamePrecision(other) {
- // @ts-ignore
- if (typeof other === 'string' && this.constructor.FIELDS.includes(other)) {
- return other === this.getPrecision();
- }
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // @ts-ignore
- if (this[field] != null && other[field] == null) {
- return false;
- }
- // @ts-ignore
- if (this[field] == null && other[field] != null) {
- return false;
- }
- }
- return true;
- }
- equals(other) {
- return compareWithDefaultResult(this, other, null);
- }
- equivalent(other) {
- return compareWithDefaultResult(this, other, false);
- }
- sameAs(other, precision) {
- if (!(other.isDate || other.isDateTime)) {
- return null;
- }
- else if (this.isDate && other.isDateTime) {
- return this.getDateTime().sameAs(other, precision);
- }
- else if (this.isDateTime && other.isDate) {
- other = other.getDateTime();
- }
- // @ts-ignore
- if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) {
- throw new Error(`Invalid precision: ${precision}`);
- }
- // make a copy of other in the correct timezone offset if they don't match.
- // When comparing DateTime values with different timezone offsets, implementations
- // should normalize to the timezone offset of the evaluation request timestamp,
- // but only when the comparison precision is hours, minutes, seconds, or milliseconds.
- if (isPrecisionUnspecifiedOrGreaterThanDay(precision)) {
- if (this.timezoneOffset !== other.timezoneOffset) {
- other = other.convertToTimezoneOffset(this.timezoneOffset);
- }
- }
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // if both have this precision defined
- // @ts-ignore
- if (this[field] != null && other[field] != null) {
- // if they are different then return with false
- // @ts-ignore
- if (this[field] !== other[field]) {
- return false;
- }
- // if both dont have this precision, return true of precision is not defined
- // @ts-ignore
- }
- else if (this[field] == null && other[field] == null) {
- if (precision == null) {
- return true;
- }
- else {
- // we havent met precision yet
- return null;
- }
- // otherwise they have inconclusive precision, return null
- }
- else {
- return null;
- }
- // if precision is defined and we have reached expected precision, we can leave the loop
- if (precision != null && precision === field) {
- break;
- }
- }
- // if we made it here, then all fields matched.
- return true;
- }
- sameOrBefore(other, precision) {
- if (!(other.isDate || other.isDateTime)) {
- return null;
- }
- else if (this.isDate && other.isDateTime) {
- return this.getDateTime().sameOrBefore(other, precision);
- }
- else if (this.isDateTime && other.isDate) {
- other = other.getDateTime();
- }
- // @ts-ignore
- if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) {
- throw new Error(`Invalid precision: ${precision}`);
- }
- // make a copy of other in the correct timezone offset if they don't match.
- // When comparing DateTime values with different timezone offsets, implementations
- // should normalize to the timezone offset of the evaluation request timestamp,
- // but only when the comparison precision is hours, minutes, seconds, or milliseconds.
- if (isPrecisionUnspecifiedOrGreaterThanDay(precision)) {
- if (this.timezoneOffset !== other.timezoneOffset) {
- other = other.convertToTimezoneOffset(this.timezoneOffset);
- }
- }
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // if both have this precision defined
- // @ts-ignore
- if (this[field] != null && other[field] != null) {
- // if this value is less than the other return with true. this is before other
- // @ts-ignore
- if (this[field] < other[field]) {
- return true;
- // if this value is greater than the other return with false. this is after
- // @ts-ignore
- }
- else if (this[field] > other[field]) {
- return false;
- }
- // execution continues if the values are the same
- // if both dont have this precision, return true if precision is not defined
- // @ts-ignore
- }
- else if (this[field] == null && other[field] == null) {
- if (precision == null) {
- return true;
- }
- else {
- // we havent met precision yet
- return null;
- }
- // otherwise they have inconclusive precision, return null
- }
- else {
- return null;
- }
- // if precision is defined and we have reached expected precision, we can leave the loop
- if (precision != null && precision === field) {
- break;
- }
- }
- // if we made it here, then all fields matched and they are same
- return true;
- }
- sameOrAfter(other, precision) {
- if (!(other.isDate || other.isDateTime)) {
- return null;
- }
- else if (this.isDate && other.isDateTime) {
- return this.getDateTime().sameOrAfter(other, precision);
- }
- else if (this.isDateTime && other.isDate) {
- other = other.getDateTime();
- }
- // @ts-ignore
- if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) {
- throw new Error(`Invalid precision: ${precision}`);
- }
- // make a copy of other in the correct timezone offset if they don't match.
- // When comparing DateTime values with different timezone offsets, implementations
- // should normalize to the timezone offset of the evaluation request timestamp,
- // but only when the comparison precision is hours, minutes, seconds, or milliseconds.
- if (isPrecisionUnspecifiedOrGreaterThanDay(precision)) {
- if (this.timezoneOffset !== other.timezoneOffset) {
- other = other.convertToTimezoneOffset(this.timezoneOffset);
- }
- }
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // if both have this precision defined
- // @ts-ignore
- if (this[field] != null && other[field] != null) {
- // if this value is greater than the other return with true. this is after other
- // @ts-ignore
- if (this[field] > other[field]) {
- return true;
- // if this value is greater than the other return with false. this is before
- // @ts-ignore
- }
- else if (this[field] < other[field]) {
- return false;
- }
- // execution continues if the values are the same
- // if both dont have this precision, return true if precision is not defined
- // @ts-ignore
- }
- else if (this[field] == null && other[field] == null) {
- if (precision == null) {
- return true;
- }
- else {
- // we havent met precision yet
- return null;
- }
- // otherwise they have inconclusive precision, return null
- }
- else {
- return null;
- }
- // if precision is defined and we have reached expected precision, we can leave the loop
- if (precision != null && precision === field) {
- break;
- }
- }
- // if we made it here, then all fields matched and they are same
- return true;
- }
- before(other, precision) {
- if (!(other.isDate || other.isDateTime)) {
- return null;
- }
- else if (this.isDate && other.isDateTime) {
- return this.getDateTime().before(other, precision);
- }
- else if (this.isDateTime && other.isDate) {
- other = other.getDateTime();
- }
- // @ts-ignore
- if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) {
- throw new Error(`Invalid precision: ${precision}`);
- }
- // make a copy of other in the correct timezone offset if they don't match.
- // When comparing DateTime values with different timezone offsets, implementations
- // should normalize to the timezone offset of the evaluation request timestamp,
- // but only when the comparison precision is hours, minutes, seconds, or milliseconds.
- if (isPrecisionUnspecifiedOrGreaterThanDay(precision)) {
- if (this.timezoneOffset !== other.timezoneOffset) {
- other = other.convertToTimezoneOffset(this.timezoneOffset);
- }
- }
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // if both have this precision defined
- // @ts-ignore
- if (this[field] != null && other[field] != null) {
- // if this value is less than the other return with true. this is before other
- // @ts-ignore
- if (this[field] < other[field]) {
- return true;
- // if this value is greater than the other return with false. this is after
- // @ts-ignore
- }
- else if (this[field] > other[field]) {
- return false;
- }
- // execution continues if the values are the same
- // if both dont have this precision, return false if precision is not defined
- // @ts-ignore
- }
- else if (this[field] == null && other[field] == null) {
- if (precision == null) {
- return false;
- }
- else {
- // we havent met precision yet
- return null;
- }
- // otherwise they have inconclusive precision, return null
- }
- else {
- return null;
- }
- // if precision is defined and we have reached expected precision, we can leave the loop
- if (precision != null && precision === field) {
- break;
- }
- }
- // if we made it here, then all fields matched and they are same
- return false;
- }
- after(other, precision) {
- if (!(other.isDate || other.isDateTime)) {
- return null;
- }
- else if (this.isDate && other.isDateTime) {
- return this.getDateTime().after(other, precision);
- }
- else if (this.isDateTime && other.isDate) {
- other = other.getDateTime();
- }
- // @ts-ignore
- if (precision != null && this.constructor.FIELDS.indexOf(precision) < 0) {
- throw new Error(`Invalid precision: ${precision}`);
- }
- // make a copy of other in the correct timezone offset if they don't match.
- // When comparing DateTime values with different timezone offsets, implementations
- // should normalize to the timezone offset of the evaluation request timestamp,
- // but only when the comparison precision is hours, minutes, seconds, or milliseconds.
- if (isPrecisionUnspecifiedOrGreaterThanDay(precision)) {
- if (this.timezoneOffset !== other.timezoneOffset) {
- other = other.convertToTimezoneOffset(this.timezoneOffset);
- }
- }
- // @ts-ignore
- for (const field of this.constructor.FIELDS) {
- // if both have this precision defined
- // @ts-ignore
- if (this[field] != null && other[field] != null) {
- // if this value is greater than the other return with true. this is after other
- // @ts-ignore
- if (this[field] > other[field]) {
- return true;
- // if this value is greater than the other return with false. this is before
- // @ts-ignore
- }
- else if (this[field] < other[field]) {
- return false;
- }
- // execution continues if the values are the same
- // if both dont have this precision, return false if precision is not defined
- // @ts-ignore
- }
- else if (this[field] == null && other[field] == null) {
- if (precision == null) {
- return false;
- }
- else {
- // we havent met precision yet
- return null;
- }
- // otherwise they have inconclusive precision, return null
- }
- else {
- return null;
- }
- // if precision is defined and we have reached expected precision, we can leave the loop
- if (precision != null && precision === field) {
- break;
- }
- }
- // if we made it here, then all fields matched and they are same
- return false;
- }
- add(offset, field) {
- if (offset === 0 || this.year == null) {
- return this.copy();
- }
- // Use luxon to do the date math because it honors DST and it has the leap-year/end-of-month semantics we want.
- // NOTE: The luxonDateTime will contain default values where this[unit] is null, but we'll account for that.
- let luxonDateTime = this.toLuxonDateTime();
- // From the spec: "The operation is performed by converting the time-based quantity to the most precise value
- // specified in the date/time (truncating any resulting decimal portion) and then adding it to the date/time value."
- // However, since you can't really convert days to months, if "this" is less precise than the field being added, we can
- // add to the earliest possible value of "this" or subtract from the latest possible value of "this" (depending on the
- // sign of the offset), and then null out the imprecise fields again after doing the calculation. Due to the way
- // luxonDateTime is constructed above, it is already at the earliest value, so only adjust if the offset is negative.
- // @ts-ignore
- const offsetIsMorePrecise = this[field] == null; //whether the quantity we are adding is more precise than "this".
- if (offsetIsMorePrecise && offset < 0) {
- luxonDateTime = luxonDateTime.endOf(this.getPrecision());
- }
- // Now do the actual math and convert it back to a Date/DateTime w/ originally null fields nulled out again
- const luxonResult = luxonDateTime.plus({ [field]: offset });
- const result = this.constructor
- .fromLuxonDateTime(luxonResult)
- .reducedPrecision(this.getPrecision());
- // Luxon never has a null offset, but sometimes "this" does, so reset to null if applicable
- if (this.isDateTime && this.timezoneOffset == null) {
- result.timezoneOffset = null;
- }
- // Can't use overflowsOrUnderflows from math.js due to circular dependencies when we require it
- if (result.after(exports.MAX_DATETIME_VALUE || result.before(exports.MIN_DATETIME_VALUE))) {
- return null;
- }
- else {
- return result;
- }
- }
-}
-class DateTime extends AbstractDate {
- static parse(string) {
- if (string === null) {
- return null;
- }
- const matches = /(\d{4})(-(\d{2}))?(-(\d{2}))?(T((\d{2})(:(\d{2})(:(\d{2})(\.(\d+))?)?)?)?(Z|(([+-])(\d{2})(:?(\d{2}))?))?)?/.exec(string);
- if (matches == null) {
- return null;
- }
- const years = matches[1];
- const months = matches[3];
- const days = matches[5];
- const hours = matches[8];
- const minutes = matches[10];
- const seconds = matches[12];
- let milliseconds = matches[14];
- if (milliseconds != null) {
- milliseconds = (0, util_1.normalizeMillisecondsField)(milliseconds);
- }
- if (milliseconds != null) {
- string = (0, util_1.normalizeMillisecondsFieldInString)(string, matches[14]);
- }
- if (!isValidDateTimeStringFormat(string)) {
- return null;
- }
- // convert the args to integers
- const args = [years, months, days, hours, minutes, seconds, milliseconds].map(arg => {
- return arg != null ? parseInt(arg) : arg;
- });
- // convert timezone offset to decimal and add it to arguments
- if (matches[18] != null) {
- const num = parseInt(matches[18]) + (matches[20] != null ? parseInt(matches[20]) / 60 : 0);
- args.push(matches[17] === '+' ? num : num * -1);
- }
- else if (matches[15] === 'Z') {
- args.push(0);
- }
- // @ts-ignore
- return new DateTime(...args);
- }
- // TODO: Note: using the jsDate type causes issues, fix later
- static fromJSDate(date, timezoneOffset) {
- //This is from a JS Date, not a CQL Date
- if (date instanceof DateTime) {
- return date;
- }
- if (timezoneOffset != null) {
- date = new util_1.jsDate(date.getTime() + timezoneOffset * 60 * 60 * 1000);
- return new DateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), timezoneOffset);
- }
- else {
- return new DateTime(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
- }
- }
- static fromLuxonDateTime(luxonDT) {
- if (luxonDT instanceof DateTime) {
- return luxonDT;
- }
- return new DateTime(luxonDT.year, luxonDT.month, luxonDT.day, luxonDT.hour, luxonDT.minute, luxonDT.second, luxonDT.millisecond, luxonDT.offset / 60);
- }
- constructor(year = null, month = null, day = null, hour = null, minute = null, second = null, millisecond = null, timezoneOffset) {
- // from the spec: If no timezone is specified, the timezone of the evaluation request timestamp is used.
- // NOTE: timezoneOffset will be explicitly null for the Time overload, whereas
- // it will be undefined if simply unspecified
- super(year, month, day);
- this.hour = hour;
- this.minute = minute;
- this.second = second;
- this.millisecond = millisecond;
- if (timezoneOffset === undefined) {
- this.timezoneOffset = (new util_1.jsDate().getTimezoneOffset() / 60) * -1;
- }
- else {
- this.timezoneOffset = timezoneOffset;
- }
- }
- get isDateTime() {
- return true;
- }
- get isDate() {
- return false;
- }
- copy() {
- return new DateTime(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond, this.timezoneOffset);
- }
- successor(precision) {
- if (precision) {
- return this.add(1, precision);
- }
- else if (this.millisecond != null) {
- return this.add(1, DateTime.Unit.MILLISECOND);
- }
- else if (this.second != null) {
- return this.add(1, DateTime.Unit.SECOND);
- }
- else if (this.minute != null) {
- return this.add(1, DateTime.Unit.MINUTE);
- }
- else if (this.hour != null) {
- return this.add(1, DateTime.Unit.HOUR);
- }
- else if (this.day != null) {
- return this.add(1, DateTime.Unit.DAY);
- }
- else if (this.month != null) {
- return this.add(1, DateTime.Unit.MONTH);
- }
- else if (this.year != null) {
- return this.add(1, DateTime.Unit.YEAR);
- }
- }
- predecessor(precision) {
- if (precision) {
- return this.add(-1, precision);
- }
- else if (this.millisecond != null) {
- return this.add(-1, DateTime.Unit.MILLISECOND);
- }
- else if (this.second != null) {
- return this.add(-1, DateTime.Unit.SECOND);
- }
- else if (this.minute != null) {
- return this.add(-1, DateTime.Unit.MINUTE);
- }
- else if (this.hour != null) {
- return this.add(-1, DateTime.Unit.HOUR);
- }
- else if (this.day != null) {
- return this.add(-1, DateTime.Unit.DAY);
- }
- else if (this.month != null) {
- return this.add(-1, DateTime.Unit.MONTH);
- }
- else if (this.year != null) {
- return this.add(-1, DateTime.Unit.YEAR);
- }
- }
- convertToTimezoneOffset(timezoneOffset = 0) {
- const shiftedLuxonDT = this.toLuxonDateTime().setZone(luxon_1.FixedOffsetZone.instance(timezoneOffset * 60));
- const shiftedDT = DateTime.fromLuxonDateTime(shiftedLuxonDT);
- return shiftedDT.reducedPrecision(this.getPrecision());
- }
- differenceBetween(other, unitField) {
- other = this._implicitlyConvert(other);
- if (other == null || !other.isDateTime) {
- return null;
- }
- // According to CQL spec:
- // * "Difference calculations are performed by truncating the datetime values at the next precision,
- // and then performing the corresponding duration calculation on the truncated values."
- // * "When difference is calculated for hours or finer units, timezone offsets should be normalized
- // prior to truncation to correctly consider real (actual elapsed) time. When difference is calculated
- // for days or coarser units, however, the time components (including timezone offset) should be truncated
- // without normalization to correctly reflect the difference in calendar days, months, and years."
- const a = this.toLuxonUncertainty();
- const b = other.toLuxonUncertainty();
- // If unit is days or above, reset all the DateTimes to UTC since TZ offset should not be considered;
- // Otherwise, we don't actually have to "normalize" to a common TZ because Luxon takes TZ into account.
- if ([DateTime.Unit.YEAR, DateTime.Unit.MONTH, DateTime.Unit.WEEK, DateTime.Unit.DAY].includes(unitField)) {
- a.low = a.low.toUTC(0, { keepLocalTime: true });
- a.high = a.high.toUTC(0, { keepLocalTime: true });
- b.low = b.low.toUTC(0, { keepLocalTime: true });
- b.high = b.high.toUTC(0, { keepLocalTime: true });
- }
- // Truncate all dates at precision below specified unit
- a.low = truncateLuxonDateTime(a.low, unitField);
- a.high = truncateLuxonDateTime(a.high, unitField);
- b.low = truncateLuxonDateTime(b.low, unitField);
- b.high = truncateLuxonDateTime(b.high, unitField);
- // Return the duration based on the normalize and truncated values
- return new uncertainty_1.Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField));
- }
- durationBetween(other, unitField) {
- other = this._implicitlyConvert(other);
- if (other == null || !other.isDateTime) {
- return null;
- }
- // According to the CQL specification, just like date and time comparison calculations,
- // consider seconds and milliseconds as a single combined precision with decimal semantics
- // this means that if milliseconds are not specified, then we treat it as though their
- // millisecond value is "0" so that no Uncertainty will be produced
- /* eslint-disable @typescript-eslint/no-this-alias */
- let aDateTime = this;
- let bDateTime = other;
- if (this.second !== null &&
- this.millisecond == null &&
- unitField !== DateTime.Unit.MILLISECOND) {
- aDateTime = this.copy();
- aDateTime.millisecond = 0;
- }
- if (other.second != null &&
- other.millisecond == null &&
- unitField !== DateTime.Unit.MILLISECOND) {
- bDateTime = other.copy();
- bDateTime.millisecond = 0;
- }
- const a = aDateTime.toLuxonUncertainty();
- const b = bDateTime.toLuxonUncertainty();
- return new uncertainty_1.Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField));
- }
- isUTC() {
- // A timezoneOffset of 0 indicates UTC time.
- return !this.timezoneOffset;
- }
- getPrecision() {
- let result = null;
- if (this.year != null) {
- result = DateTime.Unit.YEAR;
- }
- else {
- return result;
- }
- if (this.month != null) {
- result = DateTime.Unit.MONTH;
- }
- else {
- return result;
- }
- if (this.day != null) {
- result = DateTime.Unit.DAY;
- }
- else {
- return result;
- }
- if (this.hour != null) {
- result = DateTime.Unit.HOUR;
- }
- else {
- return result;
- }
- if (this.minute != null) {
- result = DateTime.Unit.MINUTE;
- }
- else {
- return result;
- }
- if (this.second != null) {
- result = DateTime.Unit.SECOND;
- }
- else {
- return result;
- }
- if (this.millisecond != null) {
- result = DateTime.Unit.MILLISECOND;
- }
- return result;
- }
- getPrecisionValue() {
- return this.isTime()
- ? TIME_PRECISION_VALUE_MAP.get(this.getPrecision())
- : DATETIME_PRECISION_VALUE_MAP.get(this.getPrecision());
- }
- toLuxonDateTime() {
- const offsetMins = this.timezoneOffset != null
- ? this.timezoneOffset * 60
- : new util_1.jsDate().getTimezoneOffset() * -1;
- return luxon_1.DateTime.fromObject({
- year: this.year ?? undefined,
- month: this.month ?? undefined,
- day: this.day ?? undefined,
- hour: this.hour ?? undefined,
- minute: this.minute ?? undefined,
- second: this.second ?? undefined,
- millisecond: this.millisecond ?? undefined
- }, {
- zone: luxon_1.FixedOffsetZone.instance(offsetMins)
- });
- }
- toLuxonUncertainty() {
- const low = this.toLuxonDateTime();
- const high = low.endOf(this.getPrecision());
- return new uncertainty_1.Uncertainty(low, high);
- }
- toJSDate(ignoreTimezone = false) {
- let luxonDT = this.toLuxonDateTime();
- // I don't know if anyone is using "ignoreTimezone" anymore (we aren't), but just in case
- if (ignoreTimezone) {
- const offset = new util_1.jsDate().getTimezoneOffset() * -1;
- luxonDT = luxonDT.setZone(luxon_1.FixedOffsetZone.instance(offset), { keepLocalTime: true });
- }
- return luxonDT.toJSDate();
- }
- toJSON() {
- return this.toString();
- }
- toString() {
- if (this.isTime()) {
- return this.toStringTime();
- }
- else {
- return this.toStringDateTime();
- }
- }
- toStringTime() {
- let str = '';
- if (this.hour != null) {
- str += String(this.hour).padStart(2, '0');
- if (this.minute != null) {
- str += ':' + String(this.minute).padStart(2, '0');
- if (this.second != null) {
- str += ':' + String(this.second).padStart(2, '0');
- if (this.millisecond != null) {
- str += '.' + String(this.millisecond).padStart(3, '0');
- }
- }
- }
- }
- return str;
- }
- toStringDateTime() {
- let str = '';
- if (this.year != null) {
- str += String(this.year).padStart(4, '0');
- if (this.month != null) {
- str += '-' + String(this.month).padStart(2, '0');
- if (this.day != null) {
- str += '-' + String(this.day).padStart(2, '0');
- if (this.hour != null) {
- str += 'T' + String(this.hour).padStart(2, '0');
- if (this.minute != null) {
- str += ':' + String(this.minute).padStart(2, '0');
- if (this.second != null) {
- str += ':' + String(this.second).padStart(2, '0');
- if (this.millisecond != null) {
- str += '.' + String(this.millisecond).padStart(3, '0');
- }
- }
- }
- }
- }
- }
- }
- if (str.indexOf('T') !== -1 && this.timezoneOffset != null) {
- str += this.timezoneOffset < 0 ? '-' : '+';
- const offsetHours = Math.floor(Math.abs(this.timezoneOffset));
- str += String(offsetHours).padStart(2, '0');
- const offsetMin = (Math.abs(this.timezoneOffset) - offsetHours) * 60;
- str += ':' + String(offsetMin).padStart(2, '0');
- }
- return str;
- }
- getDateTime() {
- return this;
- }
- getDate() {
- return new Date(this.year, this.month, this.day);
- }
- getTime() {
- // Times no longer have timezoneOffets, so we must explicitly set it to null
- return new DateTime(0, 1, 1, this.hour, this.minute, this.second, this.millisecond, null);
- }
- isTime() {
- return this.year === 0 && this.month === 1 && this.day === 1;
- }
- _implicitlyConvert(other) {
- if (other != null && other.isDate) {
- return other.getDateTime();
- }
- return other;
- }
- reducedPrecision(unitField = DateTime.Unit.MILLISECOND) {
- const reduced = this.copy();
- if (unitField != null && unitField !== DateTime.Unit.MILLISECOND) {
- const fieldIndex = DateTime.FIELDS.indexOf(unitField);
- const fieldsToRemove = DateTime.FIELDS.slice(fieldIndex + 1);
- for (const field of fieldsToRemove) {
- // @ts-ignore
- reduced[field] = null;
- }
- }
- return reduced;
- }
-}
-exports.DateTime = DateTime;
-DateTime.Unit = {
- YEAR: 'year',
- MONTH: 'month',
- WEEK: 'week',
- DAY: 'day',
- HOUR: 'hour',
- MINUTE: 'minute',
- SECOND: 'second',
- MILLISECOND: 'millisecond'
-};
-DateTime.FIELDS = [
- DateTime.Unit.YEAR,
- DateTime.Unit.MONTH,
- DateTime.Unit.DAY,
- DateTime.Unit.HOUR,
- DateTime.Unit.MINUTE,
- DateTime.Unit.SECOND,
- DateTime.Unit.MILLISECOND
-];
-class Date extends AbstractDate {
- static parse(string) {
- if (string === null) {
- return null;
- }
- const matches = /(\d{4})(-(\d{2}))?(-(\d{2}))?/.exec(string);
- if (matches == null) {
- return null;
- }
- const years = matches[1];
- const months = matches[3];
- const days = matches[5];
- if (!isValidDateStringFormat(string)) {
- return null;
- }
- // convert args to integers
- const args = [years, months, days].map(arg => (arg != null ? parseInt(arg) : arg));
- // @ts-ignore
- return new Date(...args);
- }
- constructor(year = null, month = null, day = null) {
- super(year, month, day);
- }
- get isDate() {
- return true;
- }
- get isDateTime() {
- return false;
- }
- copy() {
- return new Date(this.year, this.month, this.day);
- }
- successor(precision) {
- if (precision) {
- return this.add(1, precision);
- }
- else if (this.day != null) {
- return this.add(1, Date.Unit.DAY);
- }
- else if (this.month != null) {
- return this.add(1, Date.Unit.MONTH);
- }
- else if (this.year != null) {
- return this.add(1, Date.Unit.YEAR);
- }
- }
- predecessor(precision) {
- if (precision) {
- return this.add(-1, precision);
- }
- else if (this.day != null) {
- return this.add(-1, Date.Unit.DAY);
- }
- else if (this.month != null) {
- return this.add(-1, Date.Unit.MONTH);
- }
- else if (this.year != null) {
- return this.add(-1, Date.Unit.YEAR);
- }
- }
- differenceBetween(other, unitField) {
- if (other != null && other.isDateTime) {
- return this.getDateTime().differenceBetween(other, unitField);
- }
- if (other == null || !other.isDate) {
- return null;
- }
- // According to CQL spec:
- // * "Difference calculations are performed by truncating the datetime values at the next precision,
- // and then performing the corresponding duration calculation on the truncated values."
- const a = this.toLuxonUncertainty();
- const b = other.toLuxonUncertainty();
- // Truncate all dates at precision below specified unit
- a.low = truncateLuxonDateTime(a.low, unitField);
- a.high = truncateLuxonDateTime(a.high, unitField);
- b.low = truncateLuxonDateTime(b.low, unitField);
- b.high = truncateLuxonDateTime(b.high, unitField);
- // Return the duration based on the normalize and truncated values
- return new uncertainty_1.Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField));
- }
- durationBetween(other, unitField) {
- if (other != null && other.isDateTime) {
- return this.getDateTime().durationBetween(other, unitField);
- }
- if (other == null || !other.isDate) {
- return null;
- }
- const a = this.toLuxonUncertainty();
- const b = other.toLuxonUncertainty();
- return new uncertainty_1.Uncertainty(wholeLuxonDuration(b.low.diff(a.high, unitField), unitField), wholeLuxonDuration(b.high.diff(a.low, unitField), unitField));
- }
- getPrecision() {
- let result = null;
- if (this.year != null) {
- result = Date.Unit.YEAR;
- }
- else {
- return result;
- }
- if (this.month != null) {
- result = Date.Unit.MONTH;
- }
- else {
- return result;
- }
- if (this.day != null) {
- result = Date.Unit.DAY;
- }
- else {
- return result;
- }
- return result;
- }
- getPrecisionValue() {
- return DATETIME_PRECISION_VALUE_MAP.get(this.getPrecision());
- }
- toLuxonDateTime() {
- return luxon_1.DateTime.fromObject({
- year: this.year ?? undefined,
- month: this.month ?? undefined,
- day: this.day ?? undefined
- }, {
- zone: luxon_1.FixedOffsetZone.utcInstance
- });
- }
- toLuxonUncertainty() {
- const low = this.toLuxonDateTime();
- const high = low.endOf(this.getPrecision()).startOf('day'); // Date type is always at T00:00:00.0
- return new uncertainty_1.Uncertainty(low, high);
- }
- toJSDate() {
- const [y, mo, d] = [
- this.year,
- this.month != null ? this.month - 1 : 0,
- this.day != null ? this.day : 1
- ];
- return new util_1.jsDate(y, mo, d);
- }
- static fromJSDate(date) {
- if (date instanceof Date) {
- return date;
- }
- return new Date(date.getFullYear(), date.getMonth() + 1, date.getDate());
- }
- static fromLuxonDateTime(luxonDT) {
- if (luxonDT instanceof Date) {
- return luxonDT;
- }
- return new Date(luxonDT.year, luxonDT.month, luxonDT.day);
- }
- toJSON() {
- return this.toString();
- }
- toString() {
- let str = '';
- if (this.year != null) {
- str += this.year.toString().padStart(4, '0');
- if (this.month != null) {
- str += '-' + this.month.toString().padStart(2, '0');
- if (this.day != null) {
- str += '-' + this.day.toString().padStart(2, '0');
- }
- }
- }
- return str;
- }
- getDateTime(timeZoneOffset) {
- // from the spec: the result will be a DateTime with the time components unspecified,
- // except for the timezone offset, which will be set to the timezone offset of the evaluation
- // request timestamp. (this last part is achieved by passing in the timeZoneOffset from the context)
- if (this.year != null && this.month != null && this.day != null) {
- return new DateTime(this.year, this.month, this.day, null, null, null, null, timeZoneOffset);
- // from spec: no component may be specified at a precision below an unspecified precision.
- // For example, hour may be null, but if it is, minute, second, and millisecond must all be null as well.
- }
- else {
- return new DateTime(this.year, this.month, this.day);
- }
- }
- reducedPrecision(unitField = Date.Unit.DAY) {
- const reduced = this.copy();
- if (unitField !== Date.Unit.DAY) {
- const fieldIndex = Date.FIELDS.indexOf(unitField);
- const fieldsToRemove = Date.FIELDS.slice(fieldIndex + 1);
- for (const field of fieldsToRemove) {
- // @ts-ignore
- reduced[field] = null;
- }
- }
- return reduced;
- }
-}
-exports.Date = Date;
-Date.Unit = { YEAR: 'year', MONTH: 'month', WEEK: 'week', DAY: 'day' };
-Date.FIELDS = [Date.Unit.YEAR, Date.Unit.MONTH, Date.Unit.DAY];
-exports.MIN_DATETIME_VALUE = DateTime.parse(limits_1.MIN_DATETIME_VALUE_STRING);
-exports.MAX_DATETIME_VALUE = DateTime.parse(limits_1.MAX_DATETIME_VALUE_STRING);
-exports.MIN_DATE_VALUE = Date.parse(limits_1.MIN_DATE_VALUE_STRING);
-exports.MAX_DATE_VALUE = Date.parse(limits_1.MAX_DATE_VALUE_STRING);
-exports.MIN_TIME_VALUE = DateTime.parse(limits_1.MIN_TIME_VALUE_STRING)?.getTime();
-exports.MAX_TIME_VALUE = DateTime.parse(limits_1.MAX_TIME_VALUE_STRING)?.getTime();
-const DATETIME_PRECISION_VALUE_MAP = (() => {
- const dtpvMap = new Map();
- dtpvMap.set(DateTime.Unit.YEAR, 4);
- dtpvMap.set(DateTime.Unit.MONTH, 6);
- dtpvMap.set(DateTime.Unit.DAY, 8);
- dtpvMap.set(DateTime.Unit.HOUR, 10);
- dtpvMap.set(DateTime.Unit.MINUTE, 12);
- dtpvMap.set(DateTime.Unit.SECOND, 14);
- dtpvMap.set(DateTime.Unit.MILLISECOND, 17);
- return dtpvMap;
-})();
-const TIME_PRECISION_VALUE_MAP = (() => {
- const tpvMap = new Map();
- tpvMap.set(DateTime.Unit.HOUR, 2);
- tpvMap.set(DateTime.Unit.MINUTE, 4);
- tpvMap.set(DateTime.Unit.SECOND, 6);
- tpvMap.set(DateTime.Unit.MILLISECOND, 9);
- return tpvMap;
-})();
-function compareWithDefaultResult(a, b, defaultResult) {
- // return false there is a type mismatch
- if ((!a.isDate || !b.isDate) && (!a.isDateTime || !b.isDateTime)) {
- return false;
- }
- // make a copy of other in the correct timezone offset if they don't match.
- if (a.timezoneOffset !== b.timezoneOffset) {
- b = b.convertToTimezoneOffset(a.timezoneOffset);
- }
- for (const field of a.constructor.FIELDS) {
- // if both have this precision defined
- if (a[field] != null && b[field] != null) {
- // For the purposes of comparison, seconds and milliseconds are combined
- // as a single precision using a decimal, with decimal equality semantics
- if (field === 'second') {
- // NOTE: if millisecond is null it will calculate like this anyway, but
- // if millisecond is undefined, using it will result in NaN calculations
- const aMillisecond = a['millisecond'] != null ? a['millisecond'] : 0;
- const aSecondAndMillisecond = a[field] + aMillisecond / 1000;
- const bMillisecond = b['millisecond'] != null ? b['millisecond'] : 0;
- const bSecondAndMillisecond = b[field] + bMillisecond / 1000;
- // second/millisecond is the most precise comparison, so we can directly return
- return aSecondAndMillisecond === bSecondAndMillisecond;
- }
- // if they are different then return with false
- if (a[field] !== b[field]) {
- return false;
- }
- // if both dont have this precision, return true
- }
- else if (a[field] == null && b[field] == null) {
- return true;
- // otherwise they have inconclusive precision, return defaultResult
- }
- else {
- return defaultResult;
- }
- }
- // if we made it here, then all fields matched.
- return true;
-}
-function isValidDateStringFormat(string) {
- if (typeof string !== 'string') {
- return false;
- }
- const format = LENGTH_TO_DATE_FORMAT_MAP.get(string.length);
- if (format == null) {
- return false;
- }
- return luxon_1.DateTime.fromFormat(string, format).isValid;
-}
-function isValidDateTimeStringFormat(string) {
- if (typeof string !== 'string') {
- return false;
- }
- // Luxon doesn't support +hh offset, so change it to +hh:00
- if (/T[\d:.]*[+-]\d{2}$/.test(string)) {
- string += ':00';
- }
- const formats = LENGTH_TO_DATETIME_FORMATS_MAP.get(string.length);
- if (formats == null) {
- return false;
- }
- return formats.some((fmt) => luxon_1.DateTime.fromFormat(string, fmt).isValid);
-}
-// Will return true if provided precision is unspecified or if
-// precision is hours, minutes, seconds, or milliseconds
-function isPrecisionUnspecifiedOrGreaterThanDay(precision) {
- return precision == null || /^h|mi|s/.test(precision);
-}
-
-},{"../util/limits":57,"../util/util":60,"./uncertainty":14,"luxon":78}],9:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Exception = void 0;
-class Exception {
- constructor(message, wrapped) {
- this.message = message;
- this.wrapped = wrapped;
- }
-}
-exports.Exception = Exception;
-
-},{}],10:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Interval = void 0;
-const uncertainty_1 = require("./uncertainty");
-const logic_1 = require("./logic");
-const math_1 = require("../util/math");
-const cmp = __importStar(require("../util/comparison"));
-const elmTypes_1 = require("../util/elmTypes");
-const limits_1 = require("../util/limits");
-const quantity_1 = require("./quantity");
-// TODO: Replace all build.fhir.org URL references with stable references once CQL 2.0 is pulished
-class Interval {
- constructor(low, high, lowClosed, highClosed, pointType = elmTypes_1.ELM_ANY_TYPE) {
- this.low = low;
- this.high = high;
- this.lowClosed = lowClosed;
- this.highClosed = highClosed;
- this.pointType = pointType;
- this.lowClosed = lowClosed != null ? lowClosed : true;
- this.highClosed = highClosed != null ? highClosed : true;
- if (this.pointType == null || this.pointType === elmTypes_1.ELM_ANY_TYPE) {
- let point = low ?? high;
- if (point?.isUncertainty) {
- point = point.low ?? point.high;
- }
- if (point != null) {
- if (typeof point === 'number') {
- this.pointType = Number.isInteger(point) ? elmTypes_1.ELM_INTEGER_TYPE : elmTypes_1.ELM_DECIMAL_TYPE;
- }
- else if (typeof point === 'bigint') {
- this.pointType = elmTypes_1.ELM_LONG_TYPE;
- }
- else if (point.isTime && point.isTime()) {
- this.pointType = elmTypes_1.ELM_TIME_TYPE;
- }
- else if (point.isDate) {
- this.pointType = elmTypes_1.ELM_DATE_TYPE;
- }
- else if (point.isDateTime) {
- this.pointType = elmTypes_1.ELM_DATETIME_TYPE;
- }
- else if (point.isQuantity) {
- this.pointType = elmTypes_1.ELM_QUANTITY_TYPE;
- }
- }
- if (this.pointType == null) {
- this.pointType = elmTypes_1.ELM_ANY_TYPE;
- }
- }
- }
- get isInterval() {
- return true;
- }
- copy() {
- let newLow = this.low;
- let newHigh = this.high;
- if (this.low != null && typeof this.low.copy === 'function') {
- newLow = this.low.copy();
- }
- if (this.high != null && typeof this.high.copy === 'function') {
- newHigh = this.high.copy();
- }
- return new Interval(newLow, newHigh, this.lowClosed, this.highClosed, this.pointType);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#contains
- contains(item, precision) {
- if (item != null && item.isInterval) {
- throw new Error('Argument to contains must be a point');
- }
- // "The contains operator for intervals returns true if the given point is equal to the starting
- // or ending point of the interval, or greater than the starting point and less than the ending
- // point... If precision is specified and the point type is a Date, DateTime, or Time type,
- // comparisons used in the operation are performed at the specified precision."
- return logic_1.ThreeValuedLogic.and(cmp.greaterThanOrEquals(item, this.start(), precision), cmp.lessThanOrEquals(item, this.end(), precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#properly-includes
- properContains(item, precision) {
- // From contains: "If the second argument is null, the result is null."
- if (item == null) {
- return null;
- }
- else if (item.isInterval) {
- throw new Error('Argument to contains must be a point');
- }
- // "For the interval-point overload, this operator returns true if the interval contains
- // (i.e. includes) the point, and the interval is not a unit interval containing only the
- // point."
- return logic_1.ThreeValuedLogic.and(this.contains(item, precision), logic_1.ThreeValuedLogic.not(cmp.equals(this.start(), this.end())));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#properly-includes
- properlyIncludes(other, precision) {
- // "For the interval-interval overload, if either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- else if (!other.isInterval) {
- throw new Error('Argument to properlyIncludes must be an interval');
- }
- // "... the starting point of the first interval is less than or equal to the starting point of
- // the second interval, and the ending point of the first interval is greater than or equal to
- // the ending point of the second interval, and they are not the same interval... If precision
- // is specified and the point type is a Date, DateTime, or Time type, comparisons used in the
- // operation are performed at the specified precision."
- return logic_1.ThreeValuedLogic.and(cmp.lessThanOrEquals(this.start(), other.start(), precision), cmp.greaterThanOrEquals(this.end(), other.end(), precision), logic_1.ThreeValuedLogic.not(other.includes(this, precision)));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#includes
- includes(other, precision) {
- // "For the interval-interval overload, if either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "For the point-interval overload, this operator is a synonym for the contains operator."
- else if (!other.isInterval) {
- return this.contains(other, precision);
- }
- // "... the starting point of the first interval is less than or equal to the starting point of
- // the second interval, and the ending point of the first interval is greater than or equal to
- // the ending point of the second interval... If precision is specified and the point type is a
- // Date, DateTime, or Time type, comparisons used in the operation are performed at the
- // specified precision."
- return logic_1.ThreeValuedLogic.and(cmp.lessThanOrEquals(this.start(), other.start(), precision), cmp.greaterThanOrEquals(this.end(), other.end(), precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#included-in
- includedIn(other, precision) {
- // "For the interval-interval overload, if either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- else if (other == null || !other.isInterval) {
- throw new Error('Argument to includedIn must be an interval');
- }
- // "... the starting point of the first interval is greater than or equal to the starting point
- // of the second interval, and the ending point of the first interval is less than or equal to
- // the ending point of the second interval... If precision is specified and the point type is a
- // Date, DateTime, or Time type, comparisons used in the operation are performed at the
- // specified precision."
- return logic_1.ThreeValuedLogic.and(cmp.greaterThanOrEquals(this.start(), other.start(), precision), cmp.lessThanOrEquals(this.end(), other.end(), precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#overlaps
- overlaps(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the ending point of the first interval is greater than or equal to the starting point
- // of the second interval, and the starting point of the first interval is less than or equal
- // to the ending point of the second interval... If precision is specified and the point type
- // is a Date, DateTime, or Time type, comparisons used in the operation are performed at the
- // specified precision."
- return logic_1.ThreeValuedLogic.and(cmp.greaterThanOrEquals(this.end(), other.start(), precision), cmp.lessThanOrEquals(this.start(), other.end(), precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#overlaps
- overlapsAfter(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the overlaps after operator returns true if the first interval overlaps the second
- // and ends after it."
- return logic_1.ThreeValuedLogic.and(cmp.lessThanOrEquals(this.start(), other.end(), precision), cmp.greaterThan(this.end(), other.end(), precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#overlaps
- overlapsBefore(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "The operator overlaps before returns true if the first interval overlaps the second and
- // starts before it..."
- return logic_1.ThreeValuedLogic.and(cmp.greaterThanOrEquals(this.end(), other.start(), precision), cmp.lessThan(this.start(), other.start(), precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#union
- union(other) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- else if (!other.isInterval) {
- throw new Error('Argument to union must be an interval');
- }
- // "If the arguments do not overlap or meet, this operator returns null."
- if (!this.overlaps(other) && !this.meets(other)) {
- return null;
- }
- // "... the operator returns the interval that starts at the earliest starting point in either
- // argument, and ends at the latest ending point in either argument."
- let earliestStart;
- const thisIsEarlier = cmp.lessThan(this.start(), other.start());
- if (thisIsEarlier == null) {
- earliestStart = lowestUncertainty(this.start(), other.start());
- }
- else {
- earliestStart = thisIsEarlier ? this.start() : other.start();
- }
- let latestEnd;
- const thisIsLater = cmp.greaterThan(this.end(), other.end());
- if (thisIsLater == null) {
- latestEnd = highestUncertainty(this.end(), other.end());
- }
- else {
- latestEnd = thisIsLater ? this.end() : other.end();
- }
- return normalizeInterval(new Interval(earliestStart, latestEnd, true, true, this.pointType ?? other.pointType));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#intersect
- intersect(other) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- else if (!other.isInterval) {
- throw new Error('Argument to intersect must be an interval');
- }
- // "If the arguments do not overlap, this operator returns null."
- if (!this.overlaps(other)) {
- return null;
- }
- // "... the operator returns the interval that defines the overlapping portion of both
- // arguments."
- // Note: This spec definition isn't very precise, so we'll approach it similar to union:
- // The interval that starts at the latest starting point in either argument, and ends at the
- // earliest ending point in either argument.
- let latestStart;
- const thisIsLater = cmp.greaterThan(this.start(), other.start());
- if (thisIsLater == null) {
- latestStart = highestUncertainty(this.start(), other.start());
- }
- else {
- latestStart = thisIsLater ? this.start() : other.start();
- }
- let earliestEnd;
- const thisIsEarlier = cmp.lessThan(this.end(), other.end());
- if (thisIsEarlier == null) {
- earliestEnd = lowestUncertainty(this.end(), other.end());
- }
- else {
- earliestEnd = thisIsEarlier ? this.end() : other.end();
- }
- return normalizeInterval(new Interval(latestStart, earliestEnd, true, true, this.pointType ?? other.pointType));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#except
- except(other) {
- // "If either argument is null, the result is null."
- if (other === null) {
- return null;
- }
- else if (!other.isInterval) {
- throw new Error('Argument to except must be an interval');
- }
- // "... this operator returns the portion of the first interval that does not overlap with the
- // second."
- // Unresolved zulip: https://chat.fhir.org/#narrow/channel/179220-cql/topic/Unions.20on.20Date.20Intervals.20w.2F.20Different.20Precision/near/609516976
- let precision;
- if (this.pointType === elmTypes_1.ELM_DATE_TYPE ||
- this.pointType === elmTypes_1.ELM_DATETIME_TYPE ||
- this.pointType === elmTypes_1.ELM_TIME_TYPE) {
- const boundaries = [this.low, this.high, other.low, other.high].flatMap(boundary => boundary?.isUncertainty ? [boundary.low, boundary.high] : [boundary]);
- const leastPreciseBoundary = boundaries
- .filter(boundary => boundary != null)
- .reduce((least, boundary) => (least == null || boundary.isLessPrecise(least) ? boundary : least), null);
- precision = leastPreciseBoundary?.getPrecision();
- }
- if (this.overlaps(other, precision) === false) {
- return this.copy();
- }
- const overlapsBefore = this.overlapsBefore(other, precision);
- const overlapsAfter = this.overlapsAfter(other, precision);
- if (overlapsBefore && !overlapsAfter) {
- return normalizeInterval(new Interval(this.start(), other.start(), true, false, this.pointType));
- }
- else if (overlapsAfter && !overlapsBefore) {
- return normalizeInterval(new Interval(other.end(), this.end(), false, true, this.pointType));
- }
- return null;
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#same-as-2
- sameAs(other, precision) {
- // "If either or both arguments are null, the result is null."
- if (other === null) {
- return null;
- }
- // "When this operator is called with a mixture of Date- and DateTime-based intervals, the
- // Date values will be implicitly converted to DateTime values as defined by the ToDateTime
- // operator."
- // NOTE: Usually the translator will handle this implicit conversion, but just in case...
- const [left, right] = performConversionIfNecessary(this, other);
- // "... the two intervals start and end at the same value, using the semantics described in the
- // Start and End operators to determine interval boundaries, and for Date, DateTime, or Time
- // value, performing the comparisons at the specified precision, as described in the Same As
- // operator for Date, DateTime, or Time values."
- if (left.pointType === elmTypes_1.ELM_DATE_TYPE ||
- left.pointType === elmTypes_1.ELM_DATETIME_TYPE ||
- left.pointType === elmTypes_1.ELM_TIME_TYPE) {
- return logic_1.ThreeValuedLogic.and(left.start().sameAs(right.start(), precision), left.end().sameAs(right.end(), precision));
- }
- else {
- return logic_1.ThreeValuedLogic.and(cmp.equals(left.start(), right.start()), cmp.equals(left.end(), right.end()));
- }
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#same-or-after-2
- sameOrBefore(other, precision) {
- // "If either or both arguments are null, the result is null."
- if (other === null) {
- return null;
- }
- // "When this operator is called with a mixture of point values and intervals, the point
- // values are implicitly converted to an interval starting and ending on the given point
- // value."
- if (!other.isInterval) {
- other = new Interval(other, other, true, true, this.pointType);
- }
- // "When this operator is called with a mixture of Date- and DateTime-based intervals, the
- // Date values will be implicitly converted to DateTime values as defined by the ToDateTime
- // operator."
- // NOTE: Usually the translator will handle this implicit conversion, but just in case...
- const [left, right] = performConversionIfNecessary(this, other);
- // "... the first interval ends on or before the second one starts, using the semantics
- // described in the Start and End operators to determine interval boundaries, and for Date,
- // DateTime, or Time values, performing the comparisons at the specified precision, as
- // described in the Same or Before (Date, DateTime, or Time) operator for Date, DateTime, or
- // Time values."
- return cmp.lessThanOrEquals(left.end(), right.start(), precision);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#same-or-after-2
- sameOrAfter(other, precision) {
- // "If either or both arguments are null, the result is null."
- if (other === null) {
- return null;
- }
- // "When this operator is called with a mixture of point values and intervals, the point
- // values are implicitly converted to an interval starting and ending on the given point
- // value."
- if (!other.isInterval) {
- other = new Interval(other, other, true, true, this.pointType);
- }
- // "When this operator is called with a mixture of Date- and DateTime-based intervals, the
- // Date values will be implicitly converted to DateTime values as defined by the ToDateTime
- // operator."
- // NOTE: Usually the translator will handle this implicit conversion, but just in case...
- const [left, right] = performConversionIfNecessary(this, other);
- // "... the first interval starts on or after the second one ends, using the semantics
- // described in the Start and End operators to determine interval boundaries, and for Date,
- // DateTime, or Time values, performing the comparisons at the specified precision, as
- // described in the Same or After (Date, DateTime, or Time) operator for Date, DateTime, or
- // Time values."
- return cmp.greaterThanOrEquals(left.start(), right.end(), precision);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#equal-1
- equals(other) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the intervals are over the same point type..."
- if (this.pointType !== other.pointType) {
- return false;
- }
- // ... and they have the same value for the starting and ending points of the intervals as
- // determined by the Start and End operators."
- return logic_1.ThreeValuedLogic.and(cmp.equals(this.start(), other.start()), cmp.equals(this.end(), other.end()));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#after-1
- after(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... For the interval-point overload, the operator returns true if the given interval
- // starts after the given point."
- if (!other.isInterval) {
- return cmp.greaterThan(this.start(), other, precision);
- }
- // "... the starting point of the first interval is greater than the ending point of the
- // second interval."
- return cmp.greaterThan(this.start(), other.end(), precision);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#before-1
- before(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "For the interval-point overload, the operator returns true if the given interval ends
- // before the given point."
- if (!other.isInterval) {
- return cmp.lessThan(this.end(), other, precision);
- }
- // "... the ending point of the first interval is less than the starting point of the
- // second interval."
- return cmp.lessThan(this.end(), other.start(), precision);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#meets
- meets(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the ending point of the first interval is equal to the predecessor of the starting
- // point of the second, or... the starting point of the first interval is equal to the
- // successor of the ending point of the second... If precision is specified and the point type
- // is a Date, DateTime, or Time type, comparisons used in the operation are performed at the
- // specified precision."
- return logic_1.ThreeValuedLogic.or(this.meetsBefore(other, precision), this.meetsAfter(other, precision));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#meets
- meetsAfter(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the starting point of the first interval is equal to the successor of the ending point
- // of the second... If precision is specified and the point type is a Date, DateTime, or Time
- // type, comparisons used in the operation are performed at the specified precision."
- try {
- if (this.pointType === elmTypes_1.ELM_DATE_TYPE ||
- this.pointType === elmTypes_1.ELM_DATETIME_TYPE ||
- this.pointType === elmTypes_1.ELM_TIME_TYPE) {
- return this.start()?.sameAs((0, math_1.successor)(other.end(), other.pointType, precision), precision);
- }
- return cmp.equals(this.start(), (0, math_1.successor)(other.end(), other.pointType));
- }
- catch {
- return false;
- }
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#meets
- meetsBefore(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the ending point of the first interval is equal to the predecessor of the starting
- // point of the second... If precision is specified and the point type is a Date, DateTime, or
- // Time type, comparisons used in the operation are performed at the specified precision."
- try {
- if (this.pointType === elmTypes_1.ELM_DATE_TYPE ||
- this.pointType === elmTypes_1.ELM_DATETIME_TYPE ||
- this.pointType === elmTypes_1.ELM_TIME_TYPE) {
- return this.end()?.sameAs((0, math_1.predecessor)(other.start(), other.pointType, precision), precision);
- }
- return cmp.equals(this.end(), (0, math_1.predecessor)(other.start(), other.pointType));
- }
- catch {
- return false;
- }
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#start
- start() {
- // "If the low boundary of the interval is closed and null, this operator returns the minimum
- // value for the point type of the interval."
- if (this.low == null) {
- const quantityInstance = getQuantityInstanceForMinMax(this);
- const minValue = (0, math_1.minValueForType)(this.pointType, quantityInstance);
- if (this.lowClosed || minValue == null) {
- return minValue;
- }
- else {
- // "If the low boundary of the interval is open and null, this operator returns an
- // uncertainty from the minimum value for the point type of the interval to the high
- // boundary of the interval (using End operator semantics to determine the high boundary)."
- const end = ((end) => (end.isUncertainty ? end.high : end))(this.high == null ? (0, math_1.maxValueForType)(this.pointType, quantityInstance) : this.end());
- return new uncertainty_1.Uncertainty(minValue, end);
- }
- }
- // "If the low boundary of the interval is closed and non-null, this operator returns the low
- // value of the interval... If the low boundary of the interval is open and non-null, this
- // operator returns the successor of the low value of the interval."
- return this.lowClosed ? this.low : (0, math_1.successor)(this.low, this.pointType);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#end
- end() {
- // "If the high boundary of the interval is closed and null, this operator returns the maximum
- // value for the point type of the interval."
- if (this.high == null) {
- const quantityInstance = getQuantityInstanceForMinMax(this);
- const maxValue = (0, math_1.maxValueForType)(this.pointType, quantityInstance);
- if (this.highClosed || maxValue == null) {
- return maxValue;
- }
- else {
- // "If the high boundary of the interval is open and null, this operator returns an
- // uncertainty from the low boundary of the interval (using Start operator semantics to
- // determine the low boundary) to the maximum value for the point type of the interval."
- const start = ((start) => (start.isUncertainty ? start.low : start))(this.low == null ? (0, math_1.minValueForType)(this.pointType, quantityInstance) : this.start());
- return new uncertainty_1.Uncertainty(start, maxValue);
- }
- }
- // "If the high boundary of the interval is closed and non-null, this operator returns the high
- // value of the interval... If the high boundary of the interval is open and non-null, this
- // operator returns the predecessor of the high value of the interval."
- return this.highClosed ? this.high : (0, math_1.predecessor)(this.high, this.pointType);
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#starts
- starts(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the starting point of the first is equal to the starting point of the second interval
- // and the ending point of the first interval is less than or equal to the ending point of the
- // second interval."
- if (precision &&
- [elmTypes_1.ELM_DATETIME_TYPE, elmTypes_1.ELM_DATE_TYPE, elmTypes_1.ELM_TIME_TYPE].includes(this.pointType ?? other.pointType)) {
- // "If precision is specified and the point type is a Date, DateTime, or Time type,
- // comparisons used in the operation are performed at the specified precision."
- return logic_1.ThreeValuedLogic.and(this.start().sameAs(other.start(), precision), cmp.lessThanOrEquals(this.end(), other.end(), precision));
- }
- else {
- return logic_1.ThreeValuedLogic.and(cmp.equals(this.start(), other.start()), cmp.lessThanOrEquals(this.end(), other.end()));
- }
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#ends
- ends(other, precision) {
- // "If either argument is null, the result is null."
- if (other == null) {
- return null;
- }
- // "... the starting point of the first interval is greater than or equal to the starting point
- // of the second, and the ending point of the first interval is equal to the ending point of
- // the second."
- if (precision &&
- [elmTypes_1.ELM_DATETIME_TYPE, elmTypes_1.ELM_DATE_TYPE, elmTypes_1.ELM_TIME_TYPE].includes(this.pointType ?? other.pointType)) {
- // "If precision is specified and the point type is a Date, DateTime, or Time type,
- // comparisons used in the operation are performed at the specified precision."
- return logic_1.ThreeValuedLogic.and(cmp.greaterThanOrEquals(this.start(), other.start(), precision), this.end().sameAs(other.end(), precision));
- }
- else {
- return logic_1.ThreeValuedLogic.and(cmp.greaterThanOrEquals(this.start(), other.start()), cmp.equals(this.end(), other.end()));
- }
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#width
- width() {
- // "Note that because CQL defines duration and difference operations for date and time valued
- // intervals, width is not defined for intervals of these types."
- if (this.pointType === elmTypes_1.ELM_DATE_TYPE ||
- this.pointType === elmTypes_1.ELM_DATETIME_TYPE ||
- this.pointType === elmTypes_1.ELM_TIME_TYPE) {
- throw new Error('Width of Date, DateTime, and Time intervals is not supported');
- }
- // "The result of this operator is equivalent to invoking: (end of argument – start of argument)."
- const end = this.end();
- const start = this.start();
- return (0, math_1.limitDecimalPrecision)((0, math_1.subtract)(end, start, this.pointType));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#size
- size() {
- // "Note that because CQL defines duration and difference operations for date and time valued
- // intervals, size is not defined for intervals of these types."
- if (this.pointType === elmTypes_1.ELM_DATE_TYPE ||
- this.pointType === elmTypes_1.ELM_DATETIME_TYPE ||
- this.pointType === elmTypes_1.ELM_TIME_TYPE) {
- throw new Error('Size of Date, DateTime, and Time intervals is not supported');
- }
- // "The result of this operator is equivalent to invoking:
- // (end of argument – start of argument) + point-size, where point-size is determined by
- // successor of minimum T - minimum T."
- return (0, math_1.limitDecimalPrecision)((0, math_1.add)((0, math_1.subtract)(this.end(), this.start(), this.pointType), this.getPointSize(), this.pointType));
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#size
- getPointSize() {
- // "... point-size is determined by successor of minimum T - minimum T"
- let minValue = (0, math_1.minValueForType)(this.pointType, getQuantityInstanceForMinMax(this));
- // due to floating point issues in JS, we must use 0.0 for Decimal/Quantity instead of min
- if (minValue === limits_1.MIN_FLOAT_VALUE) {
- minValue = 0.0;
- }
- else if (minValue?.isQuantity) {
- minValue.value = 0.0;
- }
- if (minValue != null) {
- if (minValue.isDate || minValue.isDatetime || minValue.isTime) {
- // Legacy approach: we have been using minimum specified precision to get point size for
- // Date/DateTime/Time intervals. This makes sense to us (vs always using ms) but the spec
- // doesn't indicate this so we need to verify the expected implementation w/ the spec team.
- // E.g., point size of Interval[@2012-01, @2012-12] is 1 month, not 1 ms.
- return new quantity_1.Quantity(1, (this.low ?? this.high).getPrecision());
- }
- return (0, math_1.subtract)((0, math_1.successor)(minValue, this.pointType), minValue, this.pointType);
- }
- throw new Error('Point type of interval cannot be determined.');
- }
- // https://build.fhir.org/ig/HL7/cql/09-b-cqlreference.html#point-from
- pointFrom() {
- // "The point from operator extracts the single point from a unit interval."
- const start = this.start();
- if (cmp.equals(start, this.end())) {
- return start;
- }
- // "If the argument is not a unit interval, a run-time error is thrown."
- throw new Error('PointFrom operator may only be used on an interval containing a single point.');
- }
- toClosed() {
- // Calculate the closed flags. Despite the name of this function, if a boundary is null open,
- // we cannot close the boundary because that changes its meaning from "unknown" to "max/min value"
- const lowClosed = this.lowClosed || this.low != null;
- const highClosed = this.highClosed || this.high != null;
- if (this.pointType != null && this.pointType !== elmTypes_1.ELM_ANY_TYPE) {
- const quantityInstance = getQuantityInstanceForMinMax(this);
- let low;
- if (this.lowClosed && this.low == null) {
- low = (0, math_1.minValueForType)(this.pointType, quantityInstance);
- }
- else if (!this.lowClosed && this.low != null) {
- low = (0, math_1.successor)(this.low, this.pointType);
- }
- else {
- low = this.low;
- }
- let high;
- if (this.highClosed && this.high == null) {
- high = (0, math_1.maxValueForType)(this.pointType, quantityInstance);
- }
- else if (!this.highClosed && this.high != null) {
- high = (0, math_1.predecessor)(this.high, this.pointType);
- }
- else {
- high = this.high;
- }
- if (low == null) {
- low = new uncertainty_1.Uncertainty((0, math_1.minValueForType)(this.pointType, quantityInstance), high);
- }
- if (high == null) {
- high = new uncertainty_1.Uncertainty(low, (0, math_1.maxValueForType)(this.pointType, quantityInstance));
- }
- return new Interval(low, high, lowClosed, highClosed);
- }
- else {
- return new Interval(this.low, this.high, lowClosed, highClosed);
- }
- }
- toString() {
- const start = this.lowClosed ? '[' : '(';
- const end = this.highClosed ? ']' : ')';
- return start + this.low.toString() + ', ' + this.high.toString() + end;
- }
-}
-exports.Interval = Interval;
-// Return an interval that uses the standard null boundary conventions if appropriate:
-// - low closed boundary with min value for the type is changed to null closed boundary
-// - high closed boundary with max value for the type is changed to null closed boundary
-// - low open boundary that is uncertainty from min value of type to max value or interval high
-// value is changed to null open boundary
-// - high open boundary that is uncertainty from min value of type or interval low value to max
-// value of type is changed to null open boundary
-//
-// Justification: Since interval operations now use start() and end() to calculate and construct
-// intervals, results involving unbounded lows and highs will return boundaries with concrete
-// minimum and maximum values instead of the more familiar closed null boundary representations.
-// Similarly, results involving unknown lows and highs will return boundaries with uncertainty
-// ranges rather than the more familiar open null boundary representations. In other words,
-// intervals that started out looking "simple", such as Interval[null, 0], can result in new
-// intervals with specific values that are not obvious to users, such as Interval[-2147483648, 0].
-//
-// The normalizeInterval function recognizes those situations and converts the interval back to an
-// equivalent form that is more likely to be familiar to all users. The results of this approach
-// are also more consistent with previous implementations that did not use start() and end().
-// Note that in all cases, the pre-normalized and normalized intervals are semantically the same
-// (i.e., they represent the same exact range) even if they are represented using different
-// individual component values (i.e., low, high, lowClosed, and highClosed values).
-//
-// Examples:
-// - Interval[-2147483648, 10] --> Interval[null, 10]
-// - Interval[Uncertainty(-2147483648, 0), 10] --> Interval(null, 10]
-// - Interval[-10, 10] --> Interval[-10, 10] (no change)
-function normalizeInterval(interval) {
- const ivl = interval.copy();
- const minValue = (0, math_1.minValueForType)(ivl.pointType, getQuantityInstanceForMinMax(ivl));
- const maxValue = (0, math_1.maxValueForType)(ivl.pointType, getQuantityInstanceForMinMax(ivl));
- if (ivl.low != null && ivl.lowClosed !== false) {
- if (ivl.low.isUncertainty) {
- if (cmp.equals(ivl.low.low, minValue) &&
- (cmp.equals(ivl.low.high, maxValue) || cmp.equals(ivl.low.high, ivl.high))) {
- ivl.low = null;
- ivl.lowClosed = false;
- }
- }
- else if (cmp.equals(ivl.low, minValue)) {
- ivl.low = null;
- }
- }
- if (ivl.high != null && ivl.highClosed !== false) {
- if (ivl.high.isUncertainty) {
- if (cmp.equals(ivl.high.high, maxValue) &&
- (cmp.equals(ivl.high.low, minValue) || cmp.equals(ivl.high.low, ivl.low))) {
- ivl.high = null;
- ivl.highClosed = false;
- }
- }
- else if (cmp.equals(ivl.high, maxValue)) {
- ivl.high = null;
- }
- }
- return ivl;
-}
-function getQuantityInstanceForMinMax(ivl) {
- if (ivl?.pointType !== elmTypes_1.ELM_QUANTITY_TYPE) {
- return;
- }
- if (ivl.low?.isQuantity) {
- return ivl.low;
- }
- if (ivl.high?.isQuantity) {
- return ivl.high;
- }
- if (ivl.low?.isUncertainty) {
- if (ivl.low.low?.isQuantity) {
- return ivl.low.low;
- }
- if (ivl.low.high?.isQuantity) {
- return ivl.low.high;
- }
- }
- if (ivl.high?.isUncertainty) {
- if (ivl.high.low?.isQuantity) {
- return ivl.high.low;
- }
- if (ivl.high.high?.isQuantity) {
- return ivl.high.high;
- }
- }
-}
-function performConversionIfNecessary(left, right) {
- if (left.pointType === elmTypes_1.ELM_DATE_TYPE && right.pointType === elmTypes_1.ELM_DATETIME_TYPE) {
- left = new Interval(convertDateBoundaryToDateTime(left.low), convertDateBoundaryToDateTime(left.high), left.lowClosed, left.highClosed, elmTypes_1.ELM_DATETIME_TYPE);
- }
- else if (left.pointType === elmTypes_1.ELM_DATETIME_TYPE && right.pointType === elmTypes_1.ELM_DATE_TYPE) {
- right = new Interval(convertDateBoundaryToDateTime(right.low), convertDateBoundaryToDateTime(right.high), right.lowClosed, right.highClosed, elmTypes_1.ELM_DATETIME_TYPE);
- }
- return [left, right];
-}
-function convertDateBoundaryToDateTime(boundary) {
- const convert = (value) => value?.getDateTime() ?? value;
- if (boundary?.isUncertainty) {
- return new uncertainty_1.Uncertainty(convert(boundary.low), convert(boundary.high));
- }
- return convert(boundary);
-}
-function lowestUncertainty(x, y) {
- if (!x?.isUncertainty) {
- x = new uncertainty_1.Uncertainty(x);
- }
- if (!y?.isUncertainty) {
- y = new uncertainty_1.Uncertainty(y);
- }
- // Note: If the following comparisons result in null, we're dealing with date imprecision.
- // The spec doesn't currently say what to do; but it will be updated to indicate that the
- // coursest precision should be used (which is consistent with collapse)
- // https://chat.fhir.org/#narrow/channel/179220-cql/topic/Unions.20on.20Date.20Intervals.20w.2F.20Different.20Precision/near/609310186
- let low;
- const xLowIsLower = cmp.lessThan(x.low, y.low);
- if (xLowIsLower == null && x.low?.isLessPrecise) {
- low = x.low.isLessPrecise(y.low) ? x.low : y.low;
- }
- else {
- low = xLowIsLower ? x.low : y.low;
- }
- let high;
- const xHighIsLower = cmp.lessThan(x.high, y.high);
- if (xHighIsLower == null && x.high?.isLessPrecise) {
- high = x.high.isLessPrecise(y.high) ? x.high : y.high;
- }
- else {
- high = xHighIsLower ? x.high : y.high;
- }
- // use equivalent to consider nulls equal
- if (cmp.equivalent(low, high)) {
- return low;
- }
- return new uncertainty_1.Uncertainty(low, high);
-}
-function highestUncertainty(x, y) {
- if (!x?.isUncertainty) {
- x = new uncertainty_1.Uncertainty(x);
- }
- if (!y?.isUncertainty) {
- y = new uncertainty_1.Uncertainty(y);
- }
- // Note: If the following comparisons result in null, we're dealing with date imprecision.
- // The spec doesn't currently say what to do; but it will be updated to indicate that the
- // coursest precision should be used (which is consistent with collapse)
- // https://chat.fhir.org/#narrow/channel/179220-cql/topic/Unions.20on.20Date.20Intervals.20w.2F.20Different.20Precision/near/609310186
- let low;
- const xLowIsHigher = cmp.greaterThan(x.low, y.low);
- if (xLowIsHigher == null && x.low?.isLessPrecise) {
- low = x.low.isLessPrecise(y.low) ? x.low : y.low;
- }
- else {
- low = xLowIsHigher ? x.low : y.low;
- }
- let high;
- const xHighIsHigher = cmp.greaterThan(x.high, y.high);
- if (xHighIsHigher == null && x.high?.isLessPrecise) {
- high = x.high.isLessPrecise(y.high) ? x.high : y.high;
- }
- else {
- high = xHighIsHigher ? x.high : y.high;
- }
- // use equivalent to consider nulls equal
- if (cmp.equivalent(low, high)) {
- return low;
- }
- return new uncertainty_1.Uncertainty(low, high);
-}
-
-},{"../util/comparison":53,"../util/elmTypes":55,"../util/limits":57,"../util/math":58,"./logic":11,"./quantity":12,"./uncertainty":14}],11:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ThreeValuedLogic = void 0;
-class ThreeValuedLogic {
- static and(...val) {
- if (val.includes(false)) {
- return false;
- }
- else if (val.includes(null)) {
- return null;
- }
- else {
- return true;
- }
- }
- static or(...val) {
- if (val.includes(true)) {
- return true;
- }
- else if (val.includes(null)) {
- return null;
- }
- else {
- return false;
- }
- }
- static xor(...val) {
- if (val.includes(null)) {
- return null;
- }
- else {
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- return val.reduce((a, b) => (!a ^ !b) === 1);
- }
- }
- static not(val) {
- if (val != null) {
- return !val;
- }
- else {
- return null;
- }
- }
- static implies(left, right) {
- if (left === true) {
- return right;
- }
- else if (left === false) {
- return true;
- }
- else {
- return right === true ? true : null;
- }
- }
-}
-exports.ThreeValuedLogic = ThreeValuedLogic;
-
-},{}],12:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Quantity = void 0;
-exports.parseQuantity = parseQuantity;
-exports.doAddition = doAddition;
-exports.doSubtraction = doSubtraction;
-exports.doDivision = doDivision;
-exports.doMultiplication = doMultiplication;
-const elmTypes_1 = require("../util/elmTypes");
-const math_1 = require("../util/math");
-const units_1 = require("../util/units");
-class Quantity {
- constructor(value, unit) {
- this.value = value;
- this.unit = unit;
- if (this.value == null || isNaN(this.value)) {
- throw new Error('Cannot create a quantity with an undefined value');
- }
- else if (!(0, math_1.isValidDecimal)(this.value)) {
- throw new Error('Cannot create a quantity with an invalid decimal value');
- }
- // Attempt to parse the unit with UCUM. If it fails, throw a friendly error.
- if (this.unit != null) {
- const validation = (0, units_1.checkUnit)(this.unit);
- if (!validation.valid) {
- throw new Error(validation.message);
- }
- }
- }
- get isQuantity() {
- return true;
- }
- clone() {
- return new Quantity(this.value, this.unit);
- }
- toString() {
- return `${this.value} '${this.unit}'`;
- }
- sameOrBefore(other) {
- if (other != null && other.isQuantity) {
- const otherVal = (0, units_1.convertUnit)(other.value, other.unit, this.unit);
- if (otherVal == null) {
- return null;
- }
- else {
- return this.value <= otherVal;
- }
- }
- }
- sameOrAfter(other) {
- if (other != null && other.isQuantity) {
- const otherVal = (0, units_1.convertUnit)(other.value, other.unit, this.unit);
- if (otherVal == null) {
- return null;
- }
- else {
- return this.value >= otherVal;
- }
- }
- }
- after(other) {
- if (other != null && other.isQuantity) {
- const otherVal = (0, units_1.convertUnit)(other.value, other.unit, this.unit);
- if (otherVal == null) {
- return null;
- }
- else {
- return this.value > otherVal;
- }
- }
- }
- before(other) {
- if (other != null && other.isQuantity) {
- const otherVal = (0, units_1.convertUnit)(other.value, other.unit, this.unit);
- if (otherVal == null) {
- return null;
- }
- else {
- return this.value < otherVal;
- }
- }
- }
- equals(other) {
- if (other != null && other.isQuantity) {
- if ((!this.unit && other.unit) || (this.unit && !other.unit)) {
- return false;
- }
- else if (!this.unit && !other.unit) {
- return this.value === other.value;
- }
- else {
- const otherVal = (0, units_1.convertUnit)(other.value, other.unit, this.unit);
- if (otherVal == null) {
- return null;
- }
- else {
- return (0, math_1.decimalAdjust)('round', this.value, -8) === otherVal;
- }
- }
- }
- }
- convertUnit(toUnit) {
- const value = (0, units_1.convertUnit)(this.value, this.unit, toUnit);
- // Need to pass through constructor again to catch invalid units
- return new Quantity(value, toUnit);
- }
- dividedBy(other) {
- if (other == null || other === 0 || other.value === 0) {
- return null;
- }
- else if (!other.isQuantity) {
- // convert it to a quantity w/ unit 1
- other = new Quantity(other, '1');
- }
- const [val1, unit1, val2, unit2] = (0, units_1.normalizeUnitsWhenPossible)(this.value, this.unit, other.value, other.unit);
- const resultValue = val1 / val2;
- const resultUnit = (0, units_1.getQuotientOfUnits)(unit1, unit2);
- // Check for invalid unit or value
- if (resultUnit == null || (0, math_1.overflowsOrUnderflows)(resultValue, elmTypes_1.ELM_DECIMAL_TYPE)) {
- return null;
- }
- return new Quantity((0, math_1.decimalAdjust)('round', resultValue, -8), resultUnit);
- }
- multiplyBy(other) {
- if (other == null) {
- return null;
- }
- else if (!other.isQuantity) {
- // convert it to a quantity w/ unit 1
- other = new Quantity(other, '1');
- }
- const [val1, unit1, val2, unit2] = (0, units_1.normalizeUnitsWhenPossible)(this.value, this.unit, other.value, other.unit);
- const resultValue = val1 * val2;
- const resultUnit = (0, units_1.getProductOfUnits)(unit1, unit2);
- // Check for invalid unit or value
- if (resultUnit == null || (0, math_1.overflowsOrUnderflows)(resultValue, elmTypes_1.ELM_DECIMAL_TYPE)) {
- return null;
- }
- return new Quantity((0, math_1.decimalAdjust)('round', resultValue, -8), resultUnit);
- }
-}
-exports.Quantity = Quantity;
-function parseQuantity(str) {
- const components = /([+|-]?\d+\.?\d*)\s*('(.+)')?/.exec(str);
- if (components != null && components[1] != null) {
- const value = parseFloat(components[1]);
- if (!(0, math_1.isValidDecimal)(value)) {
- return null;
- }
- let unit;
- if (components[3] != null) {
- unit = components[3].trim();
- }
- else {
- unit = '';
- }
- return new Quantity(value, unit);
- }
- else {
- return null;
- }
-}
-function doAddition(a, b) {
- return (0, math_1.add)(a, b);
-}
-function doSubtraction(a, b) {
- return (0, math_1.subtract)(a, b);
-}
-function doDivision(a, b) {
- if (a != null && a.isQuantity) {
- return a.dividedBy(b);
- }
-}
-function doMultiplication(a, b) {
- if (a != null && a.isQuantity) {
- return a.multiplyBy(b);
- }
- else {
- return b.multiplyBy(a);
- }
-}
-
-},{"../util/elmTypes":55,"../util/math":58,"../util/units":59}],13:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Ratio = void 0;
-class Ratio {
- constructor(numerator, denominator) {
- this.numerator = numerator;
- this.denominator = denominator;
- if (numerator == null) {
- throw new Error('Cannot create a ratio with an undefined numerator');
- }
- if (denominator == null) {
- throw new Error('Cannot create a ratio with an undefined denominator');
- }
- }
- get isRatio() {
- return true;
- }
- clone() {
- return new Ratio(this.numerator.clone(), this.denominator.clone());
- }
- toString() {
- return `${this.numerator.toString()} : ${this.denominator.toString()}`;
- }
- equals(other) {
- if (other != null && other.isRatio) {
- const divided_this = this.numerator.dividedBy(this.denominator);
- const divided_other = other.numerator.dividedBy(other.denominator);
- return divided_this?.equals(divided_other);
- }
- else {
- return false;
- }
- }
- equivalent(other) {
- const equal = this.equals(other);
- return equal != null ? equal : false;
- }
-}
-exports.Ratio = Ratio;
-
-},{}],14:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Uncertainty = void 0;
-const comparison_1 = require("../util/comparison");
-const logic_1 = require("./logic");
-class Uncertainty {
- static from(obj) {
- if (obj != null && obj.isUncertainty) {
- return obj;
- }
- else {
- return new Uncertainty(obj);
- }
- }
- constructor(low = null, high) {
- this.low = low;
- this.high = high;
- const gt = (a, b) => {
- if (typeof a !== typeof b || a?.constructor !== b?.constructor) {
- // TODO: This should probably throw rather than return false.
- // Uncertainties with different types probably shouldn't be supported.
- return false;
- }
- if (typeof a.after === 'function') {
- return a.after(b);
- }
- else {
- return a > b;
- }
- };
- const isNonEnumerable = (val) => val != null && (val.isCode || val.isConcept || val.isValueSet);
- if (typeof this.high === 'undefined') {
- this.high = this.low;
- }
- if (isNonEnumerable(this.low) || isNonEnumerable(this.high)) {
- this.low = this.high = null;
- }
- if (this.low != null && this.high != null && gt(this.low, this.high)) {
- [this.low, this.high] = [this.high, this.low];
- }
- }
- get isUncertainty() {
- return true;
- }
- copy() {
- let newLow = this.low;
- let newHigh = this.high;
- if (typeof this.low.copy === 'function') {
- newLow = this.low.copy();
- }
- if (typeof this.high.copy === 'function') {
- newHigh = this.high.copy();
- }
- return new Uncertainty(newLow, newHigh);
- }
- isPoint() {
- // Note: Can't use normal equality, as that fails for Javascript dates
- // TODO: Fix after we don't need to support Javascript date uncertainties anymore
- const lte = (a, b) => {
- if (typeof a !== typeof b || a?.constructor !== b?.constructor) {
- return null;
- }
- if (typeof a.sameOrBefore === 'function') {
- return a.sameOrBefore(b);
- }
- else {
- return a <= b;
- }
- };
- const gte = (a, b) => {
- if (typeof a !== typeof b || a?.constructor !== b?.constructor) {
- return null;
- }
- if (typeof a.sameOrBefore === 'function') {
- return a.sameOrAfter(b);
- }
- else {
- return a >= b;
- }
- };
- return (this.low != null &&
- this.high != null &&
- (lte(this.low, this.high) ?? false) &&
- (gte(this.low, this.high) ?? false));
- }
- sameAs(other, precision) {
- // if this is a point, and other is not an uncertainty or a point, then we can compare directly
- if (this.isPoint()) {
- const sameFn = (a, b) => {
- if (typeof a !== typeof b || a?.constructor !== b?.constructor) {
- return false;
- }
- if (typeof a.sameAs === 'function') {
- return a.sameAs(b, precision);
- }
- else {
- return (0, comparison_1.equals)(a, b);
- }
- };
- if (!(other instanceof Uncertainty)) {
- return sameFn(this.low, other);
- }
- if (other.isPoint()) {
- return sameFn(this.low, other.low);
- }
- }
- other = Uncertainty.from(other);
- return logic_1.ThreeValuedLogic.not(logic_1.ThreeValuedLogic.or(this.lessThan(other, precision), this.greaterThan(other, precision)));
- }
- equals(other) {
- // if this is a point, and other is not an uncertainty or a point, then we can compare directly
- if (this.isPoint()) {
- if (!(other instanceof Uncertainty)) {
- return (0, comparison_1.equals)(this.low, other);
- }
- if (other.isPoint()) {
- return (0, comparison_1.equals)(this.low, other.low);
- }
- }
- other = Uncertainty.from(other);
- return logic_1.ThreeValuedLogic.not(logic_1.ThreeValuedLogic.or(this.lessThan(other), this.greaterThan(other)));
- }
- lessThan(other, precision) {
- const lt = (a, b) => {
- if (typeof a !== typeof b || a?.constructor !== b?.constructor) {
- return null;
- }
- if (typeof a.before === 'function') {
- return a.before(b, precision);
- }
- else {
- return a < b;
- }
- };
- other = Uncertainty.from(other);
- const bestCase = this.low == null || other.high == null || lt(this.low, other.high);
- const worstCase = this.high != null && other.low != null && lt(this.high, other.low);
- if (bestCase === worstCase) {
- return bestCase;
- }
- else {
- return null;
- }
- }
- greaterThan(other, precision) {
- return Uncertainty.from(other).lessThan(this, precision);
- }
- lessThanOrEquals(other, precision) {
- return logic_1.ThreeValuedLogic.not(this.greaterThan(Uncertainty.from(other), precision));
- }
- greaterThanOrEquals(other, precision) {
- return logic_1.ThreeValuedLogic.not(this.lessThan(Uncertainty.from(other), precision));
- }
-}
-exports.Uncertainty = Uncertainty;
-
-},{"../util/comparison":53,"./logic":11}],15:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.AnyTrue = exports.AllTrue = exports.PopulationVariance = exports.Variance = exports.PopulationStdDev = exports.GeometricMean = exports.Product = exports.StdDev = exports.Mode = exports.Median = exports.Avg = exports.Max = exports.Min = exports.Sum = exports.Count = void 0;
-const expression_1 = require("./expression");
-const util_1 = require("../util/util");
-const datatypes_1 = require("../datatypes/datatypes");
-const exception_1 = require("../datatypes/exception");
-const comparison_1 = require("../util/comparison");
-const builder_1 = require("./builder");
-const math_1 = require("../util/math");
-const elmTypes_1 = require("../util/elmTypes");
-class AggregateExpression extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- }
-}
-class Count extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const items = await this.source.execute(ctx);
- if ((0, util_1.typeIsArray)(items)) {
- return (0, util_1.removeNulls)(items).length;
- }
- return 0;
- }
-}
-exports.Count = Count;
-class Sum extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- let items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- try {
- items = processQuantities(items);
- }
- catch {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- if (hasOnlyQuantities(items)) {
- const values = getValuesFromQuantities(items);
- const sum = values.reduce((x, y) => x + y);
- return (0, math_1.overflowsOrUnderflows)(sum, elmTypes_1.ELM_DECIMAL_TYPE) ? null : new datatypes_1.Quantity(sum, items[0].unit);
- }
- else {
- const sum = items.reduce((x, y) => x + y);
- return (0, math_1.overflowsOrUnderflows)(sum, this.resultTypeName) ? null : sum;
- }
- }
-}
-exports.Sum = Sum;
-class Min extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const list = await this.source.execute(ctx);
- if (list == null) {
- return null;
- }
- const listWithoutNulls = (0, util_1.removeNulls)(list);
- // Check for incompatible units and return null. We don't want to convert
- // the units for Min/Max, so we throw away the converted array if it succeeds
- try {
- processQuantities(list);
- }
- catch {
- return null;
- }
- if (listWithoutNulls.length === 0) {
- return null;
- }
- // We assume the list is an array of all the same type.
- let minimum = listWithoutNulls[0];
- for (const element of listWithoutNulls) {
- if ((0, comparison_1.lessThan)(element, minimum)) {
- minimum = element;
- }
- }
- return minimum;
- }
-}
-exports.Min = Min;
-class Max extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const items = await this.source.execute(ctx);
- if (items == null) {
- return null;
- }
- const listWithoutNulls = (0, util_1.removeNulls)(items);
- // Check for incompatible units and return null. We don't want to convert
- // the units for Min/Max, so we throw away the converted array if it succeeds
- try {
- processQuantities(items);
- }
- catch {
- return null;
- }
- if (listWithoutNulls.length === 0) {
- return null;
- }
- // We assume the list is an array of all the same type.
- let maximum = listWithoutNulls[0];
- for (const element of listWithoutNulls) {
- if ((0, comparison_1.greaterThan)(element, maximum)) {
- maximum = element;
- }
- }
- return maximum;
- }
-}
-exports.Max = Max;
-class Avg extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- let items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- try {
- items = processQuantities(items);
- }
- catch {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- if (hasOnlyQuantities(items)) {
- const values = getValuesFromQuantities(items);
- const sum = values.reduce((x, y) => x + y);
- return new datatypes_1.Quantity(sum / values.length, items[0].unit);
- }
- else {
- const sum = items.reduce((x, y) => x + y);
- return sum / items.length;
- }
- }
-}
-exports.Avg = Avg;
-class Median extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- let items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- try {
- items = processQuantities(items);
- }
- catch {
- return null;
- }
- if (!hasOnlyQuantities(items)) {
- return medianOfNumbers(items);
- }
- const values = getValuesFromQuantities(items);
- const median = medianOfNumbers(values);
- return new datatypes_1.Quantity(median, items[0].unit);
- }
-}
-exports.Median = Median;
-class Mode extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- let filtered;
- try {
- filtered = processQuantities(items);
- }
- catch {
- return null;
- }
- if (hasOnlyQuantities(filtered)) {
- const values = getValuesFromQuantities(filtered);
- let mode = this.mode(values);
- if (mode.length === 1) {
- mode = mode[0];
- }
- return new datatypes_1.Quantity(mode, items[0].unit);
- }
- else {
- const mode = this.mode(filtered);
- if (mode.length === 1) {
- return mode[0];
- }
- else {
- return mode;
- }
- }
- }
- mode(arr) {
- let max = 0;
- const counts = {};
- let results = [];
- for (const elem of arr) {
- const cnt = (counts[elem] = (counts[elem] != null ? counts[elem] : 0) + 1);
- if (cnt === max && !results.includes(elem)) {
- results.push(elem);
- }
- else if (cnt > max) {
- results = [elem];
- max = cnt;
- }
- }
- return results;
- }
-}
-exports.Mode = Mode;
-class StdDev extends AggregateExpression {
- constructor(json) {
- super(json);
- this.type = 'standard_deviation';
- }
- async exec(ctx) {
- let items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- try {
- items = processQuantities(items);
- }
- catch {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- if (hasOnlyQuantities(items)) {
- const values = getValuesFromQuantities(items);
- const stdDev = this.standardDeviation(values);
- return new datatypes_1.Quantity(stdDev, items[0].unit);
- }
- else {
- return this.standardDeviation(items);
- }
- }
- standardDeviation(list) {
- const val = this.stats(list);
- if (val) {
- return val[this.type];
- }
- }
- stats(list) {
- const sum = list.reduce((x, y) => x + y);
- const mean = sum / list.length;
- let sumOfSquares = 0;
- for (const sq of list) {
- sumOfSquares += Math.pow(sq - mean, 2);
- }
- const std_var = (1 / (list.length - 1)) * sumOfSquares;
- const pop_var = (1 / list.length) * sumOfSquares;
- const std_dev = Math.sqrt(std_var);
- const pop_dev = Math.sqrt(pop_var);
- return {
- standard_variance: std_var,
- population_variance: pop_var,
- standard_deviation: std_dev,
- population_deviation: pop_dev
- };
- }
-}
-exports.StdDev = StdDev;
-class Product extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- let items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- try {
- items = processQuantities(items);
- }
- catch {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- if (hasOnlyQuantities(items)) {
- const values = getValuesFromQuantities(items);
- const product = values.reduce((x, y) => x * y);
- // Units are not multiplied for the geometric product
- return (0, math_1.overflowsOrUnderflows)(product, elmTypes_1.ELM_DECIMAL_TYPE)
- ? null
- : new datatypes_1.Quantity(product, items[0].unit);
- }
- else {
- const product = items.reduce((x, y) => x * y);
- return (0, math_1.overflowsOrUnderflows)(product, this.resultTypeName) ? null : product;
- }
- }
-}
-exports.Product = Product;
-class GeometricMean extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- let items = await this.source.execute(ctx);
- if (!(0, util_1.typeIsArray)(items)) {
- return null;
- }
- try {
- items = processQuantities(items);
- }
- catch {
- return null;
- }
- if (items.length === 0) {
- return null;
- }
- if (hasOnlyQuantities(items)) {
- const values = getValuesFromQuantities(items);
- const product = values.reduce((x, y) => x * y);
- const geoMean = Math.pow(product, 1.0 / items.length);
- return new datatypes_1.Quantity(geoMean, items[0].unit);
- }
- else {
- const product = items.reduce((x, y) => x * y);
- return Math.pow(product, 1.0 / items.length);
- }
- }
-}
-exports.GeometricMean = GeometricMean;
-class PopulationStdDev extends StdDev {
- constructor(json) {
- super(json);
- this.type = 'population_deviation';
- }
-}
-exports.PopulationStdDev = PopulationStdDev;
-class Variance extends StdDev {
- constructor(json) {
- super(json);
- this.type = 'standard_variance';
- }
-}
-exports.Variance = Variance;
-class PopulationVariance extends StdDev {
- constructor(json) {
- super(json);
- this.type = 'population_variance';
- }
-}
-exports.PopulationVariance = PopulationVariance;
-class AllTrue extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const items = await this.source.execute(ctx);
- if (items == null) {
- return true;
- }
- return (0, util_1.allTrue)((0, util_1.removeNulls)(items));
- }
-}
-exports.AllTrue = AllTrue;
-class AnyTrue extends AggregateExpression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const items = await this.source.execute(ctx);
- if (items == null) {
- return false;
- }
- return (0, util_1.anyTrue)(items);
- }
-}
-exports.AnyTrue = AnyTrue;
-function processQuantities(values) {
- const items = (0, util_1.removeNulls)(values);
- if (hasOnlyQuantities(items)) {
- return convertAllUnits(items);
- }
- else if (hasSomeQuantities(items)) {
- throw new exception_1.Exception('Cannot perform aggregate operations on mixed values of Quantities and non Quantities');
- }
- else {
- return items;
- }
-}
-function getValuesFromQuantities(quantities) {
- return quantities.map(quantity => quantity.value);
-}
-function hasOnlyQuantities(arr) {
- return arr.every(x => x.isQuantity);
-}
-function hasSomeQuantities(arr) {
- return arr.some(x => x.isQuantity);
-}
-function convertAllUnits(arr) {
- // convert all quantities in array to match the unit of the first item
- return arr.map(q => q.convertUnit(arr[0].unit));
-}
-function medianOfNumbers(numbers) {
- const items = (0, util_1.numerical_sort)(numbers, 'asc');
- if (items.length % 2 === 1) {
- // Odd number of items
- return items[(items.length - 1) / 2];
- }
- else {
- // Even number of items
- return (items[items.length / 2 - 1] + items[items.length / 2]) / 2;
- }
-}
-
-},{"../datatypes/datatypes":7,"../datatypes/exception":9,"../util/comparison":53,"../util/elmTypes":55,"../util/math":58,"../util/util":60,"./builder":17,"./expression":23}],16:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Predecessor = exports.Successor = exports.MaxValue = exports.MinValue = exports.Power = exports.Log = exports.Exp = exports.Ln = exports.Round = exports.Negate = exports.Abs = exports.Truncate = exports.Floor = exports.Ceiling = exports.Modulo = exports.TruncatedDivide = exports.Divide = exports.Multiply = exports.Subtract = exports.Add = void 0;
-const expression_1 = require("./expression");
-const MathUtil = __importStar(require("../util/math"));
-const quantity_1 = require("../datatypes/quantity");
-const uncertainty_1 = require("../datatypes/uncertainty");
-const builder_1 = require("./builder");
-const datetime_1 = require("../datatypes/datetime");
-const elmTypes_1 = require("../util/elmTypes");
-const limits_1 = require("../util/limits");
-class Add extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- return MathUtil.add(args[0], args[1], this.resultTypeName);
- }
-}
-exports.Add = Add;
-class Subtract extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- return MathUtil.subtract(args[0], args[1], this.resultTypeName);
- }
-}
-exports.Subtract = Subtract;
-class Multiply extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- const product = args.reduce((x, y) => {
- if (x.isUncertainty && !y.isUncertainty) {
- y = new uncertainty_1.Uncertainty(y, y);
- }
- else if (y.isUncertainty && !x.isUncertainty) {
- x = new uncertainty_1.Uncertainty(x, x);
- }
- if (x.isQuantity || y.isQuantity) {
- return (0, quantity_1.doMultiplication)(x, y);
- }
- else if (x.isUncertainty && y.isUncertainty) {
- if (x.low.isQuantity) {
- return new uncertainty_1.Uncertainty((0, quantity_1.doMultiplication)(x.low, y.low), (0, quantity_1.doMultiplication)(x.high, y.high));
- }
- else {
- return new uncertainty_1.Uncertainty(x.low * y.low, x.high * y.high);
- }
- }
- else {
- return x * y;
- }
- });
- if (MathUtil.overflowsOrUnderflows(product, this.resultTypeName)) {
- return null;
- }
- return product;
- }
-}
-exports.Multiply = Multiply;
-class Divide extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- const quotient = args.reduce((x, y) => {
- if (x.isUncertainty && !y.isUncertainty) {
- y = new uncertainty_1.Uncertainty(y, y);
- }
- else if (y.isUncertainty && !x.isUncertainty) {
- x = new uncertainty_1.Uncertainty(x, x);
- }
- if (x.isQuantity) {
- return (0, quantity_1.doDivision)(x, y);
- }
- else if (x.isUncertainty && y.isUncertainty) {
- if (x.low.isQuantity) {
- return new uncertainty_1.Uncertainty((0, quantity_1.doDivision)(x.low, y.high), (0, quantity_1.doDivision)(x.high, y.low));
- }
- else {
- return new uncertainty_1.Uncertainty(x.low / y.high, x.high / y.low);
- }
- }
- else {
- return x / y;
- }
- });
- // Note, anything divided by 0 is Infinity in Javascript, which will be
- // considered as overflow by this check.
- if (MathUtil.overflowsOrUnderflows(quotient, this.resultTypeName)) {
- return null;
- }
- return quotient;
- }
-}
-exports.Divide = Divide;
-class TruncatedDivide extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- let truncatedQuotient;
- if (typeof args[0] === 'bigint') {
- // bigint division always truncates
- try {
- truncatedQuotient = args.reduce((x, y) => x / y);
- }
- catch {
- // bigint divide by 0 throws an error
- return null;
- }
- }
- else {
- const quotient = args.reduce((x, y) => x / y);
- truncatedQuotient = quotient >= 0 ? Math.floor(quotient) : Math.ceil(quotient);
- }
- if (MathUtil.overflowsOrUnderflows(truncatedQuotient, this.resultTypeName)) {
- return null;
- }
- return truncatedQuotient;
- }
-}
-exports.TruncatedDivide = TruncatedDivide;
-class Modulo extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- let modulo;
- try {
- modulo = args.reduce((x, y) => x % y);
- }
- catch {
- // modulo divide by zero results in null according to specification
- return null;
- }
- return MathUtil.decimalLongOrNull(modulo);
- }
-}
-exports.Modulo = Modulo;
-class Ceiling extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- return Math.ceil(arg);
- }
-}
-exports.Ceiling = Ceiling;
-class Floor extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- return Math.floor(arg);
- }
-}
-exports.Floor = Floor;
-class Truncate extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- return arg >= 0 ? Math.floor(arg) : Math.ceil(arg);
- }
-}
-exports.Truncate = Truncate;
-class Abs extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- else if (arg.isQuantity) {
- return new quantity_1.Quantity(Math.abs(arg.value), arg.unit);
- }
- else if (typeof arg === 'bigint') {
- const absoluteValue = arg < 0n ? -arg : arg;
- return MathUtil.overflowsOrUnderflows(absoluteValue, this.resultTypeName)
- ? null
- : absoluteValue;
- }
- else {
- const absoluteValue = Math.abs(arg);
- return MathUtil.overflowsOrUnderflows(absoluteValue, this.resultTypeName)
- ? null
- : absoluteValue;
- }
- }
-}
-exports.Abs = Abs;
-class Negate extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- else if (arg.isQuantity) {
- return new quantity_1.Quantity(arg.value * -1, arg.unit);
- }
- else if (typeof arg === 'bigint') {
- const negatedValue = arg * -1n;
- return MathUtil.overflowsOrUnderflows(negatedValue, this.resultTypeName)
- ? null
- : negatedValue;
- }
- else {
- const negatedValue = arg * -1;
- return MathUtil.overflowsOrUnderflows(negatedValue, this.resultTypeName)
- ? null
- : negatedValue;
- }
- }
-}
-exports.Negate = Negate;
-class Round extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = (0, builder_1.build)(json.precision);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- const dec = this.precision != null ? await this.precision.execute(ctx) : 0;
- return Math.round(arg * Math.pow(10, dec)) / Math.pow(10, dec);
- }
-}
-exports.Round = Round;
-class Ln extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- const ln = Math.log(arg);
- return MathUtil.decimalOrNull(ln);
- }
-}
-exports.Ln = Ln;
-class Exp extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- const power = Math.exp(arg);
- if (MathUtil.overflowsOrUnderflows(power, this.resultTypeName)) {
- return null;
- }
- return power;
- }
-}
-exports.Exp = Exp;
-class Log extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- const log = args.reduce((x, y) => Math.log(x) / Math.log(y));
- return MathUtil.decimalOrNull(log);
- }
-}
-exports.Log = Log;
-class Power extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args == null || args.some((x) => x == null)) {
- return null;
- }
- const power = args.reduce((x, y) => doPower(x, y));
- // Note: The resultTypeName may be wrong if the exponent is a negative number. Math.overflowsOrUnderflows
- // already accounts for this possibility by only considering it an integer if Number.isInteger(value).
- // E.g., CQL-to-ELM says 10^-1 is an Integer result type, but the correct result is a 0.1 (a Decimal)
- if (MathUtil.overflowsOrUnderflows(power, this.resultTypeName)) {
- return null;
- }
- return power;
- }
-}
-exports.Power = Power;
-function doPower(x, y) {
- if (typeof x === 'bigint' && typeof y === 'bigint' && y < 0n) {
- // x ** y does not support negative exponents for bigint, so downgrade to number if possible, otherwise return null
- if (x < BigInt(Number.MIN_SAFE_INTEGER) ||
- x > BigInt(Number.MAX_SAFE_INTEGER) ||
- y < BigInt(Number.MIN_SAFE_INTEGER)) {
- // can't safely convert to number so just return null
- return null;
- }
- return Number(x) ** Number(y);
- }
- try {
- return x ** y;
- }
- catch {
- // will throw if BigInt goes out of range
- return null;
- }
-}
-class MinValue extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.valueType = json.valueType;
- }
- async exec(ctx) {
- if (MinValue.MIN_VALUES[this.valueType]) {
- if (this.valueType === elmTypes_1.ELM_DATETIME_TYPE) {
- const minDateTime = MinValue.MIN_VALUES[this.valueType].copy();
- minDateTime.timezoneOffset = ctx.getTimezoneOffset();
- return minDateTime;
- }
- else {
- return MinValue.MIN_VALUES[this.valueType];
- }
- }
- else {
- throw new Error(`Minimum not supported for ${this.valueType}`);
- }
- }
-}
-exports.MinValue = MinValue;
-MinValue.MIN_VALUES = {
- [elmTypes_1.ELM_INTEGER_TYPE]: limits_1.MIN_INT_VALUE,
- [elmTypes_1.ELM_LONG_TYPE]: limits_1.MIN_LONG_VALUE,
- [elmTypes_1.ELM_DECIMAL_TYPE]: limits_1.MIN_FLOAT_VALUE,
- [elmTypes_1.ELM_DATETIME_TYPE]: datetime_1.MIN_DATETIME_VALUE,
- [elmTypes_1.ELM_DATE_TYPE]: datetime_1.MIN_DATE_VALUE,
- [elmTypes_1.ELM_TIME_TYPE]: datetime_1.MIN_TIME_VALUE
-};
-class MaxValue extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.valueType = json.valueType;
- }
- async exec(ctx) {
- if (MaxValue.MAX_VALUES[this.valueType] != null) {
- if (this.valueType === elmTypes_1.ELM_DATETIME_TYPE) {
- const maxDateTime = MaxValue.MAX_VALUES[this.valueType].copy();
- maxDateTime.timezoneOffset = ctx.getTimezoneOffset();
- return maxDateTime;
- }
- else {
- return MaxValue.MAX_VALUES[this.valueType];
- }
- }
- else {
- throw new Error(`Maximum not supported for ${this.valueType}`);
- }
- }
-}
-exports.MaxValue = MaxValue;
-MaxValue.MAX_VALUES = {
- [elmTypes_1.ELM_INTEGER_TYPE]: limits_1.MAX_INT_VALUE,
- [elmTypes_1.ELM_LONG_TYPE]: limits_1.MAX_LONG_VALUE,
- [elmTypes_1.ELM_DECIMAL_TYPE]: limits_1.MAX_FLOAT_VALUE,
- [elmTypes_1.ELM_DATETIME_TYPE]: datetime_1.MAX_DATETIME_VALUE,
- [elmTypes_1.ELM_DATE_TYPE]: datetime_1.MAX_DATE_VALUE,
- [elmTypes_1.ELM_TIME_TYPE]: datetime_1.MAX_TIME_VALUE
-};
-class Successor extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- let successor = null;
- try {
- // MathUtil.successor throws on overflow, and the exception is used in
- // the logic for evaluating `meets`, so it can't be changed to just return null
- successor = MathUtil.successor(arg, this.resultTypeName);
- }
- catch (e) {
- if (e instanceof MathUtil.OverFlowException) {
- return null;
- }
- }
- if (MathUtil.overflowsOrUnderflows(successor, this.resultTypeName)) {
- return null;
- }
- return successor;
- }
-}
-exports.Successor = Successor;
-class Predecessor extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- let predecessor = null;
- try {
- // MathUtil.predecessor throws on underflow, and the exception is used in
- // the logic for evaluating `meets`, so it can't be changed to just return null
- predecessor = MathUtil.predecessor(arg, this.resultTypeName);
- }
- catch (e) {
- if (e instanceof MathUtil.OverFlowException) {
- return null;
- }
- }
- if (MathUtil.overflowsOrUnderflows(predecessor, this.resultTypeName)) {
- return null;
- }
- return predecessor;
- }
-}
-exports.Predecessor = Predecessor;
-
-},{"../datatypes/datetime":8,"../datatypes/quantity":12,"../datatypes/uncertainty":14,"../util/elmTypes":55,"../util/limits":57,"../util/math":58,"./builder":17,"./expression":23}],17:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.build = build;
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-const E = __importStar(require("./expressions"));
-const util_1 = require("../util/util");
-function build(json) {
- if (json == null) {
- return json;
- }
- if ((0, util_1.typeIsArray)(json)) {
- return json.map(child => build(child));
- }
- if (json.type === 'FunctionRef') {
- return new E.FunctionRef(json);
- }
- else if (json.type === 'Literal') {
- return E.Literal.from(json);
- }
- else if (functionExists(json.type)) {
- return constructByName(json.type, json);
- }
- else {
- return null;
- }
-}
-function functionExists(name) {
- // @ts-ignore
- return typeof E[name] === 'function';
-}
-function constructByName(name, json) {
- // @ts-ignore
- return new E[name](json);
-}
-
-},{"../util/util":60,"./expressions":24}],18:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.CalculateAgeAt = exports.CalculateAge = exports.Concept = exports.ConceptRef = exports.ConceptDef = exports.Code = exports.CodeRef = exports.CodeDef = exports.CodeSystemRef = exports.CodeSystemDef = exports.ExpandValueSet = exports.InValueSet = exports.AnyInValueSet = exports.ValueSetRef = exports.ValueSetDef = void 0;
-const expression_1 = require("./expression");
-const dt = __importStar(require("../datatypes/datatypes"));
-const builder_1 = require("./builder");
-const util_1 = require("../util/util");
-class ValueSetDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.id = json.id;
- this.version = json.version;
- this.codesystems = json.codeSystem?.map((cs) => new CodeSystemRef(cs));
- }
- async exec(ctx) {
- let codeSystems;
- if (this.codesystems) {
- codeSystems = (await Promise.all(this.codesystems.map(async (csRef) => csRef.exec(ctx))));
- }
- const valueset = new dt.CQLValueSet(this.id, this.version, this.name, codeSystems);
- // ctx.rootContext().set(this.name, valueset); Note (2025): this seems to be unneccesary, remove completely in future if not needed
- return valueset;
- }
-}
-exports.ValueSetDef = ValueSetDef;
-class ValueSetRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.libraryName = json.libraryName;
- }
- async exec(ctx) {
- let valueset = ctx.getValueSet(this.name, this.libraryName);
- if (valueset instanceof expression_1.Expression) {
- valueset = await valueset.execute(ctx);
- }
- return valueset;
- }
-}
-exports.ValueSetRef = ValueSetRef;
-class AnyInValueSet extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.codes = (0, builder_1.build)(json.codes);
- this.valueset = json.valueset
- ? new ValueSetRef(json.valueset)
- : (0, builder_1.build)(json.valuesetExpression);
- }
- async exec(ctx) {
- const codes = await this.codes.execute(ctx);
- // spec indicates to return false if code is null, throw error if value set cannot be resolved
- if (codes == null) {
- return false;
- }
- const valueset = await this.valueset.execute(ctx);
- if (valueset == null || !valueset.isValueSet) {
- throw new Error('ValueSet must be provided to AnyInValueSet expression');
- }
- const vsExpansion = await (0, util_1.resolveValueSet)(valueset, ctx);
- return codes.some((code) => vsExpansion.hasMatch(code));
- }
-}
-exports.AnyInValueSet = AnyInValueSet;
-class InValueSet extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.code = (0, builder_1.build)(json.code);
- this.valueset = json.valueset
- ? new ValueSetRef(json.valueset)
- : (0, builder_1.build)(json.valuesetExpression);
- }
- async exec(ctx) {
- const code = await this.code.execute(ctx);
- // spec indicates to return false if code is null, throw error if value set cannot be resolved
- if (code == null) {
- return false;
- }
- const valueset = await this.valueset.execute(ctx);
- if (valueset == null || !valueset.isValueSet) {
- throw new Error('ValueSet must be provided to InValueSet expression');
- }
- // If there is a code and valueset return whether or not the valueset has the code
- const vsExpansion = await (0, util_1.resolveValueSet)(valueset, ctx);
- return vsExpansion.hasMatch(code);
- }
-}
-exports.InValueSet = InValueSet;
-class ExpandValueSet extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.valueset = (0, builder_1.build)(json.operand);
- }
- async exec(ctx) {
- const valueset = await this.valueset.execute(ctx);
- if (valueset == null) {
- return null;
- }
- else if (!valueset.isValueSet) {
- throw new Error('ExpandValueSet function invoked on object that is not a ValueSet');
- }
- const vsExpansion = await (0, util_1.resolveValueSet)(valueset, ctx);
- return vsExpansion.expand();
- }
-}
-exports.ExpandValueSet = ExpandValueSet;
-class CodeSystemDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.id = json.id;
- this.version = json.version;
- }
- async exec(_ctx) {
- return new dt.CodeSystem(this.id, this.version, this.name);
- }
-}
-exports.CodeSystemDef = CodeSystemDef;
-class CodeSystemRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.libraryName = json.libraryName;
- }
- async exec(ctx) {
- const codeSystemDef = ctx.getCodeSystem(this.name, this.libraryName);
- return codeSystemDef.execute(ctx);
- }
-}
-exports.CodeSystemRef = CodeSystemRef;
-class CodeDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.id = json.id;
- this.systemName = json.codeSystem.name;
- this.display = json.display;
- }
- async exec(ctx) {
- const system = await ctx.getCodeSystem(this.systemName).execute(ctx);
- return new dt.Code(this.id, system.id, system.version, this.display);
- }
-}
-exports.CodeDef = CodeDef;
-class CodeRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.library = json.libraryName;
- }
- async exec(ctx) {
- ctx = this.library ? ctx.getLibraryContext(this.library) : ctx;
- const codeDef = ctx.getCode(this.name);
- return codeDef ? codeDef.execute(ctx) : undefined;
- }
-}
-exports.CodeRef = CodeRef;
-class Code extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.code = json.code;
- this.systemName = json.system.name;
- this.version = json.version;
- this.display = json.display;
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isCode() {
- return true;
- }
- async exec(ctx) {
- const system = ctx.getCodeSystem(this.systemName) || {};
- return new dt.Code(this.code, system.id, this.version, this.display);
- }
-}
-exports.Code = Code;
-class ConceptDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.display = json.display;
- this.codes = json.code;
- }
- async exec(ctx) {
- const codes = await Promise.all(this.codes.map(async (code) => {
- const codeDef = ctx.getCode(code.name);
- return codeDef ? codeDef.execute(ctx) : undefined;
- }));
- return new dt.Concept(codes, this.display);
- }
-}
-exports.ConceptDef = ConceptDef;
-class ConceptRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- }
- async exec(ctx) {
- const conceptDef = ctx.getConcept(this.name);
- return conceptDef ? conceptDef.execute(ctx) : undefined;
- }
-}
-exports.ConceptRef = ConceptRef;
-class Concept extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.codes = json.code;
- this.display = json.display;
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isConcept() {
- return true;
- }
- toCode(ctx, code) {
- const system = ctx.getCodeSystem(code.system.name) || {};
- return new dt.Code(code.code, system.id, code.version, code.display);
- }
- async exec(ctx) {
- const codes = this.codes.map((code) => this.toCode(ctx, code));
- return new dt.Concept(codes, this.display);
- }
-}
-exports.Concept = Concept;
-class CalculateAge extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const birthDate = await this.execArgs(ctx);
- // From the spec: "Note that for AgeInYears and AgeInMonths, the birthDate is specified as a
- // Date and Today() is used to obtain the current date; whereas with the other precisions,
- // birthDate is specified as a DateTime, and Now() is used to obtain the current DateTime."
- // See: https://cql.hl7.org/09-b-cqlreference.html#age
- let asOf;
- if (this.precision.toLowerCase() === dt.DateTime.Unit.YEAR ||
- this.precision.toLowerCase() === dt.DateTime.Unit.MONTH) {
- asOf = dt.DateTime.fromJSDate(ctx.getExecutionDateTime()).getDate();
- }
- else {
- asOf = dt.DateTime.fromJSDate(ctx.getExecutionDateTime());
- }
- return calculateAge(this.precision, birthDate, asOf);
- }
-}
-exports.CalculateAge = CalculateAge;
-class CalculateAgeAt extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const [birthDate, asOf] = await this.execArgs(ctx);
- const timeZoneOffset = ctx.getExecutionDateTime().timezoneOffset;
- return calculateAge(this.precision, birthDate, asOf, timeZoneOffset);
- }
-}
-exports.CalculateAgeAt = CalculateAgeAt;
-/**
- * Calculates the age as of a certain date based on the passed in birth date. If the asOf date is
- * a Date, then birth date will be converted to a Date (if necessary) before calculation is
- * performed. If the asOf is a DateTime, then the birth date will be converted to a DateTime (if
- * necessary) before calculation is performed. The result is an integer or uncertainty specifying
- * the age in the requested precision units.
- * @param precision - the precision as specified in the ELM (e.g., Year, Month, Week, etc.)
- * @param birthDate - the birth date to use for age calculations (may be Date or DateTime)
- * @param asOf - the date on which the age should be calculated (may be Date or DateTime)
- * @param timeZoneOffset - the passed in timeZoneOffset (if it exists) to be used when
- * converting birthDate from a Date to a DateTime
- * @returns the age as an integer or uncertainty in the requested precision units
- */
-function calculateAge(precision, birthDate, asOf, timeZoneOffset) {
- if (birthDate != null && asOf != null) {
- // Ensure we use like types (Date or DateTime) based on asOf type
- if (asOf.isDate && birthDate.isDateTime) {
- birthDate = birthDate.getDate();
- }
- else if (asOf.isDateTime && birthDate.isDate) {
- birthDate = birthDate.getDateTime(timeZoneOffset);
- }
- const result = birthDate.durationBetween(asOf, precision.toLowerCase());
- if (result?.isPoint()) {
- return result.low;
- }
- else {
- return result;
- }
- }
- return null;
-}
-
-},{"../datatypes/datatypes":7,"../util/util":60,"./builder":17,"./expression":23}],19:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.GreaterOrEqual = exports.Greater = exports.LessOrEqual = exports.Less = void 0;
-const expression_1 = require("./expression");
-const datatypes_1 = require("../datatypes/datatypes");
-// Equal is completely handled by overloaded#Equal
-// NotEqual is completely handled by overloaded#Equal
-class Less extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = (await this.execArgs(ctx)).map((x) => datatypes_1.Uncertainty.from(x));
- if (args[0] == null || args[1] == null) {
- return null;
- }
- return args[0].lessThan(args[1]);
- }
-}
-exports.Less = Less;
-class LessOrEqual extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = (await this.execArgs(ctx)).map((x) => datatypes_1.Uncertainty.from(x));
- if (args[0] == null || args[1] == null) {
- return null;
- }
- return args[0].lessThanOrEquals(args[1]);
- }
-}
-exports.LessOrEqual = LessOrEqual;
-class Greater extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = (await this.execArgs(ctx)).map((x) => datatypes_1.Uncertainty.from(x));
- if (args[0] == null || args[1] == null) {
- return null;
- }
- return args[0].greaterThan(args[1]);
- }
-}
-exports.Greater = Greater;
-class GreaterOrEqual extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = (await this.execArgs(ctx)).map((x) => datatypes_1.Uncertainty.from(x));
- if (args[0] == null || args[1] == null) {
- return null;
- }
- return args[0].greaterThanOrEquals(args[1]);
- }
-}
-exports.GreaterOrEqual = GreaterOrEqual;
-
-},{"../datatypes/datatypes":7,"./expression":23}],20:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Case = exports.CaseItem = exports.If = void 0;
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-const comparison_1 = require("../util/comparison");
-// TODO: Spec lists "Conditional", but it's "If" in the XSD
-class If extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.condition = (0, builder_1.build)(json.condition);
- this.th = (0, builder_1.build)(json.then);
- this.els = (0, builder_1.build)(json.else);
- }
- async exec(ctx) {
- if (await this.condition.execute(ctx)) {
- return this.th.execute(ctx);
- }
- else {
- return this.els.execute(ctx);
- }
- }
-}
-exports.If = If;
-class CaseItem {
- constructor(json) {
- this.when = (0, builder_1.build)(json.when);
- this.then = (0, builder_1.build)(json.then);
- }
-}
-exports.CaseItem = CaseItem;
-class Case extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.comparand = (0, builder_1.build)(json.comparand);
- this.caseItems = json.caseItem.map((ci) => new CaseItem(ci));
- this.els = (0, builder_1.build)(json.else);
- }
- async exec(ctx) {
- if (this.comparand) {
- return this.exec_selected(ctx);
- }
- else {
- return this.exec_standard(ctx);
- }
- }
- async exec_selected(ctx) {
- const val = await this.comparand.execute(ctx);
- for (const ci of this.caseItems) {
- if ((0, comparison_1.equals)(await ci.when.execute(ctx), val)) {
- return ci.then.execute(ctx);
- }
- }
- return this.els.execute(ctx);
- }
- async exec_standard(ctx) {
- for (const ci of this.caseItems) {
- if (await ci.when.execute(ctx)) {
- return ci.then.execute(ctx);
- }
- }
- return this.els.execute(ctx);
- }
-}
-exports.Case = Case;
-
-},{"../util/comparison":53,"./builder":17,"./expression":23}],21:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.DurationBetween = exports.DifferenceBetween = exports.TimezoneOffsetFrom = exports.TimeFrom = exports.DateFrom = exports.DateTimeComponentFrom = exports.TimeOfDay = exports.Now = exports.Today = exports.Time = exports.Date = exports.DateTime = void 0;
-exports.doAfter = doAfter;
-exports.doBefore = doBefore;
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-const literal_1 = require("./literal");
-const DT = __importStar(require("../datatypes/datatypes"));
-const elmTypes_1 = require("../util/elmTypes");
-class DateTime extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.json = json;
- }
- async exec(ctx) {
- for (const property of DateTime.PROPERTIES) {
- // if json does not contain 'timezoneOffset' set it to the executionDateTime from the context
- if (this.json[property] != null) {
- // @ts-ignore
- this[property] = (0, builder_1.build)(this.json[property]);
- }
- else if (property === 'timezoneOffset' && ctx.getTimezoneOffset() != null) {
- // @ts-ignore
- this[property] = literal_1.Literal.from({
- type: 'Literal',
- value: ctx.getTimezoneOffset(),
- valueType: elmTypes_1.ELM_INTEGER_TYPE
- });
- }
- }
- const args = await Promise.all(
- // @ts-ignore
- DateTime.PROPERTIES.map(async (p) => (this[p] != null ? this[p].execute(ctx) : undefined)));
- return new DT.DateTime(...args);
- }
-}
-exports.DateTime = DateTime;
-DateTime.PROPERTIES = [
- 'year',
- 'month',
- 'day',
- 'hour',
- 'minute',
- 'second',
- 'millisecond',
- 'timezoneOffset'
-];
-class Date extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.json = json;
- }
- async exec(ctx) {
- for (const property of Date.PROPERTIES) {
- if (this.json[property] != null) {
- // @ts-ignore
- this[property] = (0, builder_1.build)(this.json[property]);
- }
- }
- const args = await Promise.all(
- // @ts-ignore
- Date.PROPERTIES.map(async (p) => (this[p] != null ? this[p].execute(ctx) : undefined)));
- return new DT.Date(...args);
- }
-}
-exports.Date = Date;
-Date.PROPERTIES = ['year', 'month', 'day'];
-class Time extends expression_1.Expression {
- constructor(json) {
- super(json);
- for (const property of Time.PROPERTIES) {
- if (json[property] != null) {
- // @ts-ignore
- this[property] = (0, builder_1.build)(json[property]);
- }
- }
- }
- async exec(ctx) {
- const args = await Promise.all(
- // @ts-ignore
- Time.PROPERTIES.map(async (p) => (this[p] != null ? this[p].execute(ctx) : undefined)));
- return new DT.DateTime(0, 1, 1, ...args).getTime();
- }
-}
-exports.Time = Time;
-Time.PROPERTIES = ['hour', 'minute', 'second', 'millisecond'];
-class Today extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return ctx.getExecutionDateTime().getDate();
- }
-}
-exports.Today = Today;
-class Now extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return ctx.getExecutionDateTime();
- }
-}
-exports.Now = Now;
-class TimeOfDay extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return ctx.getExecutionDateTime().getTime();
- }
-}
-exports.TimeOfDay = TimeOfDay;
-class DateTimeComponentFrom extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return arg[this.precision.toLowerCase()];
- }
- else {
- return null;
- }
- }
-}
-exports.DateTimeComponentFrom = DateTimeComponentFrom;
-class DateFrom extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const date = await this.execArgs(ctx);
- if (date != null) {
- return date.getDate();
- }
- else {
- return null;
- }
- }
-}
-exports.DateFrom = DateFrom;
-class TimeFrom extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const date = await this.execArgs(ctx);
- if (date != null) {
- return date.getTime();
- }
- else {
- return null;
- }
- }
-}
-exports.TimeFrom = TimeFrom;
-class TimezoneOffsetFrom extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const date = await this.execArgs(ctx);
- if (date != null) {
- return date.timezoneOffset;
- }
- else {
- return null;
- }
- }
-}
-exports.TimezoneOffsetFrom = TimezoneOffsetFrom;
-// Delegated to by overloaded#After
-function doAfter(a, b, precision) {
- return a.after(b, precision);
-}
-// Delegated to by overloaded#Before
-function doBefore(a, b, precision) {
- return a.before(b, precision);
-}
-class DifferenceBetween extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- // Check to make sure args exist and that they have differenceBetween functions so that they can be compared to one another
- if (args[0] == null ||
- args[1] == null ||
- typeof args[0].differenceBetween !== 'function' ||
- typeof args[1].differenceBetween !== 'function') {
- return null;
- }
- const result = args[0].differenceBetween(args[1], this.precision != null ? this.precision.toLowerCase() : undefined);
- if (result != null && result.isPoint()) {
- return result.low;
- }
- else {
- return result;
- }
- }
-}
-exports.DifferenceBetween = DifferenceBetween;
-class DurationBetween extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- // Check to make sure args exist and that they have durationBetween functions so that they can be compared to one another
- if (args[0] == null ||
- args[1] == null ||
- typeof args[0].durationBetween !== 'function' ||
- typeof args[1].durationBetween !== 'function') {
- return null;
- }
- const result = args[0].durationBetween(args[1], this.precision != null ? this.precision.toLowerCase() : undefined);
- if (result != null && result.isPoint()) {
- return result.low;
- }
- else {
- return result;
- }
- }
-}
-exports.DurationBetween = DurationBetween;
-
-},{"../datatypes/datatypes":7,"../util/elmTypes":55,"./builder":17,"./expression":23,"./literal":30}],22:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.VersionedIdentifier = exports.IncludeDef = exports.UsingDef = void 0;
-const expression_1 = require("./expression");
-class UsingDef extends expression_1.UnimplementedExpression {
-}
-exports.UsingDef = UsingDef;
-class IncludeDef extends expression_1.UnimplementedExpression {
-}
-exports.IncludeDef = IncludeDef;
-class VersionedIdentifier extends expression_1.UnimplementedExpression {
-}
-exports.VersionedIdentifier = VersionedIdentifier;
-
-},{"./expression":23}],23:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.UnimplementedExpression = exports.Expression = void 0;
-const util_1 = require("../util/util");
-const customErrors_1 = require("../util/customErrors");
-const builder_1 = require("./builder");
-class Expression {
- constructor(json) {
- if (json.operand != null) {
- const op = (0, builder_1.build)(json.operand);
- if ((0, util_1.typeIsArray)(json.operand)) {
- this.args = op;
- }
- else {
- this.arg = op;
- }
- }
- if (json.localId != null) {
- this.localId = json.localId;
- }
- if (json.locator != null) {
- this.locator = json.locator;
- }
- if (json.resultTypeName != null) {
- this.resultTypeName = json.resultTypeName;
- }
- if (json.resultTypeSpecifier != null) {
- this.resultTypeSpecifier = json.resultTypeSpecifier;
- }
- }
- async execute(ctx) {
- try {
- if (this.localId != null) {
- // Store the localId and result on the root context of this library
- const execValue = await this.exec(ctx);
- ctx.rootContext().setLocalIdWithResult(this.localId, execValue);
- return execValue;
- }
- else {
- // Ensure we await this.exec before returning so AnnotatedError logic gets hit
- const execValue = await this.exec(ctx);
- return execValue;
- }
- }
- catch (e) {
- if (e instanceof customErrors_1.AnnotatedError) {
- throw e;
- }
- const libraryIdentifier = this.getRecursiveLibraryIdentifier(ctx);
- throw new customErrors_1.AnnotatedError(e, this.constructor.name, libraryIdentifier, this.localId, this.locator);
- }
- }
- async exec(_ctx) {
- return this;
- }
- async execArgs(ctx) {
- if (this.args != null) {
- const retVals = [];
- for (let index = 0; index < this.args.length; index++) {
- const arg = this.args[index];
- retVals.push(await arg.execute(ctx));
- }
- return retVals;
- }
- else if (this.arg != null) {
- return this.arg.execute(ctx);
- }
- else {
- return null;
- }
- }
- /**
- * Function used in error reporting during execution. Retrieves the source library from
- * the context if it exists, or recursively traverses the context's parents until a source
- * library identifier and version are found.
- */
- getRecursiveLibraryIdentifier(ctx) {
- const identifier = ctx.library?.source?.library
- ?.identifier;
- if (identifier) {
- return `${identifier.id}${identifier.version ? `|${identifier.version}` : ''}`;
- }
- else {
- return ctx.parent ? this.getRecursiveLibraryIdentifier(ctx.parent) : '(unknown)';
- }
- }
-}
-exports.Expression = Expression;
-class UnimplementedExpression extends Expression {
- constructor(json) {
- super(json);
- this.json = json;
- }
- async exec(_ctx) {
- throw new Error(`Unimplemented Expression: ${this.json.type}`);
- }
-}
-exports.UnimplementedExpression = UnimplementedExpression;
-
-},{"../util/customErrors":54,"../util/util":60,"./builder":17}],24:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.doProperContains = exports.doContains = exports.doExcept = exports.doIncludes = exports.doIntersect = exports.doProperIncludes = exports.doAfter = exports.doUnion = exports.doBefore = void 0;
-__exportStar(require("./expression"), exports);
-__exportStar(require("./aggregate"), exports);
-__exportStar(require("./arithmetic"), exports);
-__exportStar(require("./clinical"), exports);
-__exportStar(require("./comparison"), exports);
-__exportStar(require("./conditional"), exports);
-__exportStar(require("./datetime"), exports);
-__exportStar(require("./declaration"), exports);
-__exportStar(require("./external"), exports);
-__exportStar(require("./instance"), exports);
-__exportStar(require("./interval"), exports);
-__exportStar(require("./list"), exports);
-__exportStar(require("./literal"), exports);
-__exportStar(require("./logical"), exports);
-__exportStar(require("./message"), exports);
-__exportStar(require("./nullological"), exports);
-__exportStar(require("./parameters"), exports);
-__exportStar(require("./quantity"), exports);
-__exportStar(require("./query"), exports);
-__exportStar(require("./ratio"), exports);
-__exportStar(require("./reusable"), exports);
-__exportStar(require("./string"), exports);
-__exportStar(require("./structured"), exports);
-__exportStar(require("./type"), exports);
-__exportStar(require("./overloaded"), exports);
-// Re-exporting interval functions as overrides to avoid ambiguity
-// https://stackoverflow.com/questions/41293108/how-to-do-re-export-with-overrides
-// TODO: we should improve this by perhaps renaming and reworking these functions
-// it's a bit confusing right now giving the interval exports precedence over the others
-const interval_1 = require("./interval");
-Object.defineProperty(exports, "doBefore", { enumerable: true, get: function () { return interval_1.doBefore; } });
-Object.defineProperty(exports, "doUnion", { enumerable: true, get: function () { return interval_1.doUnion; } });
-Object.defineProperty(exports, "doAfter", { enumerable: true, get: function () { return interval_1.doAfter; } });
-Object.defineProperty(exports, "doProperIncludes", { enumerable: true, get: function () { return interval_1.doProperIncludes; } });
-Object.defineProperty(exports, "doIntersect", { enumerable: true, get: function () { return interval_1.doIntersect; } });
-Object.defineProperty(exports, "doIncludes", { enumerable: true, get: function () { return interval_1.doIncludes; } });
-Object.defineProperty(exports, "doExcept", { enumerable: true, get: function () { return interval_1.doExcept; } });
-Object.defineProperty(exports, "doContains", { enumerable: true, get: function () { return interval_1.doContains; } });
-Object.defineProperty(exports, "doProperContains", { enumerable: true, get: function () { return interval_1.doProperContains; } });
-
-},{"./aggregate":15,"./arithmetic":16,"./clinical":18,"./comparison":19,"./conditional":20,"./datetime":21,"./declaration":22,"./expression":23,"./external":25,"./instance":26,"./interval":27,"./list":29,"./literal":30,"./logical":31,"./message":32,"./nullological":33,"./overloaded":34,"./parameters":35,"./quantity":36,"./query":37,"./ratio":38,"./reusable":39,"./string":40,"./structured":41,"./type":42}],25:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Retrieve = void 0;
-const expression_1 = require("./expression");
-const util_1 = require("../util/util");
-const comparison_1 = require("../util/comparison");
-const builder_1 = require("./builder");
-const clinical_1 = require("../datatypes/clinical");
-class Retrieve extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.datatype = json.dataType;
- this.templateId = json.templateId;
- this.codeProperty = json.codeProperty;
- this.codeComparator = json.codeComparator;
- this.codes = (0, builder_1.build)(json.codes);
- this.dateProperty = json.dateProperty;
- this.dateRange = (0, builder_1.build)(json.dateRange);
- }
- async exec(ctx) {
- // Object with retrieve information to pass back to patient source
- // Always assign datatype. Assign the others only if present
- const retrieveDetails = {
- datatype: this.datatype,
- ...(this.codeProperty ? { codeProperty: this.codeProperty } : {}),
- ...(this.codeComparator ? { codeComparator: this.codeComparator } : {}),
- ...(this.dateProperty ? { dateProperty: this.dateProperty } : {})
- };
- if (this.codes) {
- const executedCodes = await this.codes.execute(ctx);
- if (executedCodes == null) {
- return [];
- }
- if ((0, util_1.typeIsArray)(executedCodes)) {
- retrieveDetails.codes = executedCodes;
- }
- else {
- // retrieveDetails codes are expected to be expanded for external usage
- retrieveDetails.codes = await (0, util_1.resolveValueSet)(executedCodes, ctx);
- }
- }
- if (this.dateRange) {
- retrieveDetails.dateRange = await this.dateRange.execute(ctx);
- }
- if (this.templateId) {
- retrieveDetails.templateId = this.templateId;
- }
- let records = await ctx.findRecords(this.templateId != null ? this.templateId : this.datatype, retrieveDetails);
- if (retrieveDetails.codes) {
- records = records.filter((r) => this.recordMatchesCodesOrVS(r, retrieveDetails.codes));
- }
- if (retrieveDetails.dateRange && this.dateProperty) {
- records = records.filter((r) => retrieveDetails.dateRange?.includes(r.getDateOrInterval(this.dateProperty)));
- }
- if (Array.isArray(records)) {
- ctx.evaluatedRecords.push(...records);
- }
- else {
- ctx.evaluatedRecords.push(records);
- }
- return records;
- }
- recordMatchesCodesOrVS(record, codes) {
- let recordCodeValue = record.getCode(this.codeProperty);
- if (Array.isArray(recordCodeValue)) {
- if (recordCodeValue.length == 0) {
- return false;
- }
- }
- else if (!recordCodeValue) {
- return false;
- }
- else {
- recordCodeValue = [recordCodeValue];
- }
- switch (this.codeComparator) {
- case 'in':
- return this.in(recordCodeValue, codes);
- case '~':
- return this.equivalent(recordCodeValue, codes);
- case '=':
- return this.equal(recordCodeValue, codes);
- default:
- // if there's a terminology filter, there should always be a comparator,
- // but just in case, default to "in"
- return this.in(recordCodeValue, codes);
- }
- }
- in(lhs, rhs) {
- if (rhs instanceof clinical_1.ValueSet || rhs instanceof clinical_1.CodeSystem) {
- return rhs.hasMatch(lhs);
- }
- else {
- // For code lists, fallback to the implementation in ~ . See comments below.
- return this.equivalent(lhs, rhs);
- }
- }
- equivalent(lhs, rhs) {
- if (rhs instanceof clinical_1.CodeSystem) {
- throw new Error("Operator '~' is not defined for Code ~ CodeSystem");
- }
- else if (rhs instanceof clinical_1.ValueSet) {
- // It's not obvious that code ~ ValueSet and code ~ Code[] should be allowed,
- // when code ~ CodeSystem is disallowed. Same for operator = below.
- // In short, due to various translator behaviors, when `rhs` here is Code[],
- // it's possible it was originally written in the CQL as a Code, a List, or a ValueSet.
- // We can't distinguish, so we have to allow all of them.
- // Then, again because of translator behaviors, x ~ ValueSet could reach this point
- // with `rhs` either being a Code[] or a ValueSet object.
- // Because we can't filter it out in the Code[] path, we should allow it in the ValueSet path as well
- // to reduce unexpected inconsistencies.
- // See full description and discussion at https://github.com/cqframework/cql-execution/pull/370
- return rhs.hasMatch(lhs);
- }
- else if (Array.isArray(rhs)) {
- // As noted above, there's no way to tell if the original CQL referred to a single code or to a list.
- // So, we treat the operators ~ and = to mean
- // "some match exists between the LHS and RHS, with the appropriate operator"
- // instead of the usual meaning
- // "the LHS and RHS themselves are a match, with the appropriate operator"
- return rhs.some(c => c.hasMatch(lhs));
- }
- else {
- // Unexpected, but just in case a single code came through
- return rhs.hasMatch(lhs);
- }
- }
- equal(lhs, rhs) {
- if (rhs instanceof clinical_1.CodeSystem) {
- throw new Error("Operator '=' is not defined for Code = CodeSystem");
- }
- let rhsCodes;
- if (rhs instanceof clinical_1.ValueSet) {
- rhsCodes = rhs.expand();
- }
- else if (Array.isArray(rhs)) {
- rhsCodes = rhs;
- }
- else {
- // unexpected, but just in case a single code came through
- rhsCodes = [rhs];
- }
- return rhsCodes.some(c => lhs.some(v => (0, comparison_1.equals)(c, v)));
- }
-}
-exports.Retrieve = Retrieve;
-
-},{"../datatypes/clinical":6,"../util/comparison":53,"../util/util":60,"./builder":17,"./expression":23}],26:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Instance = void 0;
-const expression_1 = require("./expression");
-const quantity_1 = require("../datatypes/quantity");
-const datatypes_1 = require("../datatypes/datatypes");
-const builder_1 = require("./builder");
-const elmTypes_1 = require("../util/elmTypes");
-class Element {
- constructor(json) {
- this.name = json.name;
- this.value = (0, builder_1.build)(json.value);
- }
- async exec(ctx) {
- return this.value != null ? this.value.execute(ctx) : undefined;
- }
-}
-class Instance extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.classType = json.classType;
- this.element = json.element.map((child) => new Element(child));
- }
- async exec(ctx) {
- const obj = {};
- for (const el of this.element) {
- obj[el.name] = await el.exec(ctx);
- }
- switch (this.classType) {
- case elmTypes_1.ELM_QUANTITY_TYPE:
- return new quantity_1.Quantity(obj.value, obj.unit);
- case '{urn:hl7-org:elm-types:r1}Code':
- return new datatypes_1.Code(obj.code, obj.system, obj.version, obj.display);
- case elmTypes_1.ELM_CONCEPT_TYPE:
- return new datatypes_1.Concept(obj.codes, obj.display);
- default:
- return obj;
- }
- }
-}
-exports.Instance = Instance;
-
-},{"../datatypes/datatypes":7,"../datatypes/quantity":12,"../util/elmTypes":55,"./builder":17,"./expression":23}],27:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Collapse = exports.Expand = exports.Ends = exports.Starts = exports.End = exports.Start = exports.Size = exports.Width = exports.PointFrom = exports.OverlapsBefore = exports.OverlapsAfter = exports.Overlaps = exports.MeetsBefore = exports.MeetsAfter = exports.Meets = exports.Interval = void 0;
-exports.doContains = doContains;
-exports.doProperContains = doProperContains;
-exports.doIncludes = doIncludes;
-exports.doProperIncludes = doProperIncludes;
-exports.doAfter = doAfter;
-exports.doBefore = doBefore;
-exports.doUnion = doUnion;
-exports.doExcept = doExcept;
-exports.doIntersect = doIntersect;
-const expression_1 = require("./expression");
-const datetime_1 = require("../datatypes/datetime");
-const quantity_1 = require("../datatypes/quantity");
-const math_1 = require("../util/math");
-const units_1 = require("../util/units");
-const dtivl = __importStar(require("../datatypes/interval"));
-const builder_1 = require("./builder");
-const elmTypes_1 = require("../util/elmTypes");
-class Interval extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.lowClosed = json.lowClosed;
- this.lowClosedExpression = (0, builder_1.build)(json.lowClosedExpression);
- this.highClosed = json.highClosed;
- this.highClosedExpression = (0, builder_1.build)(json.highClosedExpression);
- this.low = (0, builder_1.build)(json.low);
- this.high = (0, builder_1.build)(json.high);
- this.pointType = this.resultTypeSpecifier?.pointType?.name;
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isInterval() {
- return true;
- }
- async exec(ctx) {
- const lowValue = await this.low.execute(ctx);
- const highValue = await this.high.execute(ctx);
- const lowClosed = this.lowClosed != null
- ? this.lowClosed
- : this.lowClosedExpression && (await this.lowClosedExpression.execute(ctx));
- const highClosed = this.highClosed != null
- ? this.highClosed
- : this.highClosedExpression && (await this.highClosedExpression.execute(ctx));
- let effectivePointType = this.pointType;
- if (effectivePointType == null || effectivePointType === elmTypes_1.ELM_ANY_TYPE) {
- // try to get the point type from a cast
- if (this.low.asTypeSpecifier && this.low.asTypeSpecifier.type === elmTypes_1.ELM_NAMED_TYPE_SPECIFIER) {
- effectivePointType = this.low.asTypeSpecifier.name;
- }
- else if (this.high.asTypeSpecifier &&
- this.high.asTypeSpecifier.type === elmTypes_1.ELM_NAMED_TYPE_SPECIFIER) {
- effectivePointType = this.high.asTypeSpecifier.name;
- }
- }
- return new dtivl.Interval(lowValue, highValue, lowClosed, highClosed, effectivePointType);
- }
-}
-exports.Interval = Interval;
-// Equal is completely handled by overloaded#Equal
-// NotEqual is completely handled by overloaded#Equal
-// Delegated to by overloaded#Contains and overloaded#In
-function doContains(interval, item, precision) {
- return interval.contains(item, precision);
-}
-// Delegated to by overloaded#ProperContains and overloaded#ProperIn
-function doProperContains(interval, item, precision) {
- return interval.properContains(item, precision);
-}
-// Delegated to by overloaded#Includes and overloaded#IncludedIn
-function doIncludes(interval, subinterval, precision) {
- return interval.includes(subinterval, precision);
-}
-// Delegated to by overloaded#ProperIncludes and overloaded@ProperIncludedIn
-function doProperIncludes(interval, subinterval, precision) {
- return interval.properlyIncludes(subinterval, precision);
-}
-// Delegated to by overloaded#After
-function doAfter(a, b, precision) {
- return a.after(b, precision);
-}
-// Delegated to by overloaded#Before
-function doBefore(a, b, precision) {
- return a.before(b, precision);
-}
-class Meets extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.meets(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.Meets = Meets;
-class MeetsAfter extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.meetsAfter(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.MeetsAfter = MeetsAfter;
-class MeetsBefore extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.meetsBefore(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.MeetsBefore = MeetsBefore;
-class Overlaps extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.overlaps(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.Overlaps = Overlaps;
-class OverlapsAfter extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.overlapsAfter(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.OverlapsAfter = OverlapsAfter;
-class OverlapsBefore extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.overlapsBefore(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.OverlapsBefore = OverlapsBefore;
-class PointFrom extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const interval = await this.arg?.execute(ctx);
- if (interval == null) {
- return null;
- }
- return interval.pointFrom();
- }
-}
-exports.PointFrom = PointFrom;
-// Delegated to by overloaded#Union
-function doUnion(a, b) {
- return a.union(b);
-}
-// Delegated to by overloaded#Except
-function doExcept(a, b) {
- if (a != null && b != null) {
- return a.except(b);
- }
- else {
- return null;
- }
-}
-// Delegated to by overloaded#Intersect
-function doIntersect(a, b) {
- if (a != null && b != null) {
- return a.intersect(b);
- }
- else {
- return null;
- }
-}
-class Width extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const interval = await this.arg?.execute(ctx);
- if (interval == null) {
- return null;
- }
- return interval.width();
- }
-}
-exports.Width = Width;
-class Size extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const interval = await this.arg?.execute(ctx);
- if (interval == null) {
- return null;
- }
- return interval.size();
- }
-}
-exports.Size = Size;
-class Start extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const interval = await this.arg?.execute(ctx);
- if (interval == null) {
- return null;
- }
- const start = interval.start();
- // fix the timezoneOffset of minimum Datetime to match context offset
- if (start && start.isDateTime && start.equals(datetime_1.MIN_DATETIME_VALUE)) {
- start.timezoneOffset = ctx.getTimezoneOffset();
- }
- return start;
- }
-}
-exports.Start = Start;
-class End extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const interval = await this.arg?.execute(ctx);
- if (interval == null) {
- return null;
- }
- const end = interval.end();
- // fix the timezoneOffset of maximum Datetime to match context offset
- if (end && end.isDateTime && end.equals(datetime_1.MAX_DATETIME_VALUE)) {
- end.timezoneOffset = ctx.getTimezoneOffset();
- }
- return end;
- }
-}
-exports.End = End;
-class Starts extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.starts(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.Starts = Starts;
-class Ends extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.ends(b, this.precision);
- }
- else {
- return null;
- }
- }
-}
-exports.Ends = Ends;
-function intervalListType(intervals) {
- // Returns one of null, 'time', 'date', 'datetime', 'quantity', 'long', 'integer', 'decimal' or 'mismatch'
- let type = null;
- for (const itvl of intervals) {
- if (itvl == null) {
- continue;
- }
- if (itvl.low == null && itvl.high == null) {
- //can't really determine type from this
- continue;
- }
- // if one end is null (but not both), the type can be determined from the other end
- const low = itvl.low != null ? itvl.low : itvl.high;
- const high = itvl.high != null ? itvl.high : itvl.low;
- if (low.isTime && low.isTime() && high.isTime && high.isTime()) {
- if (type == null) {
- type = 'time';
- }
- else if (type === 'time') {
- continue;
- }
- else {
- return 'mismatch';
- }
- // if an interval mixes date and datetime, type is datetime (for implicit conversion)
- }
- else if ((low.isDateTime || high.isDateTime) &&
- (low.isDateTime || low.isDate) &&
- (high.isDateTime || high.isDate)) {
- if (type == null || type === 'date') {
- type = 'datetime';
- }
- else if (type === 'datetime') {
- continue;
- }
- else {
- return 'mismatch';
- }
- }
- else if (low.isDate && high.isDate) {
- if (type == null) {
- type = 'date';
- }
- else if (type === 'date' || type === 'datetime') {
- continue;
- }
- else {
- return 'mismatch';
- }
- }
- else if (low.isQuantity && high.isQuantity) {
- if (type == null) {
- type = 'quantity';
- }
- else if (type === 'quantity') {
- continue;
- }
- else {
- return 'mismatch';
- }
- }
- else if (typeof low === 'bigint' && typeof high === 'bigint') {
- if (type == null) {
- type = 'long';
- }
- else if (type === 'long') {
- continue;
- }
- else {
- return 'mismatch';
- }
- }
- else if (Number.isInteger(low) && Number.isInteger(high)) {
- if (type == null) {
- type = 'integer';
- }
- else if (type === 'integer' || type === 'decimal') {
- continue;
- }
- else {
- return 'mismatch';
- }
- }
- else if (typeof low === 'number' && typeof high === 'number') {
- if (type == null || type === 'integer') {
- type = 'decimal';
- }
- else if (type === 'decimal') {
- continue;
- }
- else {
- return 'mismatch';
- }
- //if we are here ends are mismatched
- }
- else {
- return 'mismatch';
- }
- }
- return type;
-}
-// TODO: Move and refactor Expand implementaton into src/datatypes/interval.ts
-class Expand extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- // expand(argument List>, per Quantity) List>
- let defaultPer, expandFunction;
- let [intervals, per] = await this.execArgs(ctx);
- if (per?.value === 0) {
- // a per of 0 is basically like a divide-by-zero; since spec says divide-by-zero returns null, we'll return null here too
- return null;
- }
- // CQL 1.5 introduced an overload to allow singular intervals; make it a list so we can use the same logic for either overload
- if (!Array.isArray(intervals)) {
- intervals = [intervals];
- }
- const type = intervalListType(intervals);
- if (type === 'mismatch') {
- throw new Error('List of intervals contains mismatched types.');
- }
- if (type == null) {
- return null;
- }
- // this step collapses overlaps, and also returns a clone of intervals so we can feel free to mutate
- intervals = collapseIntervals(intervals, per);
- if (intervals.length === 0) {
- return [];
- }
- if (['time', 'date', 'datetime'].includes(type)) {
- expandFunction = this.expandDTishInterval;
- defaultPer = (interval) => new quantity_1.Quantity(1, interval.low.getPrecision());
- }
- else if (['quantity'].includes(type)) {
- expandFunction = this.expandQuantityInterval;
- defaultPer = (interval) => new quantity_1.Quantity(1, interval.low.unit);
- }
- else if (['long', 'integer', 'decimal'].includes(type)) {
- expandFunction = this.expandNumericInterval;
- defaultPer = (_interval) => new quantity_1.Quantity(1, '1');
- }
- else {
- throw new Error('Interval list type not yet supported.');
- }
- const results = [];
- for (const interval of intervals) {
- if (interval == null) {
- continue;
- }
- // We do not support open ended intervals since result would likely be too long
- if (interval.low == null || interval.high == null) {
- return null;
- }
- if (type === 'datetime') {
- //support for implicitly converting dates to datetime
- interval.low = interval.low.getDateTime();
- interval.high = interval.high.getDateTime();
- }
- per = per != null ? per : defaultPer(interval);
- const items = expandFunction.call(this, interval, per);
- if (items === null) {
- return null;
- }
- results.push(...(items || []));
- }
- return results;
- }
- expandDTishInterval(interval, per) {
- per.unit = (0, units_1.convertToCQLDateUnit)(per.unit);
- if (per.unit === 'week') {
- per.value *= 7;
- per.unit = 'day';
- }
- // Precision Checks
- // return null if precision not applicable (e.g. gram, or minutes for dates)
- if (!interval.low.constructor.FIELDS.includes(per.unit)) {
- return null;
- }
- // open interval with null boundaries do not contribute to output
- // closed interval with null boundaries are not allowed for performance reasons
- if (interval.low == null || interval.high == null) {
- return null;
- }
- let low = interval.lowClosed ? interval.low : interval.low.successor();
- let high = interval.highClosed ? interval.high : interval.high.predecessor();
- if (low.after(high)) {
- return [];
- }
- if (interval.low.isLessPrecise(per.unit) || interval.high.isLessPrecise(per.unit)) {
- return [];
- }
- let current_low = low;
- const results = [];
- low = this.truncateToPrecision(low, per.unit);
- high = this.truncateToPrecision(high, per.unit);
- let current_high = current_low.add(per.value, per.unit).predecessor();
- let intervalToAdd = new dtivl.Interval(current_low, current_high, true, true, interval.pointType);
- while (intervalToAdd.high.sameOrBefore(high)) {
- results.push(intervalToAdd);
- current_low = current_low.add(per.value, per.unit);
- current_high = current_low.add(per.value, per.unit).predecessor();
- intervalToAdd = new dtivl.Interval(current_low, current_high, true, true, interval.pointType);
- }
- return results;
- }
- truncateToPrecision(value, unit) {
- // If interval boundaries are more precise than per quantity, truncate to
- // the precision specified by the per
- let shouldTruncate = false;
- for (const field of value.constructor.FIELDS) {
- if (shouldTruncate) {
- value[field] = null;
- }
- if (field === unit) {
- // Start truncating after this unit
- shouldTruncate = true;
- }
- }
- return value;
- }
- expandQuantityInterval(interval, per) {
- // we want to convert everything to the more precise of the interval.low or per
- let result_units;
- const res = (0, units_1.compareUnits)(interval.low.unit, per.unit);
- if (res != null && res > 0) {
- //interval.low.unit is 'bigger' aka les precise
- result_units = per.unit;
- }
- else {
- result_units = interval.low.unit;
- }
- const low_value = (0, units_1.convertUnit)(interval.low.value, interval.low.unit, result_units);
- const high_value = (0, units_1.convertUnit)(interval.high.value, interval.high.unit, result_units);
- const per_value = (0, units_1.convertUnit)(per.value, per.unit, result_units);
- // return null if unit conversion failed, must have mismatched units
- if (!(low_value != null && high_value != null && per_value != null)) {
- return null;
- }
- const results = this.makeNumericIntervalList(low_value, high_value, interval.lowClosed, interval.highClosed, per_value);
- for (const itvl of results) {
- itvl.low = new quantity_1.Quantity(itvl.low, result_units);
- itvl.high = new quantity_1.Quantity(itvl.high, result_units);
- }
- return results;
- }
- expandNumericInterval(interval, per) {
- if (per.unit !== '1' && per.unit !== '') {
- return null;
- }
- return this.makeNumericIntervalList(interval.low, interval.high, interval.lowClosed, interval.highClosed, per.value);
- }
- makeNumericIntervalList(low, high, lowClosed, highClosed, perValue) {
- // If the per value is a Decimal (has a .), 8 decimal places are appropriate
- // Integers should have 0 Decimal places
- const perIsDecimal = perValue.toString().includes('.');
- const decimalPrecision = perIsDecimal ? 8 : 0;
- const hasLongBoundaries = typeof low === 'bigint' || typeof high === 'bigint';
- low = lowClosed ? low : (0, math_1.successor)(low);
- high = highClosed ? high : (0, math_1.predecessor)(high);
- if (hasLongBoundaries && !perIsDecimal) {
- const longLow = low;
- const longHigh = high;
- if (longLow > longHigh) {
- return [];
- }
- if (longLow == null || longHigh == null) {
- return [];
- }
- const perBigInt = BigInt(perValue);
- if (perBigInt > longHigh - longLow + 1n) {
- return [];
- }
- let current_low = longLow;
- let current_high = current_low + perBigInt - 1n;
- const results = [];
- while (current_high <= longHigh) {
- results.push(new dtivl.Interval(current_low, current_high, true, true));
- current_low += perBigInt;
- current_high = current_low + perBigInt - 1n;
- }
- return results;
- }
- else if (hasLongBoundaries) {
- low = Number(low);
- high = Number(high);
- }
- // If the interval boundaries are more precise than the per quantity, the
- // more precise values will be truncated to the precision specified by the
- // per quantity.
- low = truncateDecimal(low, decimalPrecision);
- high = truncateDecimal(high, decimalPrecision);
- if (low > high) {
- return [];
- }
- if (low == null || high == null) {
- return [];
- }
- const perUnitSize = perIsDecimal ? 0.00000001 : 1;
- if (low === high &&
- Number.isInteger(low) &&
- Number.isInteger(high) &&
- !Number.isInteger(perValue)) {
- high = parseFloat((high + 1).toFixed(decimalPrecision));
- }
- let current_low = low;
- const results = [];
- if (perValue > high - low + perUnitSize) {
- return [];
- }
- let current_high = parseFloat((current_low + perValue - perUnitSize).toFixed(decimalPrecision));
- let intervalToAdd = new dtivl.Interval(current_low, current_high, true, true);
- while (intervalToAdd.high <= high) {
- results.push(intervalToAdd);
- current_low = parseFloat((current_low + perValue).toFixed(decimalPrecision));
- current_high = parseFloat((current_low + perValue - perUnitSize).toFixed(decimalPrecision));
- intervalToAdd = new dtivl.Interval(current_low, current_high, true, true);
- }
- return results;
- }
-}
-exports.Expand = Expand;
-// TODO: Move and refactor Collapse implementaton into src/datatypes/interval.ts
-class Collapse extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- // collapse(argument List>, per Quantity) List>
- const [intervals, perWidth] = await this.execArgs(ctx);
- return collapseIntervals(intervals, perWidth);
- }
-}
-exports.Collapse = Collapse;
-function collapseIntervals(intervals, perWidth) {
- // Clone intervals so this function remains idempotent
- const intervalsClone = [];
- // If the list is null, return null
- if (intervals == null) {
- return null;
- }
- for (const interval of intervals) {
- // The spec says to ignore null intervals
- if (interval != null) {
- intervalsClone.push(interval.copy());
- }
- }
- if (intervalsClone.length <= 1) {
- return intervalsClone;
- }
- else {
- // If the per argument is null, the default unit interval for the point type
- // of the intervals involved will be used (i.e. the interval that has a
- // width equal to the result of the successor function for the point type).
- if (perWidth == null) {
- const pointSize = intervalsClone[0].getPointSize();
- perWidth = pointSize.isQuantity ? pointSize : new quantity_1.Quantity(Number(pointSize), '1');
- }
- // sort intervalsClone by start
- intervalsClone.sort(function (a, b) {
- if (a.low && typeof a.low.before === 'function') {
- if (b.low != null && a.low.before(b.low)) {
- return -1;
- }
- if (b.low == null || a.low.after(b.low)) {
- return 1;
- }
- }
- else if (a.low != null && b.low != null) {
- if (a.low < b.low) {
- return -1;
- }
- if (a.low > b.low) {
- return 1;
- }
- }
- else if (a.low != null && b.low == null) {
- return 1;
- }
- else if (a.low == null && b.low != null) {
- return -1;
- }
- // if both lows are undefined, sort by high
- if (a.high && typeof a.high.before === 'function') {
- if (b.high == null || a.high.before(b.high)) {
- return -1;
- }
- if (a.high.after(b.high)) {
- return 1;
- }
- }
- else if (a.high != null && b.high != null) {
- if (a.high < b.high) {
- return -1;
- }
- if (a.high > b.high) {
- return 1;
- }
- }
- else if (a.high != null && b.high == null) {
- return -1;
- }
- else if (a.high == null && b.high != null) {
- return 1;
- }
- return 0;
- });
- // collapse intervals as necessary
- const collapsedIntervals = [];
- let a = intervalsClone.shift();
- let b = intervalsClone.shift();
- while (b) {
- if (b.low && typeof b.low.durationBetween === 'function') {
- // handle DateTimes using durationBetween
- if (a.high != null ? a.high.sameOrAfter(b.low) : undefined) {
- // overlap
- if (b.high == null || b.high.after(a.high)) {
- a.high = b.high;
- }
- }
- else if ((a.high != null ? a.high.durationBetween(b.low, perWidth.unit).high : undefined) <=
- perWidth.value) {
- a.high = b.high;
- }
- else {
- collapsedIntervals.push(a);
- a = b;
- }
- }
- else if (b.low && typeof b.low.sameOrBefore === 'function') {
- if (a.high != null && b.low.sameOrBefore((0, math_1.add)(a.high, perWidth))) {
- if (b.high == null || b.high.after(a.high)) {
- a.high = b.high;
- }
- }
- else {
- collapsedIntervals.push(a);
- a = b;
- }
- }
- else {
- const distance = b.low - a.high;
- const comparablePerWidth = typeof distance === 'bigint' && Number.isInteger(perWidth.value)
- ? BigInt(perWidth.value)
- : perWidth.value;
- const withinPerWidth = typeof distance === 'bigint' && typeof comparablePerWidth !== 'bigint'
- ? Number(distance) <= comparablePerWidth
- : distance <= comparablePerWidth;
- if (withinPerWidth) {
- if (b.high > a.high || b.high == null) {
- a.high = b.high;
- }
- }
- else {
- collapsedIntervals.push(a);
- a = b;
- }
- }
- b = intervalsClone.shift();
- }
- collapsedIntervals.push(a);
- return collapsedIntervals;
- }
-}
-function truncateDecimal(decimal, decimalPlaces) {
- // like parseFloat().toFixed() but floor rather than round
- // Needed for when per precision is less than the interval input precision
- const re = new RegExp('^-?\\d+(?:.\\d{0,' + (decimalPlaces || -1) + '})?');
- return parseFloat(decimal.toString().match(re)[0]);
-}
-
-},{"../datatypes/datetime":8,"../datatypes/interval":10,"../datatypes/quantity":12,"../util/elmTypes":55,"../util/math":58,"../util/units":59,"./builder":17,"./expression":23}],28:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Library = void 0;
-const expressions_1 = require("./expressions");
-class Library {
- constructor(json, libraryManager) {
- this.source = json;
- // identifier
- this.name = json.library.identifier?.id;
- this.version = json.library.identifier?.version;
- // usings
- const usingDefs = (json.library.usings && json.library.usings.def) || [];
- this.usings = usingDefs
- .filter((u) => u.localIdentifier !== 'System')
- .map((u) => {
- return { name: u.localIdentifier, version: u.version };
- });
- // parameters
- const paramDefs = (json.library.parameters && json.library.parameters.def) || [];
- this.parameters = {};
- for (const param of paramDefs) {
- this.parameters[param.name] = new expressions_1.ParameterDef(param);
- }
- // code systems
- const csDefs = (json.library.codeSystems && json.library.codeSystems.def) || [];
- this.codesystems = {};
- for (const codesystem of csDefs) {
- this.codesystems[codesystem.name] = new expressions_1.CodeSystemDef(codesystem);
- }
- // value sets
- const vsDefs = (json.library.valueSets && json.library.valueSets.def) || [];
- this.valuesets = {};
- for (const valueset of vsDefs) {
- this.valuesets[valueset.name] = new expressions_1.ValueSetDef(valueset);
- }
- // codes
- const codeDefs = (json.library.codes && json.library.codes.def) || [];
- this.codes = {};
- for (const code of codeDefs) {
- this.codes[code.name] = new expressions_1.CodeDef(code);
- }
- // concepts
- const conceptDefs = (json.library.concepts && json.library.concepts.def) || [];
- this.concepts = {};
- for (const concept of conceptDefs) {
- this.concepts[concept.name] = new expressions_1.ConceptDef(concept);
- }
- // expressions
- const exprDefs = (json.library.statements && json.library.statements.def) || [];
- this.expressions = {};
- this.functions = {};
- for (const expr of exprDefs) {
- if (expr.type === 'FunctionDef') {
- if (!this.functions[expr.name]) {
- this.functions[expr.name] = [];
- }
- this.functions[expr.name].push(new expressions_1.FunctionDef(expr));
- }
- else {
- this.expressions[expr.name] = new expressions_1.ExpressionDef(expr);
- }
- }
- // includes
- const inclDefs = (json.library.includes && json.library.includes.def) || [];
- this.includes = {};
- for (const incl of inclDefs) {
- if (libraryManager) {
- this.includes[incl.localIdentifier] = libraryManager.resolve(incl.path, incl.version);
- }
- }
- }
- getFunction(identifier) {
- return this.functions[identifier];
- }
- get(identifier) {
- return (this.expressions[identifier] || this.includes[identifier] || this.getFunction(identifier));
- }
- getValueSet(identifier, libraryName) {
- if (libraryName && this.includes[libraryName]) {
- return this.includes[libraryName].valuesets[identifier];
- }
- else if (libraryName == null || libraryName === this.name) {
- return this.valuesets[identifier];
- }
- }
- getCodeSystem(identifier, libraryName) {
- if (libraryName && this.includes[libraryName]) {
- return this.includes[libraryName].codesystems[identifier];
- }
- else if (libraryName == null || libraryName === this.name) {
- return this.codesystems[identifier];
- }
- }
- getCode(identifier) {
- return this.codes[identifier];
- }
- getConcept(identifier) {
- return this.concepts[identifier];
- }
- getParameter(name) {
- return this.parameters[name];
- }
-}
-exports.Library = Library;
-
-},{"./expressions":24}],29:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Slice = exports.Last = exports.First = exports.Current = exports.toDistinctList = exports.Distinct = exports.Flatten = exports.ForEach = exports.IndexOf = exports.ToList = exports.SingletonFrom = exports.Filter = exports.Times = exports.Exists = exports.List = void 0;
-exports.doUnion = doUnion;
-exports.doExcept = doExcept;
-exports.doIntersect = doIntersect;
-exports.doContains = doContains;
-exports.doProperContains = doProperContains;
-exports.doIncludes = doIncludes;
-exports.doProperIncludes = doProperIncludes;
-const immutable_1 = require("immutable");
-const comparison_1 = require("../util/comparison");
-const immutableUtil_1 = require("../util/immutableUtil");
-const util_1 = require("../util/util");
-const builder_1 = require("./builder");
-const expression_1 = require("./expression");
-class List extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.elements = (0, builder_1.build)(json.element) || [];
- }
- get isList() {
- return true;
- }
- async exec(ctx) {
- return await Promise.all(this.elements.map(item => item.execute(ctx)));
- }
-}
-exports.List = List;
-class Exists extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const list = await this.execArgs(ctx);
- // if list exists and has non empty length we need to make sure it isnt just full of nulls
- if (list) {
- return list.some((item) => item != null);
- }
- return false;
- }
-}
-exports.Exists = Exists;
-// Equal is completely handled by overloaded#Equal
-// NotEqual is completely handled by overloaded#Equal
-// Delegated to by overloaded#Union
-function doUnion(a, b) {
- const distinct = (0, exports.toDistinctList)(a.concat(b));
- return removeDuplicateNulls(distinct);
-}
-// Delegated to by overloaded#Except
-function doExcept(a, b) {
- const distinct = (0, exports.toDistinctList)(a);
- const setList = removeDuplicateNulls(distinct);
- return setList.filter(item => !doContains(b, item));
-}
-// Delegated to by overloaded#Intersect
-function doIntersect(a, b) {
- const distinct = (0, exports.toDistinctList)(a);
- const setList = removeDuplicateNulls(distinct);
- return setList.filter(item => doContains(b, item));
-}
-// ELM-only, not a product of CQL
-class Times extends expression_1.UnimplementedExpression {
-}
-exports.Times = Times;
-// ELM-only, not a product of CQL
-class Filter extends expression_1.UnimplementedExpression {
-}
-exports.Filter = Filter;
-class SingletonFrom extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null && arg.length > 1) {
- throw new Error("IllegalArgument: 'SingletonFrom' requires a 0 or 1 arg array");
- }
- else if (arg != null && arg.length === 1) {
- return arg[0];
- }
- else {
- return null;
- }
- }
-}
-exports.SingletonFrom = SingletonFrom;
-class ToList extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return [arg];
- }
- else {
- return [];
- }
- }
-}
-exports.ToList = ToList;
-class IndexOf extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- this.element = (0, builder_1.build)(json.element);
- }
- async exec(ctx) {
- let index;
- const src = await this.source.execute(ctx);
- const el = await this.element.execute(ctx);
- if (src == null || el == null) {
- return null;
- }
- for (let i = 0; i < src.length; i++) {
- const itm = src[i];
- if ((0, comparison_1.equals)(itm, el)) {
- index = i;
- break;
- }
- }
- if (index != null) {
- return index;
- }
- else {
- return -1;
- }
- }
-}
-exports.IndexOf = IndexOf;
-// Indexer is completely handled by overloaded#Indexer
-// Delegated to by overloaded#Contains and overloaded#In
-function doContains(container, item) {
- return container.some((element) => (0, comparison_1.equals)(element, item) || (element == null && item == null));
-}
-// Delegated to by overloaded#ProperContains and overloaded#ProperIn
-function doProperContains(container, item) {
- // The "proper" membership operators have list semantics, not set semantics.
- // The intent here is that given list semantics and a `distinct` operator,
- // one can achieve set semantics, but the reverse isn't possible.
- // These proper membership operators can then be described as
- // the regular membership operators, plus the list is strictly larger.
- return container.length > 1 && doContains(container, item);
-}
-// Delegated to by overloaded#Includes and overloaded@IncludedIn
-function doIncludes(list, sublist) {
- if (list == null || sublist == null) {
- return null;
- }
- return sublist.every((x) => doContains(list, x));
-}
-// Delegated to by overloaded#ProperIncludes and overloaded@ProperIncludedIn
-function doProperIncludes(list, sublist) {
- return list.length > sublist.length && doIncludes(list, sublist);
-}
-// ELM-only, not a product of CQL
-class ForEach extends expression_1.UnimplementedExpression {
-}
-exports.ForEach = ForEach;
-class Flatten extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if ((0, util_1.typeIsArray)(arg) && arg.every(x => (0, util_1.typeIsArray)(x))) {
- return arg.reduce((x, y) => x.concat(y), []);
- }
- else {
- return arg;
- }
- }
-}
-exports.Flatten = Flatten;
-class Distinct extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const result = await this.execArgs(ctx);
- if (result == null) {
- return null;
- }
- return (0, exports.toDistinctList)(result);
- }
-}
-exports.Distinct = Distinct;
-const toDistinctList = (list) => {
- const list_keys = list.map(immutableUtil_1.toNormalizedKey);
- const set = (0, immutable_1.Set)().asMutable();
- const distinct = [];
- set.withMutations(y => {
- list_keys.forEach((key, i) => {
- // Check set size
- const setSize = y.count();
- // Attempt to insert
- y.add(key);
- // If inserted, then size will increase; push to distinct
- if (y.count() > setSize) {
- distinct.push(list[i]);
- }
- });
- });
- return distinct;
-};
-exports.toDistinctList = toDistinctList;
-function removeDuplicateNulls(list) {
- // Remove duplicate null elements
- let firstNullFound = false;
- const setList = [];
- for (const item of list) {
- if (item !== null) {
- setList.push(item);
- }
- else if (item === null && !firstNullFound) {
- setList.push(item);
- firstNullFound = true;
- }
- }
- return setList;
-}
-// ELM-only, not a product of CQL
-class Current extends expression_1.UnimplementedExpression {
-}
-exports.Current = Current;
-class First extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- }
- async exec(ctx) {
- const src = await this.source.execute(ctx);
- if (src != null && (0, util_1.typeIsArray)(src) && src.length > 0) {
- return src[0];
- }
- else {
- return null;
- }
- }
-}
-exports.First = First;
-class Last extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- }
- async exec(ctx) {
- const src = await this.source.execute(ctx);
- if (src != null && (0, util_1.typeIsArray)(src) && src.length > 0) {
- return src[src.length - 1];
- }
- else {
- return null;
- }
- }
-}
-exports.Last = Last;
-class Slice extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- this.startIndex = (0, builder_1.build)(json.startIndex);
- this.endIndex = (0, builder_1.build)(json.endIndex);
- }
- async exec(ctx) {
- const src = await this.source.execute(ctx);
- if (src != null && (0, util_1.typeIsArray)(src)) {
- const startIndex = await this.startIndex.execute(ctx);
- const endIndex = await this.endIndex.execute(ctx);
- const start = startIndex != null ? startIndex : 0;
- const end = endIndex != null ? endIndex : src.length;
- if (src.length === 0 || start < 0 || end < 0 || end < start) {
- return [];
- }
- return src.slice(start, end);
- }
- return null;
- }
-}
-exports.Slice = Slice;
-// Length is completely handled by overloaded#Length
-
-},{"../util/comparison":53,"../util/immutableUtil":56,"../util/util":60,"./builder":17,"./expression":23,"immutable":75}],30:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.StringLiteral = exports.DecimalLiteral = exports.LongLiteral = exports.IntegerLiteral = exports.BooleanLiteral = exports.Literal = void 0;
-const elmTypes_1 = require("../util/elmTypes");
-const expression_1 = require("./expression");
-class Literal extends expression_1.Expression {
- static from(json) {
- switch (json.valueType) {
- case elmTypes_1.ELM_BOOLEAN_TYPE:
- return new BooleanLiteral(json);
- case elmTypes_1.ELM_INTEGER_TYPE:
- return new IntegerLiteral(json);
- case elmTypes_1.ELM_LONG_TYPE:
- return new LongLiteral(json);
- case elmTypes_1.ELM_DECIMAL_TYPE:
- return new DecimalLiteral(json);
- case elmTypes_1.ELM_STRING_TYPE:
- return new StringLiteral(json);
- default:
- return new Literal(json);
- }
- }
- constructor(json) {
- super(json);
- this.valueType = json.valueType;
- this.value = json.value;
- }
- async exec(_ctx) {
- return this.value;
- }
-}
-exports.Literal = Literal;
-// The following are not defined in ELM, but helpful for execution
-class BooleanLiteral extends Literal {
- constructor(json) {
- super(json);
- this.value = this.value === 'true';
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isBooleanLiteral() {
- return true;
- }
- async exec(_ctx) {
- return this.value;
- }
-}
-exports.BooleanLiteral = BooleanLiteral;
-class IntegerLiteral extends Literal {
- constructor(json) {
- super(json);
- this.value = parseInt(this.value, 10);
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isIntegerLiteral() {
- return true;
- }
- async exec(_ctx) {
- return this.value;
- }
-}
-exports.IntegerLiteral = IntegerLiteral;
-class LongLiteral extends Literal {
- constructor(json) {
- super(json);
- this.value = BigInt(this.value);
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isLongLiteral() {
- return true;
- }
- async exec(_ctx) {
- return this.value;
- }
-}
-exports.LongLiteral = LongLiteral;
-class DecimalLiteral extends Literal {
- constructor(json) {
- super(json);
- this.value = parseFloat(this.value);
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isDecimalLiteral() {
- return true;
- }
- async exec(_ctx) {
- return this.value;
- }
-}
-exports.DecimalLiteral = DecimalLiteral;
-class StringLiteral extends Literal {
- constructor(json) {
- super(json);
- }
- // Define a simple getter to allow type-checking of this class without instanceof
- // and in a way that survives minification (as opposed to checking constructor.name)
- get isStringLiteral() {
- return true;
- }
- async exec(_ctx) {
- // TODO: Remove these replacements when CQL-to-ELM fixes bug: https://github.com/cqframework/clinical_quality_language/issues/82
- return this.value.replace(/\\'/g, "'").replace(/\\"/g, '"');
- }
-}
-exports.StringLiteral = StringLiteral;
-
-},{"../util/elmTypes":55,"./expression":23}],31:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.IsFalse = exports.IsTrue = exports.Xor = exports.Not = exports.Or = exports.Implies = exports.And = void 0;
-const expression_1 = require("./expression");
-const datatypes_1 = require("../datatypes/datatypes");
-class And extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return datatypes_1.ThreeValuedLogic.and(...(await this.execArgs(ctx)));
- }
-}
-exports.And = And;
-class Implies extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [left, right] = await this.execArgs(ctx);
- return datatypes_1.ThreeValuedLogic.implies(left, right);
- }
-}
-exports.Implies = Implies;
-class Or extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return datatypes_1.ThreeValuedLogic.or(...(await this.execArgs(ctx)));
- }
-}
-exports.Or = Or;
-class Not extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return datatypes_1.ThreeValuedLogic.not(await this.execArgs(ctx));
- }
-}
-exports.Not = Not;
-class Xor extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return datatypes_1.ThreeValuedLogic.xor(...(await this.execArgs(ctx)));
- }
-}
-exports.Xor = Xor;
-class IsTrue extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return true === (await this.execArgs(ctx));
- }
-}
-exports.IsTrue = IsTrue;
-class IsFalse extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return false === (await this.execArgs(ctx));
- }
-}
-exports.IsFalse = IsFalse;
-
-},{"../datatypes/datatypes":7,"./expression":23}],32:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Message = void 0;
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-class Message extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- this.condition = (0, builder_1.build)(json.condition);
- this.code = (0, builder_1.build)(json.code);
- this.severity = (0, builder_1.build)(json.severity);
- this.message = (0, builder_1.build)(json.message);
- }
- async exec(ctx) {
- const source = await this.source.execute(ctx);
- const condition = await this.condition.execute(ctx);
- if (condition) {
- const code = await this.code.execute(ctx);
- const severity = await this.severity.execute(ctx);
- const message = await this.message.execute(ctx);
- const listener = ctx.getMessageListener();
- if (listener && typeof listener.onMessage === 'function') {
- listener.onMessage(source, code, severity, message);
- }
- }
- return source;
- }
-}
-exports.Message = Message;
-
-},{"./builder":17,"./expression":23}],33:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Coalesce = exports.IsNull = exports.Null = void 0;
-const expression_1 = require("./expression");
-class Null extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(_ctx) {
- return null;
- }
-}
-exports.Null = Null;
-class IsNull extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return (await this.execArgs(ctx)) == null;
- }
-}
-exports.IsNull = IsNull;
-class Coalesce extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- if (this.args) {
- for (const arg of this.args) {
- const result = await arg.execute(ctx);
- // if a single arg that's a list, coalesce over the list
- if (this.args.length === 1 && Array.isArray(result)) {
- const item = result.find(item => item != null);
- if (item != null) {
- return item;
- }
- }
- else {
- if (result != null) {
- return result;
- }
- }
- }
- }
- return null;
- }
-}
-exports.Coalesce = Coalesce;
-
-},{"./expression":23}],34:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Precision = exports.SameOrBefore = exports.SameOrAfter = exports.SameAs = exports.Before = exports.After = exports.Length = exports.ProperContains = exports.ProperIn = exports.ProperIncludedIn = exports.ProperIncludes = exports.IncludedIn = exports.Includes = exports.Contains = exports.In = exports.Indexer = exports.Intersect = exports.Except = exports.Union = exports.NotEqual = exports.Equivalent = exports.Equal = void 0;
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-const expression_1 = require("./expression");
-const logic_1 = require("../datatypes/logic");
-const datetime_1 = require("../datatypes/datetime");
-const util_1 = require("../util/util");
-const comparison_1 = require("../util/comparison");
-const DT = __importStar(require("./datetime"));
-const LIST = __importStar(require("./list"));
-const IVL = __importStar(require("./interval"));
-const elmTypes_1 = require("../util/elmTypes");
-class Equal extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args[0] == null || args[1] == null) {
- return null;
- }
- // @ts-ignore
- return (0, comparison_1.equals)(...args);
- }
-}
-exports.Equal = Equal;
-class Equivalent extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- let [a, b] = await this.execArgs(ctx);
- if (a == null && b == null) {
- return true;
- }
- else if (a == null || b == null) {
- return false;
- }
- else {
- // comparison of valueset id/version -> only check expanded equivalence if these don't match
- if (a.isValueSet && b.isValueSet) {
- if (a.id === b.id && a.version === b.version) {
- return true;
- }
- }
- if (a.isValueSet) {
- a = await (0, util_1.resolveValueSet)(a, ctx);
- }
- if (b.isValueSet) {
- b = await (0, util_1.resolveValueSet)(b, ctx);
- }
- return (0, comparison_1.equivalent)(a, b);
- }
- }
-}
-exports.Equivalent = Equivalent;
-class NotEqual extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args[0] == null || args[1] == null) {
- return null;
- }
- // @ts-ignore
- return logic_1.ThreeValuedLogic.not((0, comparison_1.equals)(...(await this.execArgs(ctx))));
- }
-}
-exports.NotEqual = NotEqual;
-class Union extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a == null && b == null) {
- return this.listTypeArgs() ? [] : null;
- }
- if (a == null || b == null) {
- const notNull = a || b;
- if ((0, util_1.typeIsArray)(notNull)) {
- return notNull;
- }
- else {
- return null;
- }
- }
- const lib = (0, util_1.typeIsArray)(a) ? LIST : IVL;
- return lib.doUnion(a, b);
- }
- listTypeArgs() {
- return this.args?.some((arg) => {
- return arg.asTypeSpecifier != null && arg.asTypeSpecifier.type === elmTypes_1.ELM_LIST_TYPE_SPECIFIER;
- });
- }
-}
-exports.Union = Union;
-class Except extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a == null) {
- return null;
- }
- if (b == null) {
- return (0, util_1.typeIsArray)(a) ? a : null;
- }
- const lib = (0, util_1.typeIsArray)(a) ? LIST : IVL;
- return lib.doExcept(a, b);
- }
-}
-exports.Except = Except;
-class Intersect extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a == null || b == null) {
- return null;
- }
- const lib = (0, util_1.typeIsArray)(a) ? LIST : IVL;
- return lib.doIntersect(a, b);
- }
-}
-exports.Intersect = Intersect;
-class Indexer extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [operand, index] = await this.execArgs(ctx);
- if (operand == null || index == null) {
- return null;
- }
- if (index < 0 || index >= operand.length) {
- return null;
- }
- return operand[index];
- }
-}
-exports.Indexer = Indexer;
-class In extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [item, container] = await this.execArgs(ctx);
- if (container == null) {
- return false;
- }
- if ((0, util_1.typeIsArray)(container)) {
- return LIST.doContains(container, item);
- }
- else {
- if (item == null) {
- return null;
- }
- return IVL.doContains(container, item, this.precision);
- }
- }
-}
-exports.In = In;
-class Contains extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [container, item] = await this.execArgs(ctx);
- if (container == null) {
- return false;
- }
- if ((0, util_1.typeIsArray)(container)) {
- return LIST.doContains(container, item);
- }
- else {
- if (item == null) {
- return null;
- }
- return IVL.doContains(container, item, this.precision);
- }
- }
-}
-exports.Contains = Contains;
-class Includes extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [container, contained] = await this.execArgs(ctx);
- if (container == null || contained == null) {
- return null;
- }
- const lib = (0, util_1.typeIsArray)(container) ? LIST : IVL;
- return lib.doIncludes(container, contained, this.precision);
- }
-}
-exports.Includes = Includes;
-class IncludedIn extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [contained, container] = await this.execArgs(ctx);
- if (container == null || contained == null) {
- return null;
- }
- const lib = (0, util_1.typeIsArray)(container) ? LIST : IVL;
- return lib.doIncludes(container, contained, this.precision);
- }
-}
-exports.IncludedIn = IncludedIn;
-class ProperIncludes extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [container, contained] = await this.execArgs(ctx);
- if (container == null || contained == null) {
- return null;
- }
- const lib = (0, util_1.typeIsArray)(container) ? LIST : IVL;
- return lib.doProperIncludes(container, contained, this.precision);
- }
-}
-exports.ProperIncludes = ProperIncludes;
-class ProperIncludedIn extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [contained, container] = await this.execArgs(ctx);
- if (container == null || contained == null) {
- return null;
- }
- const lib = (0, util_1.typeIsArray)(container) ? LIST : IVL;
- return lib.doProperIncludes(container, contained, this.precision);
- }
-}
-exports.ProperIncludedIn = ProperIncludedIn;
-class ProperIn extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [item, container] = await this.execArgs(ctx);
- if (container == null) {
- return false;
- }
- if ((0, util_1.typeIsArray)(container)) {
- return LIST.doProperContains(container, item);
- }
- else {
- return IVL.doProperContains(container, item, this.precision);
- }
- }
-}
-exports.ProperIn = ProperIn;
-class ProperContains extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [container, item] = await this.execArgs(ctx);
- if (container == null) {
- return false;
- }
- if ((0, util_1.typeIsArray)(container)) {
- return LIST.doProperContains(container, item);
- }
- else {
- return IVL.doProperContains(container, item, this.precision);
- }
- }
-}
-exports.ProperContains = ProperContains;
-class Length extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return arg.length;
- }
- else if (this.arg.asTypeSpecifier.type === elmTypes_1.ELM_LIST_TYPE_SPECIFIER) {
- return 0;
- }
- else {
- return null;
- }
- }
-}
-exports.Length = Length;
-class After extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a == null || b == null) {
- return null;
- }
- const lib = a instanceof datetime_1.DateTime ? DT : IVL;
- return lib.doAfter(a, b, this.precision);
- }
-}
-exports.After = After;
-class Before extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision != null ? json.precision.toLowerCase() : undefined;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a == null || b == null) {
- return null;
- }
- const lib = a instanceof datetime_1.DateTime ? DT : IVL;
- return lib.doBefore(a, b, this.precision);
- }
-}
-exports.Before = Before;
-class SameAs extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const [a, b] = await this.execArgs(ctx);
- if (a != null && b != null) {
- return a.sameAs(b, this.precision != null ? this.precision.toLowerCase() : undefined);
- }
- else {
- return null;
- }
- }
-}
-exports.SameAs = SameAs;
-class SameOrAfter extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const [d1, d2] = await this.execArgs(ctx);
- if (d1 != null && d2 != null) {
- return d1.sameOrAfter(d2, this.precision != null ? this.precision.toLowerCase() : undefined);
- }
- else {
- return null;
- }
- }
-}
-exports.SameOrAfter = SameOrAfter;
-class SameOrBefore extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.precision = json.precision;
- }
- async exec(ctx) {
- const [d1, d2] = await this.execArgs(ctx);
- if (d1 != null && d2 != null) {
- return d1.sameOrBefore(d2, this.precision != null ? this.precision.toLowerCase() : undefined);
- }
- else {
- return null;
- }
- }
-}
-exports.SameOrBefore = SameOrBefore;
-// Implemented for DateTime, Date, and Time but not for Decimal yet
-class Precision extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- // Since we can't extend UnimplementedExpression directly for this overloaded function,
- // we have to copy the error to throw here if we are not using the correct type
- if (!arg.getPrecisionValue) {
- throw new Error(`Unimplemented Expression: Precision`);
- }
- return arg.getPrecisionValue();
- }
-}
-exports.Precision = Precision;
-
-},{"../datatypes/datetime":8,"../datatypes/logic":11,"../util/comparison":53,"../util/elmTypes":55,"../util/util":60,"./datetime":21,"./expression":23,"./interval":27,"./list":29}],35:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ParameterRef = exports.ParameterDef = void 0;
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-class ParameterDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.default = (0, builder_1.build)(json.default);
- this.parameterTypeSpecifier = json.parameterTypeSpecifier;
- }
- async exec(ctx) {
- // If context parameters contains the name, return value.
- if (ctx && ctx.parameters[this.name] !== undefined) {
- return ctx.parameters[this.name];
- // If the parent context contains the name, return that
- }
- else if (ctx.getParentParameter(this.name) !== undefined) {
- const parentParam = ctx.getParentParameter(this.name);
- return parentParam.default != null ? parentParam.default.execute(ctx) : parentParam;
- // If default type exists, execute the default type
- }
- else if (this.default != null) {
- await this.default.execute(ctx);
- }
- }
-}
-exports.ParameterDef = ParameterDef;
-class ParameterRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.library = json.libraryName;
- }
- async exec(ctx) {
- ctx = this.library ? ctx.getLibraryContext(this.library) : ctx;
- const param = ctx.getParameter(this.name);
- return param != null ? param.execute(ctx) : undefined;
- }
-}
-exports.ParameterRef = ParameterRef;
-
-},{"./builder":17,"./expression":23}],36:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Quantity = void 0;
-const expression_1 = require("./expression");
-const DT = __importStar(require("../datatypes/datatypes"));
-// Unit conversation is currently implemented on for time duration comparison operations
-// TODO: Implement unit conversation for time duration mathematical operations
-class Quantity extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.value = parseFloat(json.value);
- this.unit = json.unit;
- }
- async exec(_ctx) {
- return new DT.Quantity(this.value, this.unit);
- }
-}
-exports.Quantity = Quantity;
-
-},{"../datatypes/datatypes":7,"./expression":23}],37:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.QueryLetRef = exports.AliasRef = exports.Query = exports.SortClause = exports.ReturnClause = exports.ByColumn = exports.ByExpression = exports.ByDirection = exports.Sort = exports.Without = exports.With = exports.LetClause = exports.AliasedQuerySource = void 0;
-const util_1 = require("../util/util");
-const builder_1 = require("./builder");
-const expression_1 = require("./expression");
-const list_1 = require("./list");
-class AliasedQuerySource {
- constructor(json) {
- this.alias = json.alias;
- this.expression = (0, builder_1.build)(json.expression);
- }
-}
-exports.AliasedQuerySource = AliasedQuerySource;
-class LetClause {
- constructor(json) {
- this.identifier = json.identifier;
- this.expression = (0, builder_1.build)(json.expression);
- }
-}
-exports.LetClause = LetClause;
-class With extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.alias = json.alias;
- this.expression = (0, builder_1.build)(json.expression);
- this.suchThat = (0, builder_1.build)(json.suchThat);
- }
- async exec(ctx) {
- let records = await this.expression.execute(ctx);
- if (!(0, util_1.typeIsArray)(records)) {
- records = [records];
- }
- const returns = [];
- for (const rec of records) {
- const childCtx = ctx.childContext();
- childCtx.set(this.alias, rec);
- returns.push(await this.suchThat.execute(childCtx));
- }
- return returns.some((x) => x);
- }
-}
-exports.With = With;
-class Without extends With {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return !(await super.exec(ctx));
- }
-}
-exports.Without = Without;
-// ELM-only, not a product of CQL
-class Sort extends expression_1.UnimplementedExpression {
-}
-exports.Sort = Sort;
-class ByDirection extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.direction = json.direction;
- this.low_order = this.direction === 'asc' || this.direction === 'ascending' ? -1 : 1;
- this.high_order = this.low_order * -1;
- }
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- async exec(ctx, a, b) {
- if (a === b) {
- return 0;
- }
- else if (a.isQuantity && b.isQuantity) {
- if (a.before(b)) {
- return this.low_order;
- }
- else {
- return this.high_order;
- }
- }
- else if (a < b) {
- return this.low_order;
- }
- else {
- return this.high_order;
- }
- }
-}
-exports.ByDirection = ByDirection;
-class ByExpression extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.expression = (0, builder_1.build)(json.expression);
- this.direction = json.direction;
- this.low_order = this.direction === 'asc' || this.direction === 'ascending' ? -1 : 1;
- this.high_order = this.low_order * -1;
- }
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- async exec(ctx, a, b) {
- let sctx = ctx.childContext(a);
- const a_val = await this.expression.execute(sctx);
- sctx = ctx.childContext(b);
- const b_val = await this.expression.execute(sctx);
- if (a_val === b_val || (a_val == null && b_val == null)) {
- return 0;
- }
- else if (a_val == null || b_val == null) {
- return a_val == null ? this.low_order : this.high_order;
- }
- else if (a_val.isQuantity && b_val.isQuantity) {
- return a_val.before(b_val) ? this.low_order : this.high_order;
- }
- else {
- return a_val < b_val ? this.low_order : this.high_order;
- }
- }
-}
-exports.ByExpression = ByExpression;
-class ByColumn extends ByExpression {
- constructor(json) {
- super(json);
- this.expression = (0, builder_1.build)({
- name: json.path,
- type: 'IdentifierRef'
- });
- }
-}
-exports.ByColumn = ByColumn;
-class ReturnClause {
- constructor(json) {
- this.expression = (0, builder_1.build)(json.expression);
- this.distinct = json.distinct != null ? json.distinct : true;
- }
-}
-exports.ReturnClause = ReturnClause;
-class SortClause {
- constructor(json) {
- this.by = (0, builder_1.build)(json != null ? json.by : undefined);
- }
- async sort(ctx, values) {
- if (this.by) {
- return (0, util_1.asyncMergeSort)(values, async (a, b) => {
- let order = 0;
- for (const item of this.by) {
- // Do not use execute here because the value of the sort order is not important.
- order = await item.exec(ctx, a, b);
- if (order !== 0) {
- break;
- }
- }
- return order;
- });
- }
- return values;
- }
-}
-exports.SortClause = SortClause;
-class AggregateClause extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.identifier = json.identifier;
- this.expression = (0, builder_1.build)(json.expression);
- this.starting = json.starting ? (0, builder_1.build)(json.starting) : null;
- this.distinct = json.distinct != null ? json.distinct : false;
- }
- async aggregate(returnedValues, ctx) {
- let aggregateValue = this.starting != null ? await this.starting.execute(ctx) : null;
- for (const contextValues of returnedValues) {
- const childContext = ctx.childContext(contextValues);
- childContext.set(this.identifier, aggregateValue);
- aggregateValue = await this.expression.execute(childContext);
- }
- return aggregateValue;
- }
-}
-class Query extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.sources = json.source.map((s) => new AliasedQuerySource(s));
- this.aliases = json.source.map((s) => s.alias);
- this.letClauses = json.let != null ? json.let.map((d) => new LetClause(d)) : [];
- this.relationship = json.relationship != null ? (0, builder_1.build)(json.relationship) : [];
- this.where = (0, builder_1.build)(json.where);
- this.returnClause = json.return != null ? new ReturnClause(json.return) : null;
- this.aggregateClause = json.aggregate != null ? new AggregateClause(json.aggregate) : null;
- this.sortClause = json.sort != null ? new SortClause(json.sort) : null;
- }
- isDistinct() {
- if (this.aggregateClause != null && this.aggregateClause.distinct != null) {
- return this.aggregateClause.distinct;
- }
- else if (this.returnClause != null && this.returnClause.distinct != null) {
- return this.returnClause.distinct;
- }
- return true;
- }
- async exec(ctx) {
- let sourceResults = await Promise.all(this.sources.map(s => s.expression.execute(ctx)));
- // If every source is null, the result is null
- // See: https://jira.hl7.org/browse/FHIR-40225
- if (sourceResults.every(r => r == null)) {
- return null;
- }
- const isList = sourceResults.some(r => Array.isArray(r));
- // For ease of processing, convert all the sources to lists and
- // convert nulls to empty lists (we already handled the ALL null case)
- sourceResults = sourceResults.map(r => {
- if (r == null) {
- return [];
- }
- else if (Array.isArray(r)) {
- return r;
- }
- else {
- return [r];
- }
- });
- // Iterate over the cartesian product of the sources.
- // See: https://cql.hl7.org/03-developersguide.html#multi-source-queries
- const cartesian = cartesianProductOf(sourceResults);
- let returnedValues = [];
- for (const combo of cartesian) {
- const rctx = ctx.childContext();
- combo.forEach((r, i) => rctx.set(this.aliases[i], r));
- for (const def of this.letClauses) {
- rctx.set(def.identifier, await def.expression.execute(rctx));
- }
- const relations = [];
- for (const rel of this.relationship) {
- const child_ctx = rctx.childContext();
- relations.push(await rel.execute(child_ctx));
- }
- const passed = (0, util_1.allTrue)(relations) && (this.where ? await this.where.execute(rctx) : true);
- if (passed) {
- if (this.returnClause != null) {
- const val = await this.returnClause.expression.execute(rctx);
- returnedValues.push(val);
- }
- else {
- if (this.aliases.length === 1 && this.aggregateClause == null) {
- returnedValues.push(rctx.get(this.aliases[0]));
- }
- else {
- returnedValues.push(rctx.context_values);
- }
- }
- }
- }
- if (this.isDistinct()) {
- returnedValues = (0, list_1.toDistinctList)(returnedValues);
- }
- if (this.aggregateClause != null) {
- returnedValues = await this.aggregateClause.aggregate(returnedValues, ctx);
- }
- if (this.sortClause != null) {
- returnedValues = await this.sortClause.sort(ctx, returnedValues);
- }
- if (isList || this.aggregateClause != null) {
- return returnedValues;
- }
- else {
- return returnedValues[0];
- }
- }
-}
-exports.Query = Query;
-class AliasRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- }
- async exec(ctx) {
- return ctx != null ? ctx.get(this.name) : undefined;
- }
-}
-exports.AliasRef = AliasRef;
-class QueryLetRef extends AliasRef {
- constructor(json) {
- super(json);
- }
-}
-exports.QueryLetRef = QueryLetRef;
-// cartesianProductOf function based on Chris West's function:
-// https://cwestblog.com/2011/05/02/cartesian-product-of-multiple-arrays/
-function cartesianProductOf(sources) {
- return sources.reduce((a, b) => {
- const ret = [];
- a.forEach(a => {
- b.forEach(b => {
- ret.push(a.concat([b]));
- });
- });
- return ret;
- }, [[]]);
-}
-
-},{"../util/util":60,"./builder":17,"./expression":23,"./list":29}],38:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Ratio = void 0;
-const expression_1 = require("./expression");
-const quantity_1 = require("../datatypes/quantity");
-const DT = __importStar(require("../datatypes/datatypes"));
-class Ratio extends expression_1.Expression {
- constructor(json) {
- super(json);
- if (json.numerator == null) {
- throw new Error('Cannot create a ratio with an undefined numerator value');
- }
- else {
- this.numerator = new quantity_1.Quantity(json.numerator.value, json.numerator.unit);
- }
- if (json.denominator == null) {
- throw new Error('Cannot create a ratio with an undefined denominator value');
- }
- else {
- this.denominator = new quantity_1.Quantity(json.denominator.value, json.denominator.unit);
- }
- }
- async exec(_ctx) {
- return new DT.Ratio(this.numerator, this.denominator);
- }
-}
-exports.Ratio = Ratio;
-
-},{"../datatypes/datatypes":7,"../datatypes/quantity":12,"./expression":23}],39:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.IdentifierRef = exports.OperandRef = exports.FunctionRef = exports.FunctionDef = exports.ExpressionRef = exports.ExpressionDef = void 0;
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-const elmTypes_1 = require("../util/elmTypes");
-class ExpressionDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.context = json.context;
- this.expression = (0, builder_1.build)(json.expression);
- }
- async exec(ctx) {
- const value = this.expression != null ? await this.expression.execute(ctx) : undefined;
- ctx.rootContext().set(this.name, value);
- return value;
- }
-}
-exports.ExpressionDef = ExpressionDef;
-class ExpressionRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.library = json.libraryName;
- }
- async exec(ctx) {
- ctx = this.library ? ctx.getLibraryContext(this.library) : ctx;
- let value = ctx.get(this.name);
- if (value instanceof expression_1.Expression) {
- value = await value.execute(ctx);
- }
- return value;
- }
-}
-exports.ExpressionRef = ExpressionRef;
-class FunctionDef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.expression = (0, builder_1.build)(json.expression);
- this.parameters = json.operand;
- }
- async exec(_ctx) {
- return this;
- }
-}
-exports.FunctionDef = FunctionDef;
-class FunctionRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.library = json.libraryName;
- }
- async exec(ctx) {
- let functionDefs, child_ctx;
- if (this.library) {
- const lib = ctx.get(this.library);
- functionDefs = lib ? lib.getFunction(this.name) : undefined;
- const libCtx = ctx.getLibraryContext(this.library);
- child_ctx = libCtx ? libCtx.childContext() : undefined;
- }
- else {
- functionDefs = ctx.getFunction(this.name);
- child_ctx = ctx.childContext();
- }
- const args = await this.execArgs(ctx);
- // Filter out functions w/ wrong number of arguments.
- functionDefs = functionDefs.filter((f) => f.parameters.length === args.length);
- // If there is still > 1 matching function, filter by argument types
- if (functionDefs.length > 1) {
- functionDefs = functionDefs.filter((f) => {
- let match = true;
- for (let i = 0; i < args.length && match; i++) {
- if (args[i] !== null) {
- let operandTypeSpecifier = f.parameters[i].operandTypeSpecifier;
- if (operandTypeSpecifier == null && f.parameters[i].operandType != null) {
- // convert it to a NamedTypedSpecifier
- operandTypeSpecifier = {
- name: f.parameters[i].operandType,
- type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER
- };
- }
- match = ctx.matchesTypeSpecifier(args[i], operandTypeSpecifier);
- }
- }
- return match;
- });
- }
- // If there is still > 1 matching function, calculate a score based on quality of matches
- if (functionDefs.length > 1) {
- // TODO
- }
- if (functionDefs.length === 0) {
- throw new Error('no function with matching signature could be found');
- }
- // By this point, we should have only one function, but until implementation is completed,
- // use the last one (no matter how many still remain)
- const functionDef = functionDefs[functionDefs.length - 1];
- for (let i = 0; i < functionDef.parameters.length; i++) {
- child_ctx.set(functionDef.parameters[i].name, args[i]);
- }
- return functionDef.expression.execute(child_ctx);
- }
-}
-exports.FunctionRef = FunctionRef;
-class OperandRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- }
- async exec(ctx) {
- return ctx.get(this.name);
- }
-}
-exports.OperandRef = OperandRef;
-class IdentifierRef extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.name = json.name;
- this.library = json.libraryName;
- }
- async exec(ctx) {
- // TODO: Technically, the ELM Translator should never output one of these
- // but this code is needed since it does, as a work-around to get queries
- // to work properly when sorting by a field in a tuple
- const lib = this.library ? ctx.get(this.library) : undefined;
- let val = lib ? lib.get(this.name) : ctx.get(this.name);
- if (val == null) {
- const parts = this.name.split('.');
- val = ctx.get(parts[0]);
- if (val != null && parts.length > 1) {
- let curr_obj = val;
- for (const part of parts.slice(1)) {
- // _obj = curr_obj?[part] ? curr_obj?.get?(part)
- // curr_obj = if _obj instanceof Function then _obj.call(curr_obj) else _obj
- let _obj;
- if (curr_obj != null) {
- _obj = curr_obj[part];
- if (_obj === undefined && typeof curr_obj.get === 'function') {
- _obj = curr_obj.get(part);
- }
- }
- curr_obj = _obj instanceof Function ? _obj.call(curr_obj) : _obj;
- }
- val = curr_obj;
- }
- }
- if (val instanceof Function) {
- return val.call(ctx.context_values);
- }
- else {
- return val;
- }
- }
-}
-exports.IdentifierRef = IdentifierRef;
-
-},{"../util/elmTypes":55,"./builder":17,"./expression":23}],40:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ReplaceMatches = exports.EndsWith = exports.StartsWith = exports.Substring = exports.Matches = exports.LastPositionOf = exports.PositionOf = exports.Lower = exports.Upper = exports.SplitOnMatches = exports.Split = exports.Combine = exports.Concatenate = void 0;
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-class Concatenate extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args.some((x) => x == null)) {
- return null;
- }
- else {
- return args.reduce((x, y) => x + y);
- }
- }
-}
-exports.Concatenate = Concatenate;
-class Combine extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.source = (0, builder_1.build)(json.source);
- this.separator = (0, builder_1.build)(json.separator);
- }
- async exec(ctx) {
- const source = await this.source.execute(ctx);
- const separator = this.separator != null ? await this.separator.execute(ctx) : '';
- if (source == null) {
- return null;
- }
- else {
- const filteredArray = source.filter((x) => x != null);
- if (filteredArray.length === 0) {
- return null;
- }
- else {
- return filteredArray.join(separator);
- }
- }
- }
-}
-exports.Combine = Combine;
-class Split extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.stringToSplit = (0, builder_1.build)(json.stringToSplit);
- this.separator = (0, builder_1.build)(json.separator);
- }
- async exec(ctx) {
- const stringToSplit = await this.stringToSplit.execute(ctx);
- const separator = await this.separator.execute(ctx);
- if (stringToSplit && separator) {
- return stringToSplit.split(separator);
- }
- return stringToSplit ? [stringToSplit] : null;
- }
-}
-exports.Split = Split;
-class SplitOnMatches extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.stringToSplit = (0, builder_1.build)(json.stringToSplit);
- this.separatorPattern = (0, builder_1.build)(json.separatorPattern);
- }
- async exec(ctx) {
- const stringToSplit = await this.stringToSplit.execute(ctx);
- const separatorPattern = await this.separatorPattern.execute(ctx);
- if (stringToSplit && separatorPattern) {
- return stringToSplit.split(new RegExp(separatorPattern));
- }
- return stringToSplit ? [stringToSplit] : null;
- }
-}
-exports.SplitOnMatches = SplitOnMatches;
-// Length is completely handled by overloaded#Length
-class Upper extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return arg.toUpperCase();
- }
- else {
- return null;
- }
- }
-}
-exports.Upper = Upper;
-class Lower extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return arg.toLowerCase();
- }
- else {
- return null;
- }
- }
-}
-exports.Lower = Lower;
-// Indexer is completely handled by overloaded#Indexer
-class PositionOf extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.pattern = (0, builder_1.build)(json.pattern);
- this.string = (0, builder_1.build)(json.string);
- }
- async exec(ctx) {
- const pattern = await this.pattern.execute(ctx);
- const string = await this.string.execute(ctx);
- if (pattern == null || string == null) {
- return null;
- }
- else {
- return string.indexOf(pattern);
- }
- }
-}
-exports.PositionOf = PositionOf;
-class LastPositionOf extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.pattern = (0, builder_1.build)(json.pattern);
- this.string = (0, builder_1.build)(json.string);
- }
- async exec(ctx) {
- const pattern = await this.pattern.execute(ctx);
- const string = await this.string.execute(ctx);
- if (pattern == null || string == null) {
- return null;
- }
- else {
- return string.lastIndexOf(pattern);
- }
- }
-}
-exports.LastPositionOf = LastPositionOf;
-class Matches extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [string, pattern] = await this.execArgs(ctx);
- if (string == null || pattern == null) {
- return null;
- }
- return new RegExp('^' + pattern + '$').test(string);
- }
-}
-exports.Matches = Matches;
-class Substring extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.stringToSub = (0, builder_1.build)(json.stringToSub);
- this.startIndex = (0, builder_1.build)(json.startIndex);
- this.length = (0, builder_1.build)(json['length']);
- }
- async exec(ctx) {
- const stringToSub = await this.stringToSub.execute(ctx);
- const startIndex = await this.startIndex.execute(ctx);
- const length = this.length != null ? await this.length.execute(ctx) : null;
- // According to spec: If stringToSub or startIndex is null, or startIndex is out of range, the result is null.
- if (stringToSub == null ||
- startIndex == null ||
- startIndex < 0 ||
- startIndex >= stringToSub.length) {
- return null;
- }
- else if (length != null) {
- return stringToSub.substr(startIndex, length);
- }
- else {
- return stringToSub.substr(startIndex);
- }
- }
-}
-exports.Substring = Substring;
-class StartsWith extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args.some((x) => x == null)) {
- return null;
- }
- else {
- return args[0].slice(0, args[1].length) === args[1];
- }
- }
-}
-exports.StartsWith = StartsWith;
-class EndsWith extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args.some((x) => x == null)) {
- return null;
- }
- else {
- return args[1] === '' || args[0].slice(-args[1].length) === args[1];
- }
- }
-}
-exports.EndsWith = EndsWith;
-class ReplaceMatches extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const args = await this.execArgs(ctx);
- if (args.some((x) => x == null)) {
- return null;
- }
- else {
- return args[0].replace(new RegExp(args[1], 'g'), args[2].replace(/\\\$/g, '$$'));
- }
- }
-}
-exports.ReplaceMatches = ReplaceMatches;
-
-},{"./builder":17,"./expression":23}],41:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.TupleElementDefinition = exports.TupleElement = exports.Tuple = exports.Property = void 0;
-const expression_1 = require("./expression");
-const builder_1 = require("./builder");
-class Property extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.scope = json.scope;
- this.source = (0, builder_1.build)(json.source);
- this.path = json.path;
- }
- async exec(ctx) {
- let obj = this.scope != null ? ctx.get(this.scope) : this.source;
- if (obj instanceof expression_1.Expression) {
- obj = await obj.execute(ctx);
- }
- let val = getPropertyFromObject(obj, this.path);
- if (val == null) {
- const parts = this.path.split('.');
- let curr_obj = obj;
- for (const part of parts) {
- const _obj = getPropertyFromObject(curr_obj, part);
- curr_obj = _obj instanceof Function ? _obj.call(curr_obj) : _obj;
- }
- val = curr_obj != null ? curr_obj : null; // convert undefined to null
- }
- if (val instanceof Function) {
- return val.call(obj);
- }
- else {
- return val;
- }
- }
-}
-exports.Property = Property;
-function getPropertyFromObject(obj, path) {
- let val;
- if (obj != null) {
- val = obj[path];
- if (val === undefined && typeof obj.get === 'function') {
- val = obj.get(path);
- }
- }
- return val;
-}
-class Tuple extends expression_1.Expression {
- constructor(json) {
- super(json);
- const elements = json.element != null ? json.element : [];
- this.elements = elements.map((el) => {
- return {
- name: el.name,
- value: (0, builder_1.build)(el.value)
- };
- });
- }
- get isTuple() {
- return true;
- }
- async exec(ctx) {
- const val = {};
- for (const el of this.elements) {
- val[el.name] = el.value != null ? await el.value.execute(ctx) : undefined;
- }
- return val;
- }
-}
-exports.Tuple = Tuple;
-class TupleElement extends expression_1.UnimplementedExpression {
-}
-exports.TupleElement = TupleElement;
-class TupleElementDefinition extends expression_1.UnimplementedExpression {
-}
-exports.TupleElementDefinition = TupleElementDefinition;
-
-},{"./builder":17,"./expression":23}],42:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.TupleTypeSpecifier = exports.NamedTypeSpecifier = exports.ListTypeSpecifier = exports.IntervalTypeSpecifier = exports.Is = exports.CanConvertQuantity = exports.ConvertQuantity = exports.ConvertsToTime = exports.ConvertsToString = exports.ConvertsToRatio = exports.ConvertsToQuantity = exports.ConvertsToLong = exports.ConvertsToInteger = exports.ConvertsToDecimal = exports.ConvertsToDateTime = exports.ConvertsToDate = exports.ConvertsToBoolean = exports.Convert = exports.ToTime = exports.ToString = exports.ToRatio = exports.ToQuantity = exports.ToLong = exports.ToInteger = exports.ToDecimal = exports.ToDateTime = exports.ToDate = exports.ToConcept = exports.ToBoolean = exports.As = void 0;
-const expression_1 = require("./expression");
-const datetime_1 = require("../datatypes/datetime");
-const clinical_1 = require("../datatypes/clinical");
-const interval_1 = require("../datatypes/interval");
-const quantity_1 = require("../datatypes/quantity");
-const math_1 = require("../util/math");
-const util_1 = require("../util/util");
-const ratio_1 = require("../datatypes/ratio");
-const uncertainty_1 = require("../datatypes/uncertainty");
-const elmTypes_1 = require("../util/elmTypes");
-// TODO: Casting and Conversion needs unit tests!
-class As extends expression_1.Expression {
- constructor(json) {
- super(json);
- if (json.asTypeSpecifier) {
- this.asTypeSpecifier = json.asTypeSpecifier;
- }
- else if (json.asType) {
- // convert it to a NamedTypedSpecifier
- this.asTypeSpecifier = {
- name: json.asType,
- type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER
- };
- }
- this.strict = json.strict != null ? json.strict : false;
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- // If it is null, return null
- if (arg == null) {
- return null;
- }
- if (ctx.matchesTypeSpecifier(arg, this.asTypeSpecifier)) {
- // intervals track their point type, so adjust the interval point type if it does not match
- if (arg.isInterval && this.asTypeSpecifier.type === elmTypes_1.ELM_INTERVAL_TYPE_SPECIFIER) {
- const argInterval = arg;
- const asIntervalSpecifier = this.asTypeSpecifier;
- const asIntervalPointType = asIntervalSpecifier.pointType
- ?.name;
- if (asIntervalPointType && argInterval.pointType !== asIntervalPointType) {
- return new interval_1.Interval(argInterval.low, argInterval.high, argInterval.lowClosed, argInterval.highClosed, asIntervalPointType);
- }
- }
- // TODO: request patient source to change type identification
- return arg;
- }
- else if (this.strict) {
- const argTypeString = specifierToString(guessSpecifierType(arg));
- const asTypeString = specifierToString(this.asTypeSpecifier);
- throw new Error(`Cannot cast ${argTypeString} as ${asTypeString}`);
- }
- else {
- return null;
- }
- }
-}
-exports.As = As;
-class ToBoolean extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- const strArg = arg.toString().toLowerCase();
- if (['true', 't', 'yes', 'y', '1'].includes(strArg)) {
- return true;
- }
- else if (['false', 'f', 'no', 'n', '0'].includes(strArg)) {
- return false;
- }
- }
- return null;
- }
-}
-exports.ToBoolean = ToBoolean;
-class ToConcept extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return new clinical_1.Concept([arg], arg.display);
- }
- else {
- return null;
- }
- }
-}
-exports.ToConcept = ToConcept;
-class ToDate extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- else if (arg.isDateTime) {
- return arg.getDate();
- }
- else {
- return datetime_1.Date.parse(arg.toString());
- }
- }
-}
-exports.ToDate = ToDate;
-class ToDateTime extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg == null) {
- return null;
- }
- else if (arg.isDate) {
- const timezoneOffset = ctx.getExecutionDateTime().timezoneOffset;
- return arg.getDateTime(timezoneOffset);
- }
- else {
- return datetime_1.DateTime.parse(arg.toString());
- }
- }
-}
-exports.ToDateTime = ToDateTime;
-class ToDecimal extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- if (arg.isUncertainty) {
- const low = (0, math_1.limitDecimalPrecision)(parseFloat(arg.low.toString()));
- const high = (0, math_1.limitDecimalPrecision)(parseFloat(arg.high.toString()));
- return new uncertainty_1.Uncertainty(low, high);
- }
- else {
- const decimal = (0, math_1.limitDecimalPrecision)(parseFloat(arg.toString()));
- if ((0, math_1.isValidDecimal)(decimal)) {
- return decimal;
- }
- }
- }
- return null;
- }
-}
-exports.ToDecimal = ToDecimal;
-class ToInteger extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (typeof arg === 'number') {
- if ((0, math_1.isValidInteger)(arg)) {
- return arg;
- }
- }
- else if (typeof arg === 'bigint') {
- const integer = Number(arg);
- if ((0, math_1.isValidInteger)(integer)) {
- return integer;
- }
- }
- else if (typeof arg === 'string') {
- // check for blank string because Number('') and Number(' ') evaluate to 0.
- if (arg.trim().length === 0) {
- return null;
- }
- // note: invalid strings will result in NaN and fail isValidInteger
- const integer = Number(arg);
- if ((0, math_1.isValidInteger)(integer)) {
- return integer;
- }
- }
- else if (typeof arg === 'boolean') {
- return arg ? 1 : 0;
- }
- return null;
- }
-}
-exports.ToInteger = ToInteger;
-class ToLong extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (typeof arg === 'bigint') {
- if ((0, math_1.isValidLong)(arg)) {
- return arg;
- }
- }
- else if (typeof arg === 'number') {
- try {
- const long = BigInt(arg);
- if ((0, math_1.isValidLong)(long)) {
- return long;
- }
- }
- catch {
- return null;
- }
- }
- else if (typeof arg === 'string') {
- // check string format because BigInt throws for invalid strings
- if (!/^[+-]?\d+$/.test(arg)) {
- return null;
- }
- const long = BigInt(arg);
- if ((0, math_1.isValidLong)(long)) {
- return long;
- }
- }
- else if (typeof arg === 'boolean') {
- return arg ? 1n : 0n;
- }
- return null;
- }
-}
-exports.ToLong = ToLong;
-class ToQuantity extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- return this.convertValue(await this.execArgs(ctx));
- }
- convertValue(val) {
- if (val == null) {
- return null;
- }
- else if (typeof val === 'number') {
- return new quantity_1.Quantity(val, '1');
- }
- else if (typeof val === 'bigint') {
- // By definition, Quantity value is a Decimal in CQL, so we need to convert bigint to number.
- // While this isn't perfect, in practice it is probably OK since the range of safer integers
- // in JS number is pretty big: -(2^53 - 1) to 2^53 - 1, which is plus/minus 9 quadrillion.
- // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger#description
- return new quantity_1.Quantity(Number(val), '1');
- }
- else if (val.isRatio) {
- // numerator and denominator are guaranteed non-null
- return val.numerator.dividedBy(val.denominator);
- }
- else if (val.isUncertainty) {
- return new uncertainty_1.Uncertainty(this.convertValue(val.low), this.convertValue(val.high));
- }
- else {
- // it's a string or something else we'll try to parse as a string
- return (0, quantity_1.parseQuantity)(val.toString());
- }
- }
-}
-exports.ToQuantity = ToQuantity;
-class ToRatio extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- // Argument will be of form ':'
- let denominator, numerator;
- try {
- // String will be split into an array. Numerator will be at index 1, Denominator will be at index 4
- const splitRatioString = arg
- .toString()
- .match(/^(\d+(\.\d+)?\s*('.+')?)\s*:\s*(\d+(\.\d+)?\s*('.+')?)$/);
- if (splitRatioString == null) {
- return null;
- }
- numerator = (0, quantity_1.parseQuantity)(splitRatioString[1]);
- denominator = (0, quantity_1.parseQuantity)(splitRatioString[4]);
- }
- catch {
- // If the input string is not formatted correctly, or cannot be
- // interpreted as a valid Quantity value, the result is null.
- return null;
- }
- // The value element of a Quantity must be present.
- if (numerator == null || denominator == null) {
- return null;
- }
- return new ratio_1.Ratio(numerator, denominator);
- }
- else {
- return null;
- }
- }
-}
-exports.ToRatio = ToRatio;
-class ToString extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- return arg.toString();
- }
- else {
- return null;
- }
- }
-}
-exports.ToString = ToString;
-class ToTime extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg != null) {
- const timeString = arg.toString();
- // Return null if string doesn't represent a valid ISO-8601 Time
- // hh:mm:ss.fff or hh:mm:ss.fff
- const matches = /^T?((\d{2})(:(\d{2})(:(\d{2})(\.(\d+))?)?)?)?(Z|(([+-])(\d{2})(:?(\d{2}))?))?$/.exec(timeString);
- if (matches == null) {
- return null;
- }
- let hours = matches[2];
- let minutes = matches[4];
- let seconds = matches[6];
- // Validate h/m/s if they exist, but allow null
- if (hours != null) {
- if (hours < 0 || hours > 23) {
- return null;
- }
- hours = parseInt(hours, 10);
- }
- if (minutes != null) {
- if (minutes < 0 || minutes > 59) {
- return null;
- }
- minutes = parseInt(minutes, 10);
- }
- if (seconds != null) {
- if (seconds < 0 || seconds > 59) {
- return null;
- }
- seconds = parseInt(seconds, 10);
- }
- let milliseconds = matches[8];
- if (milliseconds != null) {
- milliseconds = parseInt((0, util_1.normalizeMillisecondsField)(milliseconds));
- }
- // Time is implemented as Datetime with year 0, month 1, day 1 and null timezoneOffset
- return new datetime_1.DateTime(0, 1, 1, hours, minutes, seconds, milliseconds, null);
- }
- else {
- return null;
- }
- }
-}
-exports.ToTime = ToTime;
-class Convert extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- this.toType = json.toType;
- }
- async exec(ctx) {
- switch (this.toType) {
- case elmTypes_1.ELM_BOOLEAN_TYPE:
- return new ToBoolean({ type: 'ToBoolean', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_CONCEPT_TYPE:
- return new ToConcept({ type: 'ToConcept', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_DECIMAL_TYPE:
- return new ToDecimal({ type: 'ToDecimal', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_INTEGER_TYPE:
- return new ToInteger({ type: 'ToInteger', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_LONG_TYPE:
- return new ToLong({ type: 'ToLong', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_STRING_TYPE:
- return new ToString({ type: 'ToString', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_QUANTITY_TYPE:
- return new ToQuantity({ type: 'ToQuantity', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_DATETIME_TYPE:
- return new ToDateTime({ type: 'ToDateTime', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_DATE_TYPE:
- return new ToDate({ type: 'ToDate', operand: this.operand }).execute(ctx);
- case elmTypes_1.ELM_TIME_TYPE:
- return new ToTime({ type: 'ToTime', operand: this.operand }).execute(ctx);
- default:
- return this.execArgs(ctx);
- }
- }
-}
-exports.Convert = Convert;
-class ConvertsToBoolean extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToBoolean, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToBoolean = ConvertsToBoolean;
-class ConvertsToDate extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToDate, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToDate = ConvertsToDate;
-class ConvertsToDateTime extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToDateTime, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToDateTime = ConvertsToDateTime;
-class ConvertsToDecimal extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToDecimal, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToDecimal = ConvertsToDecimal;
-class ConvertsToInteger extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToInteger, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToInteger = ConvertsToInteger;
-class ConvertsToLong extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToLong, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToLong = ConvertsToLong;
-class ConvertsToQuantity extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToQuantity, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToQuantity = ConvertsToQuantity;
-class ConvertsToRatio extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToRatio, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToRatio = ConvertsToRatio;
-class ConvertsToString extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToString, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToString = ConvertsToString;
-class ConvertsToTime extends expression_1.Expression {
- constructor(json) {
- super(json);
- this.operand = json.operand;
- }
- async exec(ctx) {
- const operatorValue = await this.execArgs(ctx);
- if (operatorValue === null) {
- return null;
- }
- else {
- return canConvertToType(ToTime, this.operand, ctx);
- }
- }
-}
-exports.ConvertsToTime = ConvertsToTime;
-async function canConvertToType(ConversionClass, operand, ctx) {
- try {
- const expression = new ConversionClass({ type: ConversionClass.name, operand: operand });
- const value = await expression.execute(ctx);
- if (value != null) {
- return true;
- }
- else {
- return false;
- }
- }
- catch {
- return false;
- }
-}
-class ConvertQuantity extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [quantity, newUnit] = await this.execArgs(ctx);
- if (quantity != null && newUnit != null) {
- try {
- return quantity.convertUnit(newUnit);
- }
- catch {
- // Cannot convert input to target unit, spec says to return null
- return null;
- }
- }
- }
-}
-exports.ConvertQuantity = ConvertQuantity;
-class CanConvertQuantity extends expression_1.Expression {
- constructor(json) {
- super(json);
- }
- async exec(ctx) {
- const [quantity, newUnit] = await this.execArgs(ctx);
- if (quantity != null && newUnit != null) {
- try {
- quantity.convertUnit(newUnit);
- return true;
- }
- catch {
- return false;
- }
- }
- return null;
- }
-}
-exports.CanConvertQuantity = CanConvertQuantity;
-class Is extends expression_1.Expression {
- constructor(json) {
- super(json);
- if (json.isTypeSpecifier) {
- this.isTypeSpecifier = json.isTypeSpecifier;
- }
- else if (json.isType) {
- // Convert it to a NamedTypeSpecifier
- this.isTypeSpecifier = {
- name: json.isType,
- type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER
- };
- }
- }
- async exec(ctx) {
- const arg = await this.execArgs(ctx);
- if (arg === null) {
- return false;
- }
- if (typeof arg._is !== 'function' && !isSystemType(this.isTypeSpecifier)) {
- // We need an _is implementation in order to check non System types
- throw new Error(`Patient Source does not support Is operation for localId: ${this.localId}`);
- }
- return ctx.matchesTypeSpecifier(arg, this.isTypeSpecifier);
- }
-}
-exports.Is = Is;
-function isSystemType(spec) {
- switch (spec.type) {
- case elmTypes_1.ELM_NAMED_TYPE_SPECIFIER:
- return spec.name.startsWith('{urn:hl7-org:elm-types:r1}');
- case elmTypes_1.ELM_LIST_TYPE_SPECIFIER:
- return isSystemType(spec.elementType);
- case elmTypes_1.ELM_TUPLE_TYPE_SPECIFIER:
- return spec.element.every((e) => isSystemType(e.elementType));
- case elmTypes_1.ELM_INTERVAL_TYPE_SPECIFIER:
- return isSystemType(spec.pointType);
- case elmTypes_1.ELM_CHOICE_TYPE_SPECIFIER:
- return spec.choice.every((c) => isSystemType(c));
- default:
- return false;
- }
-}
-function specifierToString(spec) {
- if (typeof spec === 'string') {
- return spec;
- }
- else if (spec == null || spec.type == null) {
- return '';
- }
- switch (spec.type) {
- case elmTypes_1.ELM_NAMED_TYPE_SPECIFIER:
- return spec.name;
- case elmTypes_1.ELM_LIST_TYPE_SPECIFIER:
- return `List<${specifierToString(spec.elementType)}>`;
- case elmTypes_1.ELM_TUPLE_TYPE_SPECIFIER:
- return `Tuple<${spec.element
- .map((e) => `${e.name} ${specifierToString(e.elementType)}`)
- .join(', ')}>`;
- case elmTypes_1.ELM_INTERVAL_TYPE_SPECIFIER:
- return `Interval<${specifierToString(spec.pointType)}>`;
- case elmTypes_1.ELM_CHOICE_TYPE_SPECIFIER:
- return `Choice<${spec.choice.map((c) => specifierToString(c)).join(', ')}>`;
- default:
- return JSON.stringify(spec);
- }
-}
-function guessSpecifierType(val) {
- if (val == null) {
- return 'Null';
- }
- const typeHierarchy = typeof val._typeHierarchy === 'function' && val._typeHierarchy();
- if (typeHierarchy && typeHierarchy.length > 0) {
- return typeHierarchy[0];
- }
- else if (typeof val === 'boolean') {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_BOOLEAN_TYPE };
- }
- else if (typeof val === 'number' && Math.floor(val) === val) {
- // it could still be a decimal, but we have to just take our best guess!
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_INTEGER_TYPE };
- }
- else if (typeof val === 'number') {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_DECIMAL_TYPE };
- }
- else if (typeof val === 'bigint') {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_LONG_TYPE };
- }
- else if (typeof val === 'string') {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_STRING_TYPE };
- }
- else if (val.isConcept) {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_CONCEPT_TYPE };
- }
- else if (val.isCode) {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: '{urn:hl7-org:elm-types:r1}Code' };
- }
- else if (val.isDate) {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_DATE_TYPE };
- }
- else if (val.isTime && val.isTime()) {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_TIME_TYPE };
- }
- else if (val.isDateTime) {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_DATETIME_TYPE };
- }
- else if (val.isQuantity) {
- return { type: elmTypes_1.ELM_NAMED_TYPE_SPECIFIER, name: elmTypes_1.ELM_DATETIME_TYPE };
- }
- else if (Array.isArray(val)) {
- // Get unique types from the array (by converting to string and putting in a Set)
- const typesAsStrings = Array.from(new Set(val.map(v => JSON.stringify(guessSpecifierType(v)))));
- const types = typesAsStrings.map(ts => (/^{/.test(ts) ? JSON.parse(ts) : ts));
- return {
- type: elmTypes_1.ELM_LIST_TYPE_SPECIFIER,
- elementType: types.length == 1 ? types[0] : { type: elmTypes_1.ELM_CHOICE_TYPE_SPECIFIER, choice: types }
- };
- }
- else if (val.isInterval) {
- return {
- type: elmTypes_1.ELM_INTERVAL_TYPE_SPECIFIER,
- pointType: val.pointType
- };
- }
- else if (typeof val === 'object' && Object.keys(val).length > 0) {
- return {
- type: elmTypes_1.ELM_TUPLE_TYPE_SPECIFIER,
- element: Object.keys(val).map(k => ({ name: k, elementType: guessSpecifierType(val[k]) }))
- };
- }
- return 'Unknown';
-}
-class IntervalTypeSpecifier extends expression_1.UnimplementedExpression {
-}
-exports.IntervalTypeSpecifier = IntervalTypeSpecifier;
-class ListTypeSpecifier extends expression_1.UnimplementedExpression {
-}
-exports.ListTypeSpecifier = ListTypeSpecifier;
-class NamedTypeSpecifier extends expression_1.UnimplementedExpression {
-}
-exports.NamedTypeSpecifier = NamedTypeSpecifier;
-class TupleTypeSpecifier extends expression_1.UnimplementedExpression {
-}
-exports.TupleTypeSpecifier = TupleTypeSpecifier;
-
-},{"../datatypes/clinical":6,"../datatypes/datetime":8,"../datatypes/interval":10,"../datatypes/quantity":12,"../datatypes/ratio":13,"../datatypes/uncertainty":14,"../util/elmTypes":55,"../util/math":58,"../util/util":60,"./expression":23}],43:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.UnfilteredContext = exports.PatientContext = exports.Context = void 0;
-const dt = __importStar(require("../datatypes/datatypes"));
-const exception_1 = require("../datatypes/exception");
-const elmTypes_1 = require("../util/elmTypes");
-const util_1 = require("../util/util");
-const messageListeners_1 = require("./messageListeners");
-class Context {
- constructor(parent, _codeService, _parameters, executionDateTime, messageListener) {
- this.parent = parent;
- this._codeService = _codeService;
- this.context_values = {};
- this.library_context = {};
- this.localId_context = {};
- this.evaluatedRecords = [];
- // TODO: If there is an issue with number of parameters look into cql4browsers fix: 387ea77538182833283af65e6341e7a05192304c
- this.checkParameters(_parameters ?? {}); // not crazy about possibly throwing an error in a constructor, but...
- this._parameters = _parameters || {};
- this.executionDateTime = executionDateTime;
- this.messageListener = messageListener;
- }
- get parameters() {
- return this._parameters || (this.parent && this.parent.parameters);
- }
- set parameters(params) {
- this.checkParameters(params);
- this._parameters = params;
- }
- get codeService() {
- return this._codeService || (this.parent && this.parent.codeService);
- }
- set codeService(cs) {
- this._codeService = cs;
- }
- withParameters(params) {
- this.parameters = params || {};
- return this;
- }
- withCodeService(cs) {
- this.codeService = cs;
- return this;
- }
- rootContext() {
- if (this.parent) {
- return this.parent.rootContext();
- }
- else {
- return this;
- }
- }
- async findRecords(profile, retrieveDetails) {
- return this.parent && this.parent.findRecords(profile, retrieveDetails);
- }
- childContext(context_values) {
- const ctx = new Context(this);
- ctx.context_values = context_values ?? {};
- return ctx;
- }
- getLibraryContext(library) {
- return this.parent && this.parent.getLibraryContext(library);
- }
- getLocalIdContext(localId) {
- return this.parent && this.parent.getLocalIdContext(localId);
- }
- getParameter(name) {
- return this.parent && this.parent.getParameter(name);
- }
- getParentParameter(name) {
- if (this.parent) {
- if (this.parent.parameters[name] != null) {
- return this.parent.parameters[name];
- }
- else {
- return this.parent.getParentParameter(name);
- }
- }
- }
- getTimezoneOffset() {
- if (this.executionDateTime != null) {
- return this.executionDateTime.timezoneOffset;
- }
- else if (this.parent && this.parent.getTimezoneOffset != null) {
- return this.parent.getTimezoneOffset();
- }
- else {
- throw new exception_1.Exception('No Timezone Offset has been set');
- }
- }
- getExecutionDateTime() {
- if (this.executionDateTime != null) {
- return this.executionDateTime;
- }
- else if (this.parent && this.parent.getExecutionDateTime != null) {
- return this.parent.getExecutionDateTime();
- }
- else {
- throw new exception_1.Exception('No Execution DateTime has been set');
- }
- }
- getMessageListener() {
- if (this.messageListener != null) {
- return this.messageListener;
- }
- else if (this.parent && this.parent.getMessageListener != null) {
- return this.parent.getMessageListener();
- }
- else {
- return new messageListeners_1.NullMessageListener();
- }
- }
- getValueSet(name, library) {
- return this.parent && this.parent.getValueSet(name, library);
- }
- getCodeSystem(name, libraryName) {
- return this.parent && this.parent.getCodeSystem(name, libraryName);
- }
- getCode(name) {
- return this.parent && this.parent.getCode(name);
- }
- getConcept(name) {
- return this.parent && this.parent.getConcept(name);
- }
- getFunction(name) {
- return this.parent && this.parent.getFunction(name);
- }
- get(identifier) {
- // Check for undefined because if its null, we actually *do* want to return null (rather than
- // looking at parent), but if it's really undefined, *then* look at the parent
- if (typeof this.context_values[identifier] !== 'undefined') {
- return this.context_values[identifier];
- }
- else if (identifier === '$this') {
- return this.context_values;
- }
- else {
- return this.parent != null && this.parent.get(identifier);
- }
- }
- set(identifier, value) {
- this.context_values[identifier] = value;
- }
- setLocalIdWithResult(localId, value) {
- // Temporary fix. Real fix will be to return a list of all result values for a given localId.
- const ctx = this.localId_context[localId];
- if (ctx === false || ctx === null || ctx === undefined || ctx.length === 0) {
- this.localId_context[localId] = value;
- }
- }
- getLocalIdResult(localId) {
- return this.localId_context[localId];
- }
- // Returns an object of objects containing each library name
- // with the localIds and result values
- getAllLocalIds() {
- const localIdResults = {};
- // Add the localIds and result values from the main library
- localIdResults[this.parent.source.library.identifier.id] = {};
- localIdResults[this.parent.source.library.identifier.id] = this.localId_context;
- // Iterate over support libraries and store localIds
- for (const libName in this.library_context) {
- const lib = this.library_context[libName];
- this.supportLibraryLocalIds(lib, localIdResults);
- }
- return localIdResults;
- }
- // Recursive function that will grab nested support library localId results
- supportLibraryLocalIds(lib, localIdResults) {
- // Set library identifier name as the key and the object of localIds with their results as the value
- // if it already exists then we need to merge the results instead of overwriting
- if (localIdResults[lib.library.source.library.identifier.id] != null) {
- this.mergeLibraryLocalIdResults(localIdResults, lib.library.source.library.identifier.id, lib.localId_context);
- }
- else {
- localIdResults[lib.library.source.library.identifier.id] = lib.localId_context;
- }
- // Iterate over any support libraries in the current support library
- Object.values(lib.library_context).forEach(supportLib => {
- this.supportLibraryLocalIds(supportLib, localIdResults);
- });
- }
- // Merges the localId results for a library into the already collected results. The logic used for which result
- // to keep is the same as the logic used above in setLocalIdWithResult, "falsey" results are always replaced.
- mergeLibraryLocalIdResults(localIdResults, libraryId, libraryResults) {
- for (const localId in libraryResults) {
- const localIdResult = libraryResults[localId];
- const existingResult = localIdResults[libraryId][localId];
- // overwrite this localid result if the existing result is "falsey". future work could track all results for each localid
- if (existingResult === false ||
- existingResult === null ||
- existingResult === undefined ||
- existingResult.length === 0) {
- localIdResults[libraryId][localId] = localIdResult;
- }
- }
- }
- checkParameters(params) {
- for (const pName in params) {
- const pVal = params[pName];
- const pDef = this.getParameter(pName);
- if (pVal == null) {
- return; // Null can theoretically be any type
- }
- if (typeof pDef === 'undefined') {
- return; // This will happen if the parameter is declared in a different (included) library
- }
- else if (pDef.parameterTypeSpecifier != null &&
- !this.matchesTypeSpecifier(pVal, pDef.parameterTypeSpecifier)) {
- throw new Error(`Passed in parameter '${pName}' is wrong type`);
- }
- else if (pDef['default'] != null && !this.matchesInstanceType(pVal, pDef['default'])) {
- throw new Error(`Passed in parameter '${pName}' is wrong type`);
- }
- }
- return true;
- }
- matchesTypeSpecifier(val, spec) {
- switch (spec.type) {
- case elmTypes_1.ELM_NAMED_TYPE_SPECIFIER:
- return this.matchesNamedTypeSpecifier(val, spec);
- case elmTypes_1.ELM_LIST_TYPE_SPECIFIER:
- return this.matchesListTypeSpecifier(val, spec);
- case elmTypes_1.ELM_TUPLE_TYPE_SPECIFIER:
- return this.matchesTupleTypeSpecifier(val, spec);
- case elmTypes_1.ELM_INTERVAL_TYPE_SPECIFIER:
- return this.matchesIntervalTypeSpecifier(val, spec);
- case elmTypes_1.ELM_CHOICE_TYPE_SPECIFIER:
- return this.matchesChoiceTypeSpecifier(val, spec);
- default:
- return true; // default to true when we don't know
- }
- }
- matchesListTypeSpecifier(val, spec) {
- return ((0, util_1.typeIsArray)(val) && val.every(x => this.matchesTypeSpecifier(x, spec.elementType)));
- }
- matchesTupleTypeSpecifier(val, spec) {
- // TODO: Spec is not clear about exactly how tuples should be matched
- return (val != null &&
- typeof val === 'object' &&
- !(0, util_1.typeIsArray)(val) &&
- !val.isInterval &&
- !val.isConcept &&
- !val.isCode &&
- !val.isDateTime &&
- !val.isDate &&
- !val.isQuantity &&
- spec.element.every((x) => typeof val[x.name] === 'undefined' ||
- this.matchesTypeSpecifier(val[x.name], x.elementType)));
- }
- matchesIntervalTypeSpecifier(val, spec) {
- return (val.isInterval &&
- (val.low == null || this.matchesTypeSpecifier(val.low, spec.pointType)) &&
- (val.high == null || this.matchesTypeSpecifier(val.high, spec.pointType)));
- }
- matchesChoiceTypeSpecifier(val, spec) {
- return spec.choice.some((c) => this.matchesTypeSpecifier(val, c));
- }
- matchesNamedTypeSpecifier(val, spec) {
- if (val == null) {
- return true;
- }
- switch (spec.name) {
- case elmTypes_1.ELM_BOOLEAN_TYPE:
- return typeof val === 'boolean';
- case elmTypes_1.ELM_DECIMAL_TYPE:
- return typeof val === 'number';
- case elmTypes_1.ELM_INTEGER_TYPE:
- return typeof val === 'number' && Math.floor(val) === val;
- case elmTypes_1.ELM_LONG_TYPE:
- return typeof val === 'bigint';
- case elmTypes_1.ELM_STRING_TYPE:
- return typeof val === 'string';
- case elmTypes_1.ELM_CONCEPT_TYPE:
- return val && val.isConcept;
- case '{urn:hl7-org:elm-types:r1}Code':
- return val && val.isCode;
- case elmTypes_1.ELM_DATETIME_TYPE:
- return val && val.isDateTime;
- case elmTypes_1.ELM_DATE_TYPE:
- return val && val.isDate;
- case elmTypes_1.ELM_QUANTITY_TYPE:
- return val && val.isQuantity;
- case elmTypes_1.ELM_TIME_TYPE:
- return val && val.isTime && val.isTime();
- default:
- // Use the data model's implementation of _is, if it is available
- if (typeof val._is === 'function') {
- return val._is(spec);
- }
- // If the value is an array or interval, then we assume it cannot be cast to a
- // named type. Technically, this is not 100% true because a modelinfo can define
- // a named type whose base type is a list or interval. But none of our models
- // (FHIR, QDM, QICore) do that, so for those models, this approach will always be
- // correct.
- if (Array.isArray(val) || val.isInterval) {
- return false;
- }
- // Otherwise just default to true to match legacy behavior.
- //
- // NOTE: This is also where arbitrary tuples land because they will not have
- // an "is" function and we don't encode the type information into the runtime
- // objects so we can't easily determine their type. We can't reject them,
- // else things like `Encounter{ id: "1" } is Encounter` would return false.
- // So for now we allow false positives in order to avoid false negatives.
- return true;
- }
- }
- matchesInstanceType(val, inst) {
- if (inst.isBooleanLiteral) {
- return typeof val === 'boolean';
- }
- else if (inst.isDecimalLiteral) {
- return typeof val === 'number';
- }
- else if (inst.isIntegerLiteral) {
- return typeof val === 'number' && Math.floor(val) === val;
- }
- else if (inst.isLongLiteral) {
- return typeof val === 'bigint';
- }
- else if (inst.isStringLiteral) {
- return typeof val === 'string';
- }
- else if (inst.isCode) {
- return val && val.isCode;
- }
- else if (inst.isConcept) {
- return val && val.isConcept;
- }
- else if (inst.isTime && inst.isTime()) {
- return val && val.isTime && val.isTime();
- }
- else if (inst.isDate) {
- return val && val.isDate;
- }
- else if (inst.isDateTime) {
- return val && val.isDateTime;
- }
- else if (inst.isQuantity) {
- return val && val.isQuantity;
- }
- else if (inst.isList) {
- return this.matchesListInstanceType(val, inst);
- }
- else if (inst.isTuple) {
- return this.matchesTupleInstanceType(val, inst);
- }
- else if (inst.isInterval) {
- return this.matchesIntervalInstanceType(val, inst);
- }
- return true; // default to true when we don't know for sure
- }
- matchesListInstanceType(val, list) {
- return ((0, util_1.typeIsArray)(val) && val.every(x => this.matchesInstanceType(x, list.elements[0])));
- }
- matchesTupleInstanceType(val, tpl) {
- return (typeof val === 'object' &&
- !(0, util_1.typeIsArray)(val) &&
- tpl.elements.every((x) => typeof val[x.name] === 'undefined' || this.matchesInstanceType(val[x.name], x.value)));
- }
- matchesIntervalInstanceType(val, ivl) {
- const pointType = ivl.low != null ? ivl.low : ivl.high;
- return (val.isInterval &&
- (val.low == null || this.matchesInstanceType(val.low, pointType)) &&
- (val.high == null || this.matchesInstanceType(val.high, pointType)));
- }
-}
-exports.Context = Context;
-class PatientContext extends Context {
- constructor(library, patient, codeService, parameters, executionDateTime = dt.DateTime.fromJSDate(new Date()), messageListener = new messageListeners_1.NullMessageListener()) {
- super(library, codeService, parameters, executionDateTime, messageListener);
- this.library = library;
- this.patient = patient;
- }
- rootContext() {
- return this;
- }
- getLibraryContext(library) {
- if (this.library_context[library] == null) {
- this.library_context[library] = new PatientContext(this.get(library), this.patient, this.codeService, this.parameters, this.executionDateTime, this.messageListener);
- }
- return this.library_context[library];
- }
- getLocalIdContext(localId) {
- if (this.localId_context[localId] == null) {
- this.localId_context[localId] = new PatientContext(this.get(localId), this.patient, this.codeService, this.parameters, this.executionDateTime, this.messageListener);
- }
- return this.localId_context[localId];
- }
- async findRecords(profile, retrieveDetails) {
- return this.patient && this.patient.findRecords(profile, retrieveDetails);
- }
-}
-exports.PatientContext = PatientContext;
-class UnfilteredContext extends Context {
- constructor(library, results, codeService, parameters, executionDateTime = dt.DateTime.fromJSDate(new Date()), messageListener = new messageListeners_1.NullMessageListener()) {
- super(library, codeService, parameters, executionDateTime, messageListener);
- this.library = library;
- this.results = results;
- }
- rootContext() {
- return this;
- }
- async findRecords(_template) {
- throw new exception_1.Exception('Retrieves are not currently supported in Unfiltered Context');
- }
- getLibraryContext(_library) {
- throw new exception_1.Exception('Library expressions are not currently supported in Unfiltered Context');
- }
- get(identifier) {
- //First check to see if the identifier is a unfiltered context expression that has already been cached
- if (this.context_values[identifier]) {
- return this.context_values[identifier];
- }
- //if not look to see if the library has a unfiltered expression of that identifier
- if (this.library.expressions[identifier] &&
- this.library.expressions[identifier].context === 'Unfiltered') {
- return this.library.expressions[identifier];
- }
- //lastly attempt to gather all patient level results that have that identifier
- // should this compact null values before return ?
- return Object.values(this.results.patientResults).map((pr) => pr[identifier]);
- }
-}
-exports.UnfilteredContext = UnfilteredContext;
-
-},{"../datatypes/datatypes":7,"../datatypes/exception":9,"../util/elmTypes":55,"../util/util":60,"./messageListeners":45}],44:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Executor = void 0;
-const messageListeners_1 = require("./messageListeners");
-const results_1 = require("./results");
-const context_1 = require("./context");
-class Executor {
- constructor(library, codeService, parameters, messageListener = new messageListeners_1.NullMessageListener()) {
- this.library = library;
- this.codeService = codeService;
- this.parameters = parameters;
- this.messageListener = messageListener;
- }
- withLibrary(lib) {
- this.library = lib;
- return this;
- }
- withParameters(params) {
- this.parameters = params != null ? params : {};
- return this;
- }
- withCodeService(cs) {
- this.codeService = cs;
- return this;
- }
- withMessageListener(ml) {
- this.messageListener = ml;
- return this;
- }
- async exec_expression(expression, patientSource, executionDateTime) {
- const r = new results_1.Results();
- const expr = this.library.expressions[expression];
- if (expr != null) {
- // NOTE: Using await to support async data providers whose implementations return promise
- // await has no effect on functions that don't return promises, so it is safe to use in all cases
- let currentPatient = await patientSource.currentPatient();
- while (currentPatient) {
- const patient_ctx = new context_1.PatientContext(this.library, currentPatient, this.codeService, this.parameters, executionDateTime, this.messageListener);
- r.recordPatientResults(patient_ctx, { [expression]: await expr.execute(patient_ctx) });
- currentPatient = await patientSource.nextPatient();
- }
- }
- return r;
- }
- async exec(patientSource, executionDateTime) {
- const r = await this.exec_patient_context(patientSource, executionDateTime);
- const unfilteredContext = new context_1.UnfilteredContext(this.library, r, this.codeService, this.parameters, executionDateTime, this.messageListener);
- const resultMap = {};
- for (const key in this.library.expressions) {
- const expr = this.library.expressions[key];
- if (expr.context === 'Unfiltered') {
- resultMap[key] = await expr.exec(unfilteredContext);
- }
- }
- r.recordUnfilteredResults(resultMap);
- return r;
- }
- async exec_patient_context(patientSource, executionDateTime) {
- const r = new results_1.Results();
- // NOTE: Using await to support async data providers whose implementations return promise
- // await has no effect on functions that don't return promises, so it is safe to use in all cases
- let currentPatient = await patientSource.currentPatient();
- while (currentPatient) {
- const patient_ctx = new context_1.PatientContext(this.library, currentPatient, this.codeService, this.parameters, executionDateTime, this.messageListener);
- const resultMap = {};
- for (const key in this.library.expressions) {
- const expr = this.library.expressions[key];
- if (expr.context === 'Patient') {
- resultMap[key] = await expr.execute(patient_ctx);
- }
- }
- r.recordPatientResults(patient_ctx, resultMap);
- currentPatient = await patientSource.nextPatient();
- }
- return r;
- }
-}
-exports.Executor = Executor;
-
-},{"./context":43,"./messageListeners":45,"./results":47}],45:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ConsoleMessageListener = exports.NullMessageListener = void 0;
-class NullMessageListener {
- onMessage(_source, _code, _severity, _message) {
- // do nothing
- }
-}
-exports.NullMessageListener = NullMessageListener;
-class ConsoleMessageListener {
- constructor(logSourceOnTrace = false) {
- this.logSourceOnTrace = logSourceOnTrace;
- }
- onMessage(source, code, severity, message) {
- // eslint-disable-next-line no-console
- const print = severity === 'Error' ? console.error : console.log;
- let content = `${severity}: [${code}] ${message}`;
- if (severity === 'Trace' && this.logSourceOnTrace) {
- content += `\n<<<<< SOURCE:\n${JSON.stringify(source)}\n>>>>>`;
- }
- print(content);
- }
-}
-exports.ConsoleMessageListener = ConsoleMessageListener;
-
-},{}],46:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Repository = void 0;
-const library_1 = require("../elm/library");
-class Repository {
- constructor(data) {
- this.data = data;
- this.libraries = Array.from(Object.values(data));
- }
- resolve(path, version) {
- for (const lib of this.libraries) {
- if (lib.library && lib.library.identifier) {
- const { id, system, version: libraryVersion } = lib.library.identifier;
- const libraryUri = `${system}/${id}`;
- if (path === libraryUri || path === id) {
- if (version) {
- if (libraryVersion === version) {
- return new library_1.Library(lib, this);
- }
- }
- else {
- return new library_1.Library(lib, this);
- }
- }
- }
- }
- }
-}
-exports.Repository = Repository;
-
-},{"../elm/library":28}],47:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.Results = void 0;
-class Results {
- constructor() {
- this.patientResults = {};
- this.unfilteredResults = {};
- this.localIdPatientResultsMap = {};
- this.patientEvaluatedRecords = {};
- }
- // Expose an evaluatedRecords array for backwards compatibility
- get evaluatedRecords() {
- return [].concat(...Object.values(this.patientEvaluatedRecords));
- }
- recordPatientResults(patient_ctx, resultMap) {
- const p = patient_ctx.patient;
- // NOTE: From now on prefer getId() over id() because some data models may have an id property
- // that is not a string (e.g., FHIR) -- so reserve getId() for the API (and expect a string
- // representation) but leave id() for data-model specific formats.
- const patientId = typeof p.getId === 'function' ? p.getId() : p.id();
- // Record the results
- this.patientResults[patientId] = resultMap;
- // Record the local IDs
- this.localIdPatientResultsMap[patientId] = patient_ctx.getAllLocalIds();
- // Record the evaluatedRecords, merging with an aggregated array across all libraries
- this.patientEvaluatedRecords[patientId] = [...patient_ctx.evaluatedRecords];
- Object.values(patient_ctx.library_context).forEach((ctx) => {
- this.patientEvaluatedRecords[patientId].push(...ctx.evaluatedRecords);
- });
- }
- recordUnfilteredResults(resultMap) {
- this.unfilteredResults = resultMap;
- }
-}
-exports.Results = Results;
-
-},{}],48:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-
-},{}],49:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-
-},{}],50:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-__exportStar(require("./cql-code-service.interfaces"), exports);
-__exportStar(require("./cql-patient.interfaces"), exports);
-__exportStar(require("./runtime.types"), exports);
-__exportStar(require("./type-specifiers.interfaces"), exports);
-
-},{"./cql-code-service.interfaces":48,"./cql-patient.interfaces":49,"./runtime.types":51,"./type-specifiers.interfaces":52}],51:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-
-},{}],52:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-
-},{}],53:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.lessThan = lessThan;
-exports.lessThanOrEquals = lessThanOrEquals;
-exports.greaterThan = greaterThan;
-exports.greaterThanOrEquals = greaterThanOrEquals;
-exports.equivalent = equivalent;
-exports.equals = equals;
-const uncertainty_1 = require("../datatypes/uncertainty");
-function areNumbers(a, b) {
- return typeof a === 'number' && typeof b === 'number';
-}
-function areBigInts(a, b) {
- return typeof a === 'bigint' && typeof b === 'bigint';
-}
-function areStrings(a, b) {
- return typeof a === 'string' && typeof b === 'string';
-}
-function areDateTimesOrQuantities(a, b) {
- return ((a && a.isDateTime && b && b.isDateTime) ||
- (a && a.isDate && b && b.isDate) ||
- (a && a.isQuantity && b && b.isQuantity));
-}
-function isUncertainty(x) {
- return x instanceof uncertainty_1.Uncertainty;
-}
-function lessThan(a, b, precision) {
- if (areNumbers(a, b) || areBigInts(a, b) || areStrings(a, b)) {
- return a < b;
- }
- else if (areDateTimesOrQuantities(a, b)) {
- return a.before(b, precision);
- }
- else if (isUncertainty(a)) {
- return a.lessThan(b, precision);
- }
- else if (isUncertainty(b)) {
- return uncertainty_1.Uncertainty.from(a).lessThan(b, precision);
- }
- else {
- return null;
- }
-}
-function lessThanOrEquals(a, b, precision) {
- if (areNumbers(a, b) || areBigInts(a, b) || areStrings(a, b)) {
- return a <= b;
- }
- else if (areDateTimesOrQuantities(a, b)) {
- return a.sameOrBefore(b, precision);
- }
- else if (isUncertainty(a)) {
- return a.lessThanOrEquals(b, precision);
- }
- else if (isUncertainty(b)) {
- return uncertainty_1.Uncertainty.from(a).lessThanOrEquals(b, precision);
- }
- else {
- return null;
- }
-}
-function greaterThan(a, b, precision) {
- if (areNumbers(a, b) || areBigInts(a, b) || areStrings(a, b)) {
- return a > b;
- }
- else if (areDateTimesOrQuantities(a, b)) {
- return a.after(b, precision);
- }
- else if (isUncertainty(a)) {
- return a.greaterThan(b, precision);
- }
- else if (isUncertainty(b)) {
- return uncertainty_1.Uncertainty.from(a).greaterThan(b, precision);
- }
- else {
- return null;
- }
-}
-function greaterThanOrEquals(a, b, precision) {
- if (areNumbers(a, b) || areBigInts(a, b) || areStrings(a, b)) {
- return a >= b;
- }
- else if (areDateTimesOrQuantities(a, b)) {
- return a.sameOrAfter(b, precision);
- }
- else if (isUncertainty(a)) {
- return a.greaterThanOrEquals(b, precision);
- }
- else if (isUncertainty(b)) {
- return uncertainty_1.Uncertainty.from(a).greaterThanOrEquals(b, precision);
- }
- else {
- return null;
- }
-}
-function equivalent(a, b) {
- if (a == null && b == null) {
- return true;
- }
- if (a == null || b == null) {
- return false;
- }
- if (isCode(a)) {
- return codesAreEquivalent(a, b);
- }
- // Quantity equivalence is the same as Quantity equality
- if (a.isQuantity) {
- return a.equals(b);
- }
- // Use overloaded 'equivalent' function if it is available
- if (typeof a.equivalent === 'function') {
- return a.equivalent(b);
- }
- const [aClass, bClass] = getClassOfObjects(a, b);
- switch (aClass) {
- case '[object Array]':
- return compareEveryItemInArrays(a, b, equivalent);
- case '[object Object]':
- return compareObjects(a, b, equivalent);
- case '[object String]':
- // Make sure b is also a string
- if (bClass === '[object String]') {
- // String equivalence is case- and locale insensitive
- a = a.replace(/\s/g, ' ');
- b = b.replace(/\s/g, ' ');
- return a.localeCompare(b, 'en', { sensitivity: 'base' }) === 0;
- }
- break;
- }
- return equals(a, b);
-}
-function isCode(object) {
- return object.hasMatch && typeof object.hasMatch === 'function';
-}
-function codesAreEquivalent(code1, code2) {
- return code1.hasMatch(code2);
-}
-function getClassOfObjects(object1, object2) {
- return [object1, object2].map(obj => ({}).toString.call(obj));
-}
-function compareEveryItemInArrays(array1, array2, comparisonFunction) {
- return (array1.length === array2.length &&
- array1.every((item, i) => comparisonFunction(item, array2[i])));
-}
-function compareObjects(a, b, comparisonFunction) {
- if (!classesEqual(a, b)) {
- return false;
- }
- return deepCompareKeysAndValues(a, b, comparisonFunction);
-}
-function classesEqual(object1, object2) {
- return object2 instanceof object1.constructor && object1 instanceof object2.constructor;
-}
-function deepCompareKeysAndValues(a, b, comparisonFunction) {
- let finalComparisonResult;
- const aKeys = getKeysFromObject(a).sort();
- const bKeys = getKeysFromObject(b).sort();
- // Array.every() will only return true or false, so set a flag for if we should return null
- let shouldReturnNull = false;
- // Check if both arrays of keys are the same length and key names match
- if (aKeys.length === bKeys.length && aKeys.every((value, index) => value === bKeys[index])) {
- finalComparisonResult = aKeys.every(key => {
- // if both are null we should return true to satisfy ignoring empty values in tuples
- if (a[key] == null && b[key] == null) {
- return true;
- }
- const comparisonResult = comparisonFunction(a[key], b[key]);
- if (comparisonResult === null) {
- shouldReturnNull = true;
- return true;
- }
- return comparisonResult;
- });
- }
- else {
- finalComparisonResult = false;
- }
- if (finalComparisonResult && shouldReturnNull) {
- return null;
- }
- return finalComparisonResult;
-}
-function getKeysFromObject(object) {
- return Object.keys(object).filter(k => !isFunction(object[k]));
-}
-function isFunction(input) {
- return input instanceof Function || {}.toString.call(input) === '[object Function]';
-}
-function equals(a, b) {
- // Handle null cases first: spec says if either is null, return null
- if (a == null || b == null) {
- return null;
- }
- // If one is a Quantity, use the Quantity equals function
- if (a && a.isQuantity) {
- return a.equals(b);
- }
- // If one is a Ratio, use the ratio equals function
- if (a && a.isRatio) {
- return a.equals(b);
- }
- // If one is an Uncertainty, convert the other to an Uncertainty
- if (a instanceof uncertainty_1.Uncertainty) {
- b = uncertainty_1.Uncertainty.from(b);
- }
- else if (b instanceof uncertainty_1.Uncertainty) {
- a = uncertainty_1.Uncertainty.from(a);
- }
- // Use overloaded 'equals' function if it is available
- if (typeof a.equals === 'function') {
- return a.equals(b);
- }
- // Return true of the objects are primitives and are strictly equal
- if ((typeof a === typeof b && typeof a === 'string') ||
- typeof a === 'number' ||
- typeof a === 'bigint' ||
- typeof a === 'boolean') {
- return a === b;
- }
- // Return false if they are instances of different classes
- const [aClass, bClass] = getClassOfObjects(a, b);
- if (aClass !== bClass) {
- return false;
- }
- switch (aClass) {
- case '[object Date]':
- // Compare the ms since epoch
- return a.getTime() === b.getTime();
- case '[object RegExp]':
- // Compare the components of the regular expression
- return ['source', 'global', 'ignoreCase', 'multiline'].every(p => a[p] === b[p]);
- case '[object Array]':
- if (a.indexOf(null) >= 0 ||
- a.indexOf(undefined) >= 0 ||
- b.indexOf(null) >= 0 ||
- b.indexOf(undefined) >= 0) {
- return null;
- }
- return compareEveryItemInArrays(a, b, equals);
- case '[object Object]':
- return compareObjects(a, b, equals);
- case '[object Function]':
- return a.toString() === b.toString();
- }
- // If we made it this far, we can't handle it
- return false;
-}
-
-},{"../datatypes/uncertainty":14}],54:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.AnnotatedError = void 0;
-/**
- * A custom error that holds additional information and a more explicit message
- * to simplify tracking down errors that occur during execution
- */
-class AnnotatedError extends Error {
- constructor(originalError, expressionName, libraryName, localId, locator) {
- super(`Encountered unexpected error during execution.\n\n\tError Message:\t${originalError.message}\n\tCQL Library:\t${libraryName}\n\tExpression:\t${expressionName}${localId ? `\n\tELM Local ID:\t${localId}` : ''}${locator ? `\n\tCQL Locator:\t${locator}` : ''}\n`);
- this.expressionName = expressionName;
- this.libraryName = libraryName;
- this.localId = localId;
- this.locator = locator;
- this.cause = originalError;
- }
-}
-exports.AnnotatedError = AnnotatedError;
-
-},{}],55:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ELM_CHOICE_TYPE_SPECIFIER = exports.ELM_INTERVAL_TYPE_SPECIFIER = exports.ELM_TUPLE_TYPE_SPECIFIER = exports.ELM_LIST_TYPE_SPECIFIER = exports.ELM_NAMED_TYPE_SPECIFIER = exports.ELM_TIME_TYPE = exports.ELM_STRING_TYPE = exports.ELM_QUANTITY_TYPE = exports.ELM_LONG_TYPE = exports.ELM_INTEGER_TYPE = exports.ELM_DECIMAL_TYPE = exports.ELM_DATETIME_TYPE = exports.ELM_DATE_TYPE = exports.ELM_CONCEPT_TYPE = exports.ELM_BOOLEAN_TYPE = exports.ELM_ANY_TYPE = void 0;
-// Simple Types
-exports.ELM_ANY_TYPE = '{urn:hl7-org:elm-types:r1}Any';
-exports.ELM_BOOLEAN_TYPE = '{urn:hl7-org:elm-types:r1}Boolean';
-exports.ELM_CONCEPT_TYPE = '{urn:hl7-org:elm-types:r1}Concept';
-exports.ELM_DATE_TYPE = '{urn:hl7-org:elm-types:r1}Date';
-exports.ELM_DATETIME_TYPE = '{urn:hl7-org:elm-types:r1}DateTime';
-exports.ELM_DECIMAL_TYPE = '{urn:hl7-org:elm-types:r1}Decimal';
-exports.ELM_INTEGER_TYPE = '{urn:hl7-org:elm-types:r1}Integer';
-exports.ELM_LONG_TYPE = '{urn:hl7-org:elm-types:r1}Long';
-exports.ELM_QUANTITY_TYPE = '{urn:hl7-org:elm-types:r1}Quantity';
-exports.ELM_STRING_TYPE = '{urn:hl7-org:elm-types:r1}String';
-exports.ELM_TIME_TYPE = '{urn:hl7-org:elm-types:r1}Time';
-// Type Specifiers
-exports.ELM_NAMED_TYPE_SPECIFIER = 'NamedTypeSpecifier';
-exports.ELM_LIST_TYPE_SPECIFIER = 'ListTypeSpecifier';
-exports.ELM_TUPLE_TYPE_SPECIFIER = 'TupleTypeSpecifier';
-exports.ELM_INTERVAL_TYPE_SPECIFIER = 'IntervalTypeSpecifier';
-exports.ELM_CHOICE_TYPE_SPECIFIER = 'ChoiceTypeSpecifier';
-
-},{}],56:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.toNormalizedKey = void 0;
-const ucum = __importStar(require("@lhncbc/ucum-lhc"));
-const immutable_1 = require("immutable");
-const datatypes_1 = require("../datatypes/datatypes");
-const math_1 = require("./math");
-const units_1 = require("./units");
-const ucumUtilInstance = ucum.UcumLhcUtils.getInstance();
-/**
- * Provide a unique key for an object to be used for value equality
- * A key is normalized such that representations for quantities, dates, intervals, etc. are comparable.
- */
-const toNormalizedKey = (js) => {
- // This is necessary because of the oddities of CQL
- // It allows ignoring non-set values in tuples to be compared correctly with set as null values in tuples
- if (js === null || js === undefined) {
- return null;
- }
- // Handle the edge case of functions
- if (typeof js === 'function') {
- return (0, immutable_1.Map)({
- name: js.toString(),
- __instance: 'JS.Function'
- });
- }
- // Simple return non-objects
- if (typeof js !== 'object') {
- return js;
- }
- // Handle objects - normalize as necessary to generate unique keys
- switch (js.constructor) {
- case Array:
- return (0, immutable_1.Seq)(js)
- .map((x) => (0, exports.toNormalizedKey)(x))
- .toList();
- case datatypes_1.Code:
- return (0, immutable_1.Map)({
- code: (0, exports.toNormalizedKey)(js.code),
- system: (0, exports.toNormalizedKey)(js.system),
- version: (0, exports.toNormalizedKey)(js.version),
- display: (0, exports.toNormalizedKey)(js.display),
- __instance: js.constructor
- });
- case Date:
- return (0, immutable_1.Map)({
- epochMs: js.getTime(),
- __instance: js.constructor
- });
- case datatypes_1.DateTime:
- if (typeof js.timezoneOffset === 'number' && js.timezoneOffset !== 0) {
- return (0, immutable_1.Seq)(js.convertToTimezoneOffset(0))
- .map((x) => (0, exports.toNormalizedKey)(x))
- .toMap()
- .set('__instance', js.constructor);
- }
- else {
- return (0, immutable_1.Seq)(js)
- .map((x) => (0, exports.toNormalizedKey)(x))
- .toMap()
- .set('__instance', js.constructor);
- }
- case datatypes_1.Interval:
- return (0, immutable_1.Seq)(js.toClosed())
- .map((x) => (0, exports.toNormalizedKey)(x))
- .toMap()
- .set('__instance', js.constructor);
- case datatypes_1.Quantity:
- if (!js.unit) {
- return (0, immutable_1.Map)({
- value: js.value ?? null,
- unit: null,
- __instance: js.constructor
- });
- }
- // Get the normalized base unit
- const baseUnitKey = ucumUtilInstance.commensurablesList(js.unit)[0];
- if (!baseUnitKey) {
- // No units found - normalization not possible and use provided values
- return (0, immutable_1.Map)({
- value: js.value ?? null,
- unit: js.unit ?? null,
- __instance: js.constructor
- });
- }
- else {
- // Unit was found - convert to baseUnit and normalize
- const baseUnitKeyCode = baseUnitKey[0].csCode_;
- const conversionValue = (0, units_1.convertUnit)(js.value, js.unit, baseUnitKeyCode);
- const finalValue = conversionValue ? (0, math_1.decimalAdjust)('round', conversionValue, -8) : null;
- return (0, immutable_1.Map)({
- value: finalValue ?? null,
- unit: baseUnitKeyCode ?? null,
- __instance: js.constructor
- });
- }
- case datatypes_1.Ratio:
- return (0, immutable_1.Map)({
- numerator: (0, exports.toNormalizedKey)(js.numerator),
- denominator: (0, exports.toNormalizedKey)(js.denominator),
- __instance: js.constructor
- });
- case RegExp:
- return (0, immutable_1.Map)({
- source: (0, exports.toNormalizedKey)(js.source),
- global: (0, exports.toNormalizedKey)(js.global),
- ignoreCase: (0, exports.toNormalizedKey)(js.ignoreCase),
- multiline: (0, exports.toNormalizedKey)(js.multiline),
- __instance: js.constructor
- });
- case datatypes_1.Uncertainty:
- if (js.isPoint()) {
- return (0, exports.toNormalizedKey)(js.low);
- }
- else {
- return (0, immutable_1.Seq)(js)
- .map((x) => (0, exports.toNormalizedKey)(x))
- .toMap()
- .set('__instance', js.constructor);
- }
- default:
- // If the object is a model object (e.g. FHIRObject) with a _typeHierarchy function,
- // then use the typeHierarchy information for the __instance value.
- // Otherwise, use the constructor for the __instance value.
- return (0, immutable_1.Seq)(js)
- .map((x) => (0, exports.toNormalizedKey)(x))
- .toMap()
- .set('__instance', (0, exports.toNormalizedKey)(js._typeHierarchy?.()) ?? js.constructor);
- }
-};
-exports.toNormalizedKey = toNormalizedKey;
-
-},{"../datatypes/datatypes":7,"./math":58,"./units":59,"@lhncbc/ucum-lhc":71,"immutable":75}],57:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.MAX_TIME_VALUE_STRING = exports.MIN_TIME_VALUE_STRING = exports.MAX_DATE_VALUE_STRING = exports.MIN_DATE_VALUE_STRING = exports.MAX_DATETIME_VALUE_STRING = exports.MIN_DATETIME_VALUE_STRING = exports.MIN_FLOAT_PRECISION_VALUE = exports.MIN_FLOAT_VALUE = exports.MAX_FLOAT_VALUE = exports.MIN_LONG_VALUE = exports.MAX_LONG_VALUE = exports.MIN_INT_VALUE = exports.MAX_INT_VALUE = void 0;
-// Keep primitive limits and temporal limit literals dependency-free so datatype and utility
-// modules can safely share them without introducing circular module initialization.
-exports.MAX_INT_VALUE = Math.pow(2, 31) - 1; // 2147483647
-exports.MIN_INT_VALUE = Math.pow(-2, 31); // -2147483648
-exports.MAX_LONG_VALUE = 9223372036854775807n;
-exports.MIN_LONG_VALUE = -9223372036854775808n;
-exports.MAX_FLOAT_VALUE = 99999999999999999999.99999999;
-exports.MIN_FLOAT_VALUE = -99999999999999999999.99999999;
-exports.MIN_FLOAT_PRECISION_VALUE = Math.pow(10, -8);
-// The constructed min/max Date/DateTime/Time are exported from src/datatypes/datetime.ts
-exports.MIN_DATETIME_VALUE_STRING = '0001-01-01T00:00:00.000';
-exports.MAX_DATETIME_VALUE_STRING = '9999-12-31T23:59:59.999';
-exports.MIN_DATE_VALUE_STRING = '0001-01-01';
-exports.MAX_DATE_VALUE_STRING = '9999-12-31';
-exports.MIN_TIME_VALUE_STRING = '0000-01-01T00:00:00.000';
-exports.MAX_TIME_VALUE_STRING = '0000-01-01T23:59:59.999';
-
-},{}],58:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.OverFlowException = void 0;
-exports.overflowsOrUnderflows = overflowsOrUnderflows;
-exports.isValidInteger = isValidInteger;
-exports.isValidLong = isValidLong;
-exports.isValidDecimal = isValidDecimal;
-exports.add = add;
-exports.subtract = subtract;
-exports.limitDecimalPrecision = limitDecimalPrecision;
-exports.successor = successor;
-exports.predecessor = predecessor;
-exports.maxValueForType = maxValueForType;
-exports.minValueForType = minValueForType;
-exports.decimalAdjust = decimalAdjust;
-exports.decimalOrNull = decimalOrNull;
-exports.decimalLongOrNull = decimalLongOrNull;
-const exception_1 = require("../datatypes/exception");
-const quantity_1 = require("../datatypes/quantity");
-const datetime_1 = require("../datatypes/datetime");
-const uncertainty_1 = require("../datatypes/uncertainty");
-const elmTypes_1 = require("./elmTypes");
-const limits_1 = require("./limits");
-const units_1 = require("./units");
-function overflowsOrUnderflows(value, type) {
- if (value == null) {
- return false;
- }
- if (value.isQuantity) {
- if (!isValidDecimal(value.value)) {
- return true;
- }
- }
- else if (value.isTime && value.isTime()) {
- if (value.after(datetime_1.MAX_TIME_VALUE)) {
- return true;
- }
- if (value.before(datetime_1.MIN_TIME_VALUE)) {
- return true;
- }
- }
- else if (value.isDateTime) {
- if (value.after(datetime_1.MAX_DATETIME_VALUE)) {
- return true;
- }
- if (value.before(datetime_1.MIN_DATETIME_VALUE)) {
- return true;
- }
- }
- else if (value.isDate) {
- if (value.after(datetime_1.MAX_DATE_VALUE)) {
- return true;
- }
- if (value.before(datetime_1.MIN_DATE_VALUE)) {
- return true;
- }
- }
- else if (typeof value === 'bigint') {
- if (!isValidLong(value)) {
- return true;
- }
- }
- else if (typeof value === 'number') {
- // Only consider it an integer if it looks like an integer (even if the type says it's an integer).
- // We need to do this because the CQL-to-ELM Translator's implementation of Power may incorrectly tag
- // a result as an Integer when it really is a decimal (e.g., when the exponent is a negative number).
- const isInteger = Number.isInteger(value) && (type === elmTypes_1.ELM_INTEGER_TYPE || type == null);
- if (isInteger) {
- if (!isValidInteger(value)) {
- return true;
- }
- }
- else if (!isValidDecimal(value)) {
- return true;
- }
- }
- else if (value.isUncertainty) {
- return overflowsOrUnderflows(value.low, type) || overflowsOrUnderflows(value.high, type);
- }
- return false;
-}
-function isValidInteger(integer) {
- if (!Number.isInteger(integer)) {
- return false;
- }
- if (integer > limits_1.MAX_INT_VALUE) {
- return false;
- }
- if (integer < limits_1.MIN_INT_VALUE) {
- return false;
- }
- return true;
-}
-function isValidLong(long) {
- if (typeof long !== 'bigint') {
- return false;
- }
- if (long > limits_1.MAX_LONG_VALUE) {
- return false;
- }
- if (long < limits_1.MIN_LONG_VALUE) {
- return false;
- }
- return true;
-}
-function isValidDecimal(decimal) {
- if (isNaN(decimal)) {
- return false;
- }
- if (typeof decimal !== 'number') {
- return false;
- }
- if (decimal > limits_1.MAX_FLOAT_VALUE) {
- return false;
- }
- if (decimal < limits_1.MIN_FLOAT_VALUE) {
- return false;
- }
- return true;
-}
-function add(a, b, type) {
- if (a == null || b == null) {
- return null;
- }
- if (a?.isUncertainty || b?.isUncertainty) {
- const aLow = a?.isUncertainty ? a.low : a;
- const aHigh = a?.isUncertainty ? a.high : a;
- const bLow = b?.isUncertainty ? b.low : b;
- const bHigh = b?.isUncertainty ? b.high : b;
- const low = add(aLow, bLow, type);
- const high = add(aHigh, bHigh, type);
- return low == null || high == null ? null : new uncertainty_1.Uncertainty(low, high);
- }
- if (typeof a === 'bigint') {
- const sum = a + (typeof b === 'bigint' ? b : BigInt(b));
- return overflowsOrUnderflows(sum, elmTypes_1.ELM_LONG_TYPE) ? null : sum;
- }
- if (typeof b === 'bigint') {
- const sum = BigInt(a) + b;
- return overflowsOrUnderflows(sum, elmTypes_1.ELM_LONG_TYPE) ? null : sum;
- }
- if (typeof a === 'number' && typeof b === 'number') {
- const sum = a + b;
- const numberType = type ?? (Number.isInteger(a) && Number.isInteger(b) ? elmTypes_1.ELM_INTEGER_TYPE : elmTypes_1.ELM_DECIMAL_TYPE);
- return overflowsOrUnderflows(sum, numberType) ? null : sum;
- }
- if (a?.isQuantity && b?.isQuantity) {
- const [aValue, aUnit, bValue, bUnit] = (0, units_1.normalizeUnitsWhenPossible)(a.value, a.unit, b.value, b.unit);
- if (aUnit !== bUnit) {
- return null;
- }
- const sum = aValue + bValue;
- return overflowsOrUnderflows(sum, elmTypes_1.ELM_DECIMAL_TYPE) ? null : new quantity_1.Quantity(sum, aUnit);
- }
- if (b?.isQuantity && (a?.isDate || a?.isDateTime || (a?.isTime && a.isTime()))) {
- const unit = (0, units_1.convertToCQLDateUnit)(b.unit) || b.unit;
- const sum = a.copy().add(b.value, unit);
- return overflowsOrUnderflows(sum) ? null : sum;
- }
- throw new Error('Unsupported argument types.');
-}
-function subtract(a, b, type) {
- if (a == null || b == null) {
- return null;
- }
- if (a?.isUncertainty || b?.isUncertainty) {
- const aLow = a?.isUncertainty ? a.low : a;
- const aHigh = a?.isUncertainty ? a.high : a;
- const bLow = b?.isUncertainty ? b.low : b;
- const bHigh = b?.isUncertainty ? b.high : b;
- const low = subtract(aLow, bHigh, type);
- const high = subtract(aHigh, bLow, type);
- return low == null || high == null ? null : new uncertainty_1.Uncertainty(low, high);
- }
- if (typeof b === 'number' || typeof b === 'bigint') {
- return add(a, -b, type);
- }
- if (b?.isQuantity) {
- return add(a, { isQuantity: true, value: -b.value, unit: b.unit }, type);
- }
- throw new Error('Unsupported argument types.');
-}
-function limitDecimalPrecision(val) {
- if (val == null) {
- return val;
- }
- else if (typeof val === 'number') {
- return (Math.round(val * Math.pow(10, 8)) / Math.pow(10, 8));
- }
- else if (val.isQuantity) {
- return new quantity_1.Quantity(limitDecimalPrecision(val.value), val.unit);
- }
- else if (val.isUncertainty) {
- return new uncertainty_1.Uncertainty(limitDecimalPrecision(val.low), limitDecimalPrecision(val.high));
- }
- return val;
-}
-class OverFlowException extends exception_1.Exception {
-}
-exports.OverFlowException = OverFlowException;
-function successor(val, type, precision) {
- if (typeof val === 'number') {
- const isInteger = type === elmTypes_1.ELM_INTEGER_TYPE || (type == null && Number.isInteger(val));
- if (isInteger) {
- if (val >= limits_1.MAX_INT_VALUE) {
- throw new OverFlowException();
- }
- else {
- return val + 1;
- }
- }
- else {
- if (val >= limits_1.MAX_FLOAT_VALUE) {
- throw new OverFlowException();
- }
- else {
- return val + limits_1.MIN_FLOAT_PRECISION_VALUE;
- }
- }
- }
- else if (typeof val === 'bigint') {
- if (val >= limits_1.MAX_LONG_VALUE) {
- throw new OverFlowException();
- }
- else {
- return val + 1n;
- }
- }
- else if (val && val.isTime && val.isTime()) {
- if (val.sameAs(datetime_1.MAX_TIME_VALUE)) {
- throw new OverFlowException();
- }
- else {
- return val.successor(precision);
- }
- }
- else if (val && val.isDateTime) {
- if (val.sameAs(datetime_1.MAX_DATETIME_VALUE)) {
- throw new OverFlowException();
- }
- else {
- return val.successor(precision);
- }
- }
- else if (val && val.isDate) {
- if (val.sameAs(datetime_1.MAX_DATE_VALUE)) {
- throw new OverFlowException();
- }
- else {
- return val.successor(precision);
- }
- }
- else if (val && val.isUncertainty) {
- // For uncertainties, if the high is the max val, don't increment it
- const high = (() => {
- try {
- return successor(val.high, type, precision);
- }
- catch {
- return val.high;
- }
- })();
- return new uncertainty_1.Uncertainty(successor(val.low, type, precision), high);
- }
- else if (val && val.isQuantity) {
- const succ = val.clone();
- succ.value = successor(val.value, elmTypes_1.ELM_DECIMAL_TYPE);
- return succ;
- }
- else if (val == null) {
- return null;
- }
-}
-function predecessor(val, type, precision) {
- if (typeof val === 'number') {
- const isInteger = type === elmTypes_1.ELM_INTEGER_TYPE || (type == null && Number.isInteger(val));
- if (isInteger) {
- if (val <= limits_1.MIN_INT_VALUE) {
- throw new OverFlowException();
- }
- else {
- return val - 1;
- }
- }
- else {
- if (val <= limits_1.MIN_FLOAT_VALUE) {
- throw new OverFlowException();
- }
- else {
- return val - limits_1.MIN_FLOAT_PRECISION_VALUE;
- }
- }
- }
- else if (typeof val === 'bigint') {
- if (val <= limits_1.MIN_LONG_VALUE) {
- throw new OverFlowException();
- }
- else {
- return val - 1n;
- }
- }
- else if (val && val.isTime && val.isTime()) {
- if (val.sameAs(datetime_1.MIN_TIME_VALUE)) {
- throw new OverFlowException();
- }
- else {
- return val.predecessor(precision);
- }
- }
- else if (val && val.isDateTime) {
- if (val.sameAs(datetime_1.MIN_DATETIME_VALUE)) {
- throw new OverFlowException();
- }
- else {
- return val.predecessor(precision);
- }
- }
- else if (val && val.isDate) {
- if (val.sameAs(datetime_1.MIN_DATE_VALUE)) {
- throw new OverFlowException();
- }
- else {
- return val.predecessor(precision);
- }
- }
- else if (val && val.isUncertainty) {
- // For uncertainties, if the low is the min val, don't decrement it
- const low = (() => {
- try {
- return predecessor(val.low, type, precision);
- }
- catch {
- return val.low;
- }
- })();
- return new uncertainty_1.Uncertainty(low, predecessor(val.high, type, precision));
- }
- else if (val && val.isQuantity) {
- const pred = val.clone();
- pred.value = predecessor(val.value, elmTypes_1.ELM_DECIMAL_TYPE);
- return pred;
- }
- else if (val == null) {
- return null;
- }
-}
-function maxValueForType(type, quantityInstance) {
- switch (type) {
- case elmTypes_1.ELM_INTEGER_TYPE:
- return limits_1.MAX_INT_VALUE;
- case elmTypes_1.ELM_LONG_TYPE:
- return limits_1.MAX_LONG_VALUE;
- case elmTypes_1.ELM_DECIMAL_TYPE:
- return limits_1.MAX_FLOAT_VALUE;
- case elmTypes_1.ELM_DATETIME_TYPE:
- return datetime_1.MAX_DATETIME_VALUE?.copy();
- case elmTypes_1.ELM_DATE_TYPE:
- return datetime_1.MAX_DATE_VALUE?.copy();
- case elmTypes_1.ELM_TIME_TYPE:
- return datetime_1.MAX_TIME_VALUE?.copy();
- case elmTypes_1.ELM_QUANTITY_TYPE: {
- // Although the spec says max Quantity has unit '1', it doesn't make sense to change the unit,
- // especially if this is being used in the context of an interval or uncertainty since the
- // left and right sides need to be comparable in those cases.
- // See: https://jira.hl7.org/browse/FHIR-57935
- return new quantity_1.Quantity(limits_1.MAX_FLOAT_VALUE, quantityInstance?.unit || '1');
- }
- }
- return null;
-}
-function minValueForType(type, quantityInstance) {
- switch (type) {
- case elmTypes_1.ELM_INTEGER_TYPE:
- return limits_1.MIN_INT_VALUE;
- case elmTypes_1.ELM_LONG_TYPE:
- return limits_1.MIN_LONG_VALUE;
- case elmTypes_1.ELM_DECIMAL_TYPE:
- return limits_1.MIN_FLOAT_VALUE;
- case elmTypes_1.ELM_DATETIME_TYPE:
- return datetime_1.MIN_DATETIME_VALUE?.copy();
- case elmTypes_1.ELM_DATE_TYPE:
- return datetime_1.MIN_DATE_VALUE?.copy();
- case elmTypes_1.ELM_TIME_TYPE:
- return datetime_1.MIN_TIME_VALUE?.copy();
- case elmTypes_1.ELM_QUANTITY_TYPE: {
- // Although the spec says max Quantity has unit '1', it doesn't make sense to change the unit,
- // especially if this is being used in the context of an interval or uncertainty since the
- // left and right sides need to be comparable in those cases.
- // See: https://jira.hl7.org/browse/FHIR-57935
- return new quantity_1.Quantity(limits_1.MIN_FLOAT_VALUE, quantityInstance?.unit || '1');
- }
- }
- return null;
-}
-function decimalAdjust(type, value, exp) {
- //If the exp is undefined or zero...
- if (typeof exp === 'undefined' || +exp === 0) {
- return Math[type](value);
- }
- value = +value;
- exp = +exp;
- //If the value is not a number or the exp is not an integer...
- if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
- return NaN;
- }
- //Shift
- value = value.toString().split('e');
- let v = value[1] ? +value[1] - exp : -exp;
- value = Math[type](+(value[0] + 'e' + v));
- //Shift back
- value = value.toString().split('e');
- v = value[1] ? +value[1] + exp : exp;
- return +(value[0] + 'e' + v);
-}
-function decimalOrNull(value) {
- return isValidDecimal(value) ? value : null;
-}
-function decimalLongOrNull(value) {
- return (typeof value === 'number' && isValidDecimal(value)) ||
- (typeof value === 'bigint' && isValidLong(value))
- ? value
- : null;
-}
-
-},{"../datatypes/datetime":8,"../datatypes/exception":9,"../datatypes/quantity":12,"../datatypes/uncertainty":14,"./elmTypes":55,"./limits":57,"./units":59}],59:[function(require,module,exports){
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.checkUnit = checkUnit;
-exports.convertUnit = convertUnit;
-exports.normalizeUnitsWhenPossible = normalizeUnitsWhenPossible;
-exports.convertToCQLDateUnit = convertToCQLDateUnit;
-exports.compareUnits = compareUnits;
-exports.getProductOfUnits = getProductOfUnits;
-exports.getQuotientOfUnits = getQuotientOfUnits;
-const ucum = __importStar(require("@lhncbc/ucum-lhc"));
-const math_1 = require("./math");
-const utils = ucum.UcumLhcUtils.getInstance();
-// The CQL specification says that dates are based on the Gregorian calendar, so CQL-based year and month
-// identifiers will be matched to the UCUM gregorian units. See http://unitsofmeasure.org/ucum.html#para-31
-const CQL_TO_UCUM_DATE_UNITS = {
- years: 'a_g',
- year: 'a_g',
- months: 'mo_g',
- month: 'mo_g',
- weeks: 'wk',
- week: 'wk',
- days: 'd',
- day: 'd',
- hours: 'h',
- hour: 'h',
- minutes: 'min',
- minute: 'min',
- seconds: 's',
- second: 's',
- milliseconds: 'ms',
- millisecond: 'ms'
-};
-const UCUM_TO_CQL_DATE_UNITS = {
- a: 'year',
- a_j: 'year',
- a_g: 'year',
- mo: 'month',
- mo_j: 'month',
- mo_g: 'month',
- wk: 'week',
- d: 'day',
- h: 'hour',
- min: 'minute',
- s: 'second',
- ms: 'millisecond'
-};
-// Cache Map for unit validity results so we dont have to go to ucum-lhc for every check.
-const unitValidityCache = new Map();
-function checkUnit(unit, allowEmptyUnits = true, allowCQLDateUnits = true) {
- if (allowEmptyUnits) {
- unit = fixEmptyUnit(unit);
- }
- if (allowCQLDateUnits) {
- unit = fixCQLDateUnit(unit);
- }
- if (!unitValidityCache.has(unit)) {
- const result = utils.validateUnitString(unit, true);
- if (result.status === 'valid') {
- unitValidityCache.set(unit, { valid: true });
- }
- else {
- let msg = `Invalid UCUM unit: '${unit}'.`;
- if (result.ucumCode != null) {
- msg += ` Did you mean '${result.ucumCode}'?`;
- }
- unitValidityCache.set(unit, { valid: false, message: msg });
- }
- }
- return unitValidityCache.get(unit);
-}
-function convertUnit(fromVal, fromUnit, toUnit, adjustPrecision = true) {
- [fromUnit, toUnit] = [fromUnit, toUnit].map(fixUnit);
- const result = utils.convertUnitTo(fixUnit(fromUnit), fromVal, fixUnit(toUnit));
- if (result.status !== 'succeeded') {
- return;
- }
- // note: convert result.toVal to number (by prefixing +) to keep typescript happy
- return adjustPrecision ? (0, math_1.decimalAdjust)('round', result.toVal, -8) : +result.toVal;
-}
-function normalizeUnitsWhenPossible(val1, unit1, val2, unit2) {
- // If both units are CQL date units, return CQL date units
- const useCQLDateUnits = unit1 in CQL_TO_UCUM_DATE_UNITS && unit2 in CQL_TO_UCUM_DATE_UNITS;
- const resultConverter = (unit) => {
- return useCQLDateUnits ? convertToCQLDateUnit(unit) : unit;
- };
- [unit1, unit2] = [unit1, unit2].map(u => fixUnit(u));
- if (unit1 === unit2) {
- return [val1, unit1, val2, unit2];
- }
- const baseUnit1 = getBaseUnitAndPower(unit1)[0];
- const baseUnit2 = getBaseUnitAndPower(unit2)[0];
- const [newVal2, newUnit2] = convertToBaseUnit(val2, unit2, baseUnit1);
- if (newVal2 == null) {
- // it was not convertible, so just return the quantities as-is
- return [val1, resultConverter(unit1), val2, resultConverter(unit2)];
- }
- // If the new val2 > old val2, return since we prefer conversion to smaller units
- if (newVal2 >= val2) {
- return [val1, resultConverter(unit1), newVal2, resultConverter(newUnit2)];
- }
- // else it was a conversion to a larger unit, so go the other way around
- const [newVal1, newUnit1] = convertToBaseUnit(val1, unit1, baseUnit2);
- if (newVal1 == null) {
- // this should not happen since we established they are convertible, but just in case...
- return [val1, resultConverter(unit1), newVal2, resultConverter(newUnit2)];
- }
- return [newVal1, resultConverter(newUnit1), val2, resultConverter(unit2)];
-}
-function convertToCQLDateUnit(unit) {
- let dateUnit;
- if (unit in CQL_TO_UCUM_DATE_UNITS) {
- // it's already a CQL unit, so return it as-is, removing trailing 's' if necessary (e.g., years -> year)
- dateUnit = unit.replace(/s$/, '');
- }
- else if (unit in UCUM_TO_CQL_DATE_UNITS) {
- dateUnit = UCUM_TO_CQL_DATE_UNITS[unit];
- }
- return dateUnit;
-}
-function compareUnits(unit1, unit2) {
- try {
- const c = convertUnit(1, unit1, unit2);
- if (c && c > 1) {
- // unit1 is bigger (less precise)
- return 1;
- }
- else if (c && c < 1) {
- // unit1 is smaller
- return -1;
- }
- //units are the same
- return 0;
- }
- catch {
- return null;
- }
-}
-function getProductOfUnits(unit1, unit2) {
- [unit1, unit2] = [unit1, unit2].map(fixEmptyUnit);
- if (!checkUnit(unit1).valid || !checkUnit(unit2).valid) {
- return null;
- }
- // If either unit contains a divisor,combine the numerators and denominators, then divide
- if (unit1.indexOf('/') >= 0 || unit2.indexOf('/') >= 0) {
- // NOTE: We're not trying to get perfection on unit simplification, but doing what is reasonable
- const match1 = unit1.match(/([^/]*)(\/(.*))?/);
- const match2 = unit2.match(/([^/]*)(\/(.*))?/);
- // In the previous regexes, numerator is match[1], denominator is match[3]
- const newNum = getProductOfUnits(match1[1], match2[1]);
- const newDen = getProductOfUnits(match1[3], match2[3]);
- return getQuotientOfUnits(newNum, newDen);
- }
- // Get all the individual units being combined, accounting for multipliers (e.g., 'm.L'),
- // and then group like base units to combine powers (and remove '1's since they are no-ops)
- // e.g., 'm.L' * 'm' ==> { m: 2, L: 1}; 'm.L' * '1' ==> { m: 1, L: 1 }; '1' : '1' ==> { }
- const factorPowerMap = new Map();
- const factors = [...unit1.split('.'), ...unit2.split('.')];
- factors.forEach(factor => {
- const [baseUnit, power] = getBaseUnitAndPower(factor);
- if (baseUnit === '1' || power === 0) {
- // skip factors that are 1 since 1 * N is N.
- return;
- }
- const accumulatedPower = (factorPowerMap.get(baseUnit) || 0) + power;
- factorPowerMap.set(baseUnit, accumulatedPower);
- });
- // Loop through the factor map, rebuilding each factor w/ combined power and join them all
- // back via the multiplier '.', treating a final '' (no non-1 units) as '1'
- // e.g., { m: 2, L: 1 } ==> 'm2.L'
- return fixUnit(Array.from(factorPowerMap.entries())
- .map(([base, power]) => `${base}${power > 1 ? power : ''}`)
- .join('.'));
-}
-function getQuotientOfUnits(unit1, unit2) {
- [unit1, unit2] = [unit1, unit2].map(fixEmptyUnit);
- if (!checkUnit(unit1).valid || !checkUnit(unit2).valid) {
- return null;
- }
- // Try to simplify division when neither unit contains a divisor itself
- if (unit1.indexOf('/') === -1 && unit2.indexOf('/') === -1) {
- // Get all the individual units in numerator and denominator accounting for multipliers
- // (e.g., 'm.L'), and then group like base units to combine powers, inversing denominator
- // powers since they are being divided.
- // e.g., 'm3.L' / 'm' ==> { m: 2, L: -1}; 'm.L' / '1' ==> { m: 1, L: 1 }; '1' / '1' ==> { 1: 0 }
- const factorPowerMap = new Map();
- unit1.split('.').forEach((factor) => {
- const [baseUnit, power] = getBaseUnitAndPower(factor);
- const accumulatedPower = (factorPowerMap.get(baseUnit) || 0) + power;
- factorPowerMap.set(baseUnit, accumulatedPower);
- });
- unit2.split('.').forEach((factor) => {
- const [baseUnit, power] = getBaseUnitAndPower(factor);
- const accumulatedPower = (factorPowerMap.get(baseUnit) || 0) - power;
- factorPowerMap.set(baseUnit, accumulatedPower);
- });
- // Construct the numerator from factors with positive power, and denominator from factors
- // with negative power, filtering out base `1` and power 0 (which is also 1).
- // e.g. numerator: { m: 2, L: -2 } ==> 'm2'; { 1: 1, L: -1 } => ''
- // e.g. denominator: { m: 2, L: -2 } ==> 'L2'; { 1: 1, L: -1 } => 'L'
- const numerator = Array.from(factorPowerMap.entries())
- .filter(([base, power]) => base !== '1' && power > 0)
- .map(([base, power]) => `${base}${power > 1 ? power : ''}`)
- .join('.');
- let denominator = Array.from(factorPowerMap.entries())
- .filter(([base, power]) => base !== '1' && power < 0)
- .map(([base, power]) => `${base}${power < -1 ? power * -1 : ''}`)
- .join('.');
- // wrap the denominator in parentheses if necessary
- denominator = /[.]/.test(denominator) ? `(${denominator})` : denominator;
- return fixUnit(`${numerator}${denominator !== '' ? '/' + denominator : ''}`);
- }
- // One of the units had a divisor, so don't try to be too smart; just construct it from the parts
- if (unit1 === unit2) {
- // e.g. 'm/g' / 'm/g' ==> '1'
- return '1';
- }
- else if (unit2 === '1') {
- // e.g., 'm/g' / '1' ==> 'm/g/'
- return unit1;
- }
- else {
- // denominator is unit2, wrapped in parentheses if necessary
- const denominator = /[./]/.test(unit2) ? `(${unit2})` : unit2;
- if (unit1 === '1') {
- // e.g., '1' / 'm' ==> '/m'; '1' / 'm.g' ==> '/(m.g)'
- return `/${denominator}`;
- }
- // e.g., 'L' / 'm' ==> 'L/m'; 'L' / 'm.g' ==> 'L/(m.g)'
- return `${unit1}/${denominator}`;
- }
-}
-// UNEXPORTED FUNCTIONS
-function convertToBaseUnit(fromVal, fromUnit, toBaseUnit) {
- const fromPower = getBaseUnitAndPower(fromUnit)[1];
- const toUnit = fromPower === 1 ? toBaseUnit : `${toBaseUnit}${fromPower}`;
- const newVal = convertUnit(fromVal, fromUnit, toUnit);
- return newVal != null ? [newVal, toUnit] : [];
-}
-function getBaseUnitAndPower(unit) {
- // don't try to extract power from complex units (containing multipliers or divisors)
- if (/[./]/.test(unit)) {
- return [unit, 1];
- }
- unit = fixUnit(unit);
- let [term, power] = unit.match(/^(.*[^-\d])?([-]?\d*)$/).slice(1);
- if (term == null || term === '') {
- term = power;
- power = '1';
- }
- else if (power == null || power === '') {
- power = '1';
- }
- return [term, parseInt(power)];
-}
-function fixEmptyUnit(unit) {
- if (unit == null || (unit.trim && unit.trim() === '')) {
- return '1';
- }
- return unit;
-}
-function fixCQLDateUnit(unit) {
- return CQL_TO_UCUM_DATE_UNITS[unit] || unit;
-}
-function fixUnit(unit) {
- return fixCQLDateUnit(fixEmptyUnit(unit));
-}
-
-},{"./math":58,"@lhncbc/ucum-lhc":71}],60:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.jsDate = exports.typeIsArray = void 0;
-exports.removeNulls = removeNulls;
-exports.numerical_sort = numerical_sort;
-exports.isNull = isNull;
-exports.allTrue = allTrue;
-exports.anyTrue = anyTrue;
-exports.normalizeMillisecondsFieldInString = normalizeMillisecondsFieldInString;
-exports.normalizeMillisecondsField = normalizeMillisecondsField;
-exports.getTimezoneSeparatorFromString = getTimezoneSeparatorFromString;
-exports.asyncMergeSort = asyncMergeSort;
-exports.resolveValueSet = resolveValueSet;
-function removeNulls(things) {
- return things.filter(x => x != null);
-}
-function numerical_sort(things, direction) {
- return things.sort((a, b) => {
- if (direction == null || direction === 'asc' || direction === 'ascending') {
- return a - b;
- }
- else {
- return b - a;
- }
- });
-}
-function isNull(value) {
- return value === null;
-}
-exports.typeIsArray = Array.isArray || (value => ({}).toString.call(value) === '[object Array]');
-function allTrue(things) {
- if ((0, exports.typeIsArray)(things)) {
- return things.every(x => x);
- }
- else {
- return things;
- }
-}
-function anyTrue(things) {
- if ((0, exports.typeIsArray)(things)) {
- return things.some(x => x);
- }
- else {
- return things;
- }
-}
-//The export below is to make it easier if js Date is overwritten with CQL Date
-exports.jsDate = Date;
-function normalizeMillisecondsFieldInString(string, msString) {
- // TODO: verify we are only removing numeral digits
- let timezoneField;
- msString = normalizeMillisecondsField(msString);
- const [beforeMs, msAndAfter] = string.split('.');
- const timezoneSeparator = getTimezoneSeparatorFromString(msAndAfter);
- if (timezoneSeparator) {
- timezoneField = msAndAfter != null ? msAndAfter.split(timezoneSeparator)[1] : undefined;
- }
- if (timezoneField == null) {
- timezoneField = '';
- }
- return (string = beforeMs + '.' + msString + timezoneSeparator + timezoneField);
-}
-function normalizeMillisecondsField(msString) {
- // fix up milliseconds by padding zeros and/or truncating (5 --> 500, 50 --> 500, 54321 --> 543, etc.)
- return (msString = (msString + '00').substring(0, 3));
-}
-function getTimezoneSeparatorFromString(string) {
- if (string != null) {
- let matches = string.match(/-/);
- if (matches && matches.length === 1) {
- return '-';
- }
- matches = string.match(/\+/);
- if (matches && matches.length === 1) {
- return '+';
- }
- }
- return '';
-}
-async function asyncMergeSort(arr, compareFn) {
- if (arr.length <= 1) {
- return arr;
- }
- const midpoint = Math.floor(arr.length / 2);
- const left = await asyncMergeSort(arr.slice(0, midpoint), compareFn);
- const right = await asyncMergeSort(arr.slice(midpoint), compareFn);
- return merge(left, right, compareFn);
-}
-async function merge(left, right, compareFn) {
- const sorted = [];
- while (left.length > 0 && right.length > 0) {
- if ((await compareFn(left[0], right[0])) <= 0) {
- const sortedElem = left.shift();
- if (sortedElem !== undefined) {
- sorted.push(sortedElem);
- }
- }
- else {
- const sortedElem = right.shift();
- if (sortedElem !== undefined) {
- sorted.push(sortedElem);
- }
- }
- }
- return [...sorted, ...left, ...right];
-}
-async function resolveValueSet(vs, ctx) {
- // code service owns implementation of any valueset expansion caching
- const vsExpansion = await ctx.codeService.findValueSet(vs.id, vs.version);
- if (!vsExpansion) {
- throw new Error(`Unable to resolve expected valueset with id ${vs.id} and version ${vs.version}`);
- }
- return vsExpansion;
-}
-
-},{}],61:[function(require,module,exports){
-module.exports={"license":"The following data (prefixes and units) was generated by the UCUM LHC code from the UCUM data and selected LOINC combinations of UCUM units. The license for the UCUM LHC code (demo and library code as well as the combined units) is located at https://github.com/lhncbc/ucum-lhc/blob/LICENSE.md.","prefixes":{"config":["code_","ciCode_","name_","printSymbol_","value_","exp_"],"data":[["E","EX","exa","E",1000000000000000000,"18"],["G","GA","giga","G",1000000000,"9"],["Gi","GIB","gibi","Gi",1073741824,null],["Ki","KIB","kibi","Ki",1024,null],["M","MA","mega","M",1000000,"6"],["Mi","MIB","mebi","Mi",1048576,null],["P","PT","peta","P",1000000000000000,"15"],["T","TR","tera","T",1000000000000,"12"],["Ti","TIB","tebi","Ti",1099511627776,null],["Y","YA","yotta","Y",1e+24,"24"],["Z","ZA","zetta","Z",1e+21,"21"],["a","A","atto","a",1e-18,"-18"],["c","C","centi","c",0.01,"-2"],["d","D","deci","d",0.1,"-1"],["da","DA","deka","da",10,"1"],["f","F","femto","f",1e-15,"-15"],["h","H","hecto","h",100,"2"],["k","K","kilo","k",1000,"3"],["m","M","milli","m",0.001,"-3"],["n","N","nano","n",1e-9,"-9"],["p","P","pico","p",1e-12,"-12"],["u","U","micro","μ",0.000001,"-6"],["y","YO","yocto","y",1e-24,"-24"],["z","ZO","zepto","z",1e-21,"-21"]]},"units":{"config":["isBase_","name_","csCode_","ciCode_","property_","magnitude_",["dim_","dimVec_"],"printSymbol_","class_","isMetric_","variable_","cnv_","cnvPfx_","isSpecial_","isArbitrary_","moleExp_","equivalentExp_","synonyms_","source_","loincProperty_","category_","guidance_","csUnitString_","ciUnitString_","baseFactorStr_","baseFactor_","defError_"],"data":[[true,"meter","m","M","length",1,[1,0,0,0,0,0,0],"m",null,false,"L",null,1,false,false,0,0,"meters; metres; distance","UCUM","Len","Clinical","unit of length = 1.09361 yards",null,null,null,null,false],[true,"second - time","s","S","time",1,[0,1,0,0,0,0,0],"s",null,false,"T",null,1,false,false,0,0,"seconds","UCUM","Time","Clinical","",null,null,null,null,false],[true,"gram","g","G","mass",1,[0,0,1,0,0,0,0],"g",null,false,"M",null,1,false,false,0,0,"grams; gm","UCUM","Mass","Clinical","",null,null,null,null,false],[true,"radian","rad","RAD","plane angle",1,[0,0,0,1,0,0,0],"rad",null,false,"A",null,1,false,false,0,0,"radians","UCUM","Angle","Clinical","unit of angular measure where 1 radian = 1/2π turn = 57.296 degrees. ",null,null,null,null,false],[true,"degree Kelvin","K","K","temperature",1,[0,0,0,0,1,0,0],"K",null,false,"C",null,1,false,false,0,0,"Kelvin; degrees","UCUM","Temp","Clinical","absolute, thermodynamic temperature scale ",null,null,null,null,false],[true,"coulomb","C","C","electric charge",1,[0,0,0,0,0,1,0],"C",null,false,"Q",null,1,false,false,0,0,"coulombs","UCUM","","Clinical","defined as amount of 1 electron charge = 6.2415093×10^18 e, and equivalent to 1 Ampere-second",null,null,null,null,false],[true,"candela","cd","CD","luminous intensity",1,[0,0,0,0,0,0,1],"cd",null,false,"F",null,1,false,false,0,0,"candelas","UCUM","","Clinical","SI base unit of luminous intensity",null,null,null,null,false],[false,"the number ten for arbitrary powers","10*","10*","number",10,[0,0,0,0,0,0,0],"10","dimless",false,null,null,1,false,false,0,0,"10^; 10 to the arbitrary powers","UCUM","Num","Clinical","10* by itself is the same as 10, but users can add digits after the *. For example, 10*3 = 1000.","1","1","10",10,false],[false,"the number ten for arbitrary powers","10^","10^","number",10,[0,0,0,0,0,0,0],"10","dimless",false,null,null,1,false,false,0,0,"10*; 10 to the arbitrary power","UCUM","Num","Clinical","10* by itself is the same as 10, but users can add digits after the *. For example, 10*3 = 1000.","1","1","10",10,false],[false,"the number pi","[pi]","[PI]","number",3.141592653589793,[0,0,0,0,0,0,0],"π","dimless",false,null,null,1,false,false,0,0,"π","UCUM","","Constant","a mathematical constant; the ratio of a circle's circumference to its diameter ≈ 3.14159","1","1","3.1415926535897932384626433832795028841971693993751058209749445923",3.141592653589793,false],[false,"","%","%","fraction",0.01,[0,0,0,0,0,0,0],"%","dimless",false,null,null,1,false,false,0,0,"percents","UCUM","FR; NFR; MFR; CFR; SFR Rto; etc. ","Clinical","","10*-2","10*-2","1",1,false],[false,"parts per thousand","[ppth]","[PPTH]","fraction",0.001,[0,0,0,0,0,0,0],"ppth","dimless",false,null,null,1,false,false,0,0,"ppth; 10^-3","UCUM","MCnc; MCnt","Clinical","[ppth] is often used in solution concentrations as 1 g/L or 1 g/kg.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-3","10*-3","1",1,false],[false,"parts per million","[ppm]","[PPM]","fraction",0.000001,[0,0,0,0,0,0,0],"ppm","dimless",false,null,null,1,false,false,0,0,"ppm; 10^-6","UCUM","MCnt; MCnc; SFr","Clinical","[ppm] is often used in solution concentrations as 1 mg/L or 1 mg/kg. Also used to express mole fractions as 1 mmol/mol.\n\n[ppm] is also used in nuclear magnetic resonance (NMR) to represent chemical shift - the difference of a measured frequency in parts per million from the reference frequency.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-6","10*-6","1",1,false],[false,"parts per billion","[ppb]","[PPB]","fraction",1e-9,[0,0,0,0,0,0,0],"ppb","dimless",false,null,null,1,false,false,0,0,"ppb; 10^-9","UCUM","MCnt; MCnc; SFr","Clinical","[ppb] is often used in solution concentrations as 1 ug/L or 1 ug/kg. Also used to express mole fractions as 1 umol/mol.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-9","10*-9","1",1,false],[false,"parts per trillion","[pptr]","[PPTR]","fraction",1e-12,[0,0,0,0,0,0,0],"pptr","dimless",false,null,null,1,false,false,0,0,"pptr; 10^-12","UCUM","MCnt; MCnc; SFr","Clinical","[pptr] is often used in solution concentrations as 1 ng/L or 1 ng/kg. Also used to express mole fractions as 1 nmol/mol.\n\nCan be ambigous and would be better if the metric units was used directly. ","10*-12","10*-12","1",1,false],[false,"mole","mol","MOL","amount of substance",6.0221367e+23,[0,0,0,0,0,0,0],"mol","si",true,null,null,1,false,false,1,0,"moles","UCUM","Sub","Clinical","Measure the number of molecules ","10*23","10*23","6.0221367",6.0221367,false],[false,"steradian - solid angle","sr","SR","solid angle",1,[0,0,0,2,0,0,0],"sr","si",true,null,null,1,false,false,0,0,"square radian; rad2; rad^2","UCUM","Angle","Clinical","unit of solid angle in three-dimensional geometry analagous to radian; used in photometry which measures the perceived brightness of object by human eye (e.g. radiant intensity = watt/steradian)","rad2","RAD2","1",1,false],[false,"hertz","Hz","HZ","frequency",1,[0,-1,0,0,0,0,0],"Hz","si",true,null,null,1,false,false,0,0,"Herz; frequency; frequencies","UCUM","Freq; Num","Clinical","equal to one cycle per second","s-1","S-1","1",1,false],[false,"newton","N","N","force",1000,[1,-2,1,0,0,0,0],"N","si",true,null,null,1,false,false,0,0,"Newtons","UCUM","Force","Clinical","unit of force with base units kg.m/s2","kg.m/s2","KG.M/S2","1",1,false],[false,"pascal","Pa","PAL","pressure",1000,[-1,-2,1,0,0,0,0],"Pa","si",true,null,null,1,false,false,0,0,"pascals","UCUM","Pres","Clinical","standard unit of pressure equal to 1 newton per square meter (N/m2)","N/m2","N/M2","1",1,false],[false,"joule","J","J","energy",1000,[2,-2,1,0,0,0,0],"J","si",true,null,null,1,false,false,0,0,"joules","UCUM","Enrg","Clinical","unit of energy defined as the work required to move an object 1 m with a force of 1 N (N.m) or an electric charge of 1 C through 1 V (C.V), or to produce 1 W for 1 s (W.s) ","N.m","N.M","1",1,false],[false,"watt","W","W","power",1000,[2,-3,1,0,0,0,0],"W","si",true,null,null,1,false,false,0,0,"watts","UCUM","EngRat","Clinical","unit of power equal to 1 Joule per second (J/s) = kg⋅m2⋅s−3","J/s","J/S","1",1,false],[false,"Ampere","A","A","electric current",1,[0,-1,0,0,0,1,0],"A","si",true,null,null,1,false,false,0,0,"Amperes","UCUM","ElpotRat","Clinical","unit of electric current equal to flow rate of electrons equal to 6.2415×10^18 elementary charges moving past a boundary in one second or 1 Coulomb/second","C/s","C/S","1",1,false],[false,"volt","V","V","electric potential",1000,[2,-2,1,0,0,-1,0],"V","si",true,null,null,1,false,false,0,0,"volts","UCUM","Elpot","Clinical","unit of electric potential (voltage) = 1 Joule per Coulomb (J/C)","J/C","J/C","1",1,false],[false,"farad","F","F","electric capacitance",0.001,[-2,2,-1,0,0,2,0],"F","si",true,null,null,1,false,false,0,0,"farads; electric capacitance","UCUM","","Clinical","CGS unit of electric capacitance with base units C/V (Coulomb per Volt)","C/V","C/V","1",1,false],[false,"ohm","Ohm","OHM","electric resistance",1000,[2,-1,1,0,0,-2,0],"Ω","si",true,null,null,1,false,false,0,0,"Ω; resistance; ohms","UCUM","","Clinical","unit of electrical resistance with units of Volt per Ampere","V/A","V/A","1",1,false],[false,"siemens","S","SIE","electric conductance",0.001,[-2,1,-1,0,0,2,0],"S","si",true,null,null,1,false,false,0,0,"Reciprocal ohm; mho; Ω−1; conductance","UCUM","","Clinical","unit of electric conductance (the inverse of electrical resistance) equal to ohm^-1","Ohm-1","OHM-1","1",1,false],[false,"weber","Wb","WB","magnetic flux",1000,[2,-1,1,0,0,-1,0],"Wb","si",true,null,null,1,false,false,0,0,"magnetic flux; webers","UCUM","","Clinical","unit of magnetic flux equal to Volt second","V.s","V.S","1",1,false],[false,"degree Celsius","Cel","CEL","temperature",1,[0,0,0,0,1,0,0],"°C","si",true,null,"Cel",1,true,false,0,0,"°C; degrees","UCUM","Temp","Clinical","","K",null,null,1,false],[false,"tesla","T","T","magnetic flux density",1000,[0,-1,1,0,0,-1,0],"T","si",true,null,null,1,false,false,0,0,"Teslas; magnetic field","UCUM","","Clinical","SI unit of magnetic field strength for magnetic field B equal to 1 Weber/square meter = 1 kg/(s2*A)","Wb/m2","WB/M2","1",1,false],[false,"henry","H","H","inductance",1000,[2,0,1,0,0,-2,0],"H","si",true,null,null,1,false,false,0,0,"henries; inductance","UCUM","","Clinical","unit of electrical inductance; usually expressed in millihenrys (mH) or microhenrys (uH).","Wb/A","WB/A","1",1,false],[false,"lumen","lm","LM","luminous flux",1,[0,0,0,2,0,0,1],"lm","si",true,null,null,1,false,false,0,0,"luminous flux; lumens","UCUM","","Clinical","unit of luminous flux defined as 1 lm = 1 cd⋅sr (candela times sphere)","cd.sr","CD.SR","1",1,false],[false,"lux","lx","LX","illuminance",1,[-2,0,0,2,0,0,1],"lx","si",true,null,null,1,false,false,0,0,"illuminance; luxes","UCUM","","Clinical","unit of illuminance equal to one lumen per square meter. ","lm/m2","LM/M2","1",1,false],[false,"becquerel","Bq","BQ","radioactivity",1,[0,-1,0,0,0,0,0],"Bq","si",true,null,null,1,false,false,0,0,"activity; radiation; becquerels","UCUM","","Clinical","measure of the atomic radiation rate with units s^-1","s-1","S-1","1",1,false],[false,"gray","Gy","GY","energy dose",1,[2,-2,0,0,0,0,0],"Gy","si",true,null,null,1,false,false,0,0,"absorbed doses; ionizing radiation doses; kerma; grays","UCUM","EngCnt","Clinical","unit of ionizing radiation dose with base units of 1 joule of radiation energy per kilogram of matter","J/kg","J/KG","1",1,false],[false,"sievert","Sv","SV","dose equivalent",1,[2,-2,0,0,0,0,0],"Sv","si",true,null,null,1,false,false,0,0,"sieverts; radiation dose quantities; equivalent doses; effective dose; operational dose; committed dose","UCUM","","Clinical","SI unit for radiation dose equivalent equal to 1 Joule/kilogram.","J/kg","J/KG","1",1,false],[false,"degree - plane angle","deg","DEG","plane angle",0.017453292519943295,[0,0,0,1,0,0,0],"°","iso1000",false,null,null,1,false,false,0,0,"°; degree of arc; arc degree; arcdegree; angle","UCUM","Angle","Clinical","one degree is equivalent to π/180 radians.","[pi].rad/360","[PI].RAD/360","2",2,false],[false,"gon","gon","GON","plane angle",0.015707963267948967,[0,0,0,1,0,0,0],"□g","iso1000",false,null,null,1,false,false,0,0,"gon (grade); gons","UCUM","Angle","Nonclinical","unit of plane angle measurement equal to 1/400 circle","deg","DEG","0.9",0.9,false],[false,"arc minute","'","'","plane angle",0.0002908882086657216,[0,0,0,1,0,0,0],"'","iso1000",false,null,null,1,false,false,0,0,"arcminutes; arcmin; arc minutes; arc mins","UCUM","Angle","Clinical","equal to 1/60 degree; used in optometry and opthamology (e.g. visual acuity tests)","deg/60","DEG/60","1",1,false],[false,"arc second","''","''","plane angle",0.00000484813681109536,[0,0,0,1,0,0,0],"''","iso1000",false,null,null,1,false,false,0,0,"arcseconds; arcsecs","UCUM","Angle","Clinical","equal to 1/60 arcminute = 1/3600 degree; used in optometry and opthamology (e.g. visual acuity tests)","'/60","'/60","1",1,false],[false,"Liters","l","L","volume",0.001,[3,0,0,0,0,0,0],"l","iso1000",true,null,null,1,false,false,0,0,"cubic decimeters; decimeters cubed; decimetres; dm3; dm^3; litres; liters, LT ","UCUM","Vol","Clinical","Because lower case \"l\" can be read as the number \"1\", though this is a valid UCUM units. UCUM strongly reccomends using \"L\"","dm3","DM3","1",1,false],[false,"Liters","L","L","volume",0.001,[3,0,0,0,0,0,0],"L","iso1000",true,null,null,1,false,false,0,0,"cubic decimeters; decimeters cubed; decimetres; dm3; dm^3; litres; liters, LT ","UCUM","Vol","Clinical","Because lower case \"l\" can be read as the number \"1\", though this is a valid UCUM units. UCUM strongly reccomends using \"L\"","l",null,"1",1,false],[false,"are","ar","AR","area",100,[2,0,0,0,0,0,0],"a","iso1000",true,null,null,1,false,false,0,0,"100 m2; 100 m^2; 100 square meter; meters squared; metres","UCUM","Area","Clinical","metric base unit for area defined as 100 m^2","m2","M2","100",100,false],[false,"minute","min","MIN","time",60,[0,1,0,0,0,0,0],"min","iso1000",false,null,null,1,false,false,0,0,"minutes","UCUM","Time","Clinical","","s","S","60",60,false],[false,"hour","h","HR","time",3600,[0,1,0,0,0,0,0],"h","iso1000",false,null,null,1,false,false,0,0,"hours; hrs; age","UCUM","Time","Clinical","","min","MIN","60",60,false],[false,"day","d","D","time",86400,[0,1,0,0,0,0,0],"d","iso1000",false,null,null,1,false,false,0,0,"days; age; dy; 24 hours; 24 hrs","UCUM","Time","Clinical","","h","HR","24",24,false],[false,"tropical year","a_t","ANN_T","time",31556925.216,[0,1,0,0,0,0,0],"at","iso1000",false,null,null,1,false,false,0,0,"solar years; a tropical; years","UCUM","Time","Clinical","has an average of 365.242181 days but is constantly changing.","d","D","365.24219",365.24219,false],[false,"mean Julian year","a_j","ANN_J","time",31557600,[0,1,0,0,0,0,0],"aj","iso1000",false,null,null,1,false,false,0,0,"mean Julian yr; a julian; years","UCUM","Time","Clinical","has an average of 365.25 days, and in everyday use, has been replaced by the Gregorian year. However, this unit is used in astronomy to calculate light year. ","d","D","365.25",365.25,false],[false,"mean Gregorian year","a_g","ANN_G","time",31556952,[0,1,0,0,0,0,0],"ag","iso1000",false,null,null,1,false,false,0,0,"mean Gregorian yr; a gregorian; years","UCUM","Time","Clinical","has an average of 365.2425 days and is the most internationally used civil calendar.","d","D","365.2425",365.2425,false],[false,"year","a","ANN","time",31557600,[0,1,0,0,0,0,0],"a","iso1000",false,null,null,1,false,false,0,0,"years; a; yr, yrs; annum","UCUM","Time","Clinical","","a_j","ANN_J","1",1,false],[false,"week","wk","WK","time",604800,[0,1,0,0,0,0,0],"wk","iso1000",false,null,null,1,false,false,0,0,"weeks; wks","UCUM","Time","Clinical","","d","D","7",7,false],[false,"synodal month","mo_s","MO_S","time",2551442.976,[0,1,0,0,0,0,0],"mos","iso1000",false,null,null,1,false,false,0,0,"Moon; synodic month; lunar month; mo-s; mo s; months; moons","UCUM","Time","Nonclinical","has an average of 29.53 days per month, unit used in astronomy","d","D","29.53059",29.53059,false],[false,"mean Julian month","mo_j","MO_J","time",2629800,[0,1,0,0,0,0,0],"moj","iso1000",false,null,null,1,false,false,0,0,"mo-julian; mo Julian; months","UCUM","Time","Clinical","has an average of 30.435 days per month","a_j/12","ANN_J/12","1",1,false],[false,"mean Gregorian month","mo_g","MO_G","time",2629746,[0,1,0,0,0,0,0],"mog","iso1000",false,null,null,1,false,false,0,0,"months; month-gregorian; mo-gregorian","UCUM","Time","Clinical","has an average 30.436875 days per month and is from the most internationally used civil calendar.","a_g/12","ANN_G/12","1",1,false],[false,"month","mo","MO","time",2629800,[0,1,0,0,0,0,0],"mo","iso1000",false,null,null,1,false,false,0,0,"months; duration","UCUM","Time","Clinical","based on Julian calendar which has an average of 30.435 days per month (this unit is used in astronomy but not in everyday life - see mo_g)","mo_j","MO_J","1",1,false],[false,"metric ton","t","TNE","mass",1000000,[0,0,1,0,0,0,0],"t","iso1000",true,null,null,1,false,false,0,0,"tonnes; megagrams; tons","UCUM","Mass","Nonclinical","equal to 1000 kg used in the US (recognized by NIST as metric ton), and internationally (recognized as tonne)","kg","KG","1e3",1000,false],[false,"bar","bar","BAR","pressure",100000000,[-1,-2,1,0,0,0,0],"bar","iso1000",true,null,null,1,false,false,0,0,"bars","UCUM","Pres","Nonclinical","unit of pressure equal to 10^5 Pascals, primarily used by meteorologists and in weather forecasting","Pa","PAL","1e5",100000,false],[false,"unified atomic mass unit","u","AMU","mass",1.6605402e-24,[0,0,1,0,0,0,0],"u","iso1000",true,null,null,1,false,false,0,0,"unified atomic mass units; amu; Dalton; Da","UCUM","Mass","Clinical","the mass of 1/12 of an unbound Carbon-12 atom nuclide equal to 1.6606x10^-27 kg ","g","G","1.6605402e-24",1.6605402e-24,false],[false,"astronomic unit","AU","ASU","length",149597870691,[1,0,0,0,0,0,0],"AU","iso1000",false,null,null,1,false,false,0,0,"AU; units","UCUM","Len","Clinical","unit of length used in astronomy for measuring distance in Solar system","Mm","MAM","149597.870691",149597.870691,false],[false,"parsec","pc","PRS","length",30856780000000000,[1,0,0,0,0,0,0],"pc","iso1000",true,null,null,1,false,false,0,0,"parsecs","UCUM","Len","Clinical","unit of length equal to 3.26 light years, and used to measure large distances to objects outside our Solar System","m","M","3.085678e16",30856780000000000,false],[false,"velocity of light in a vacuum","[c]","[C]","velocity",299792458,[1,-1,0,0,0,0,0],"c","const",true,null,null,1,false,false,0,0,"speed of light","UCUM","Vel","Constant","equal to 299792458 m/s (approximately 3 x 10^8 m/s)","m/s","M/S","299792458",299792458,false],[false,"Planck constant","[h]","[H]","action",6.6260755e-31,[2,-1,1,0,0,0,0],"h","const",true,null,null,1,false,false,0,0,"Planck's constant","UCUM","","Constant","constant = 6.62607004 × 10-34 m2.kg/s; defined as quantum of action","J.s","J.S","6.6260755e-34",6.6260755e-34,false],[false,"Boltzmann constant","[k]","[K]","(unclassified)",1.380658e-20,[2,-2,1,0,-1,0,0],"k","const",true,null,null,1,false,false,0,0,"k; kB","UCUM","","Constant","physical constant relating energy at the individual particle level with temperature = 1.38064852 ×10^−23 J/K","J/K","J/K","1.380658e-23",1.380658e-23,false],[false,"permittivity of vacuum - electric","[eps_0]","[EPS_0]","electric permittivity",8.854187817000001e-15,[-3,2,-1,0,0,2,0],"ε0","const",true,null,null,1,false,false,0,0,"ε0; Electric Constant; vacuum permittivity; permittivity of free space ","UCUM","","Constant","approximately equal to 8.854 × 10^−12 F/m (farads per meter)","F/m","F/M","8.854187817e-12",8.854187817e-12,false],[false,"permeability of vacuum - magnetic","[mu_0]","[MU_0]","magnetic permeability",0.0012566370614359172,[1,0,1,0,0,-2,0],"μ0","const",true,null,null,1,false,false,0,0,"μ0; vacuum permeability; permeability of free space; magnetic constant","UCUM","","Constant","equal to 4π×10^−7 N/A2 (Newtons per square ampere) ≈ 1.2566×10^−6 H/m (Henry per meter)","N/A2","4.[PI].10*-7.N/A2","1",0.0000012566370614359173,false],[false,"elementary charge","[e]","[E]","electric charge",1.60217733e-19,[0,0,0,0,0,1,0],"e","const",true,null,null,1,false,false,0,0,"e; q; electric charges","UCUM","","Constant","the magnitude of the electric charge carried by a single electron or proton ≈ 1.60217×10^-19 Coulombs","C","C","1.60217733e-19",1.60217733e-19,false],[false,"electronvolt","eV","EV","energy",1.60217733e-16,[2,-2,1,0,0,0,0],"eV","iso1000",true,null,null,1,false,false,0,0,"Electron Volts; electronvolts","UCUM","Eng","Clinical","unit of kinetic energy = 1 V * 1.602×10^−19 C = 1.6×10−19 Joules","[e].V","[E].V","1",1,false],[false,"electron mass","[m_e]","[M_E]","mass",9.1093897e-28,[0,0,1,0,0,0,0],"me","const",true,null,null,1,false,false,0,0,"electron rest mass; me","UCUM","Mass","Constant","approximately equal to 9.10938356 × 10-31 kg; defined as the mass of a stationary electron","g","g","9.1093897e-28",9.1093897e-28,false],[false,"proton mass","[m_p]","[M_P]","mass",1.6726231e-24,[0,0,1,0,0,0,0],"mp","const",true,null,null,1,false,false,0,0,"mp; masses","UCUM","Mass","Constant","approximately equal to 1.672622×10−27 kg","g","g","1.6726231e-24",1.6726231e-24,false],[false,"Newtonian constant of gravitation","[G]","[GC]","(unclassified)",6.67259e-14,[3,-2,-1,0,0,0,0],"G","const",true,null,null,1,false,false,0,0,"G; gravitational constant; Newton's constant","UCUM","","Constant","gravitational constant = 6.674×10−11 N⋅m2/kg2","m3.kg-1.s-2","M3.KG-1.S-2","6.67259e-11",6.67259e-11,false],[false,"standard acceleration of free fall","[g]","[G]","acceleration",9.80665,[1,-2,0,0,0,0,0],"gn","const",true,null,null,1,false,false,0,0,"standard gravity; g; ɡ0; ɡn","UCUM","Accel","Constant","defined by standard = 9.80665 m/s2","m/s2","M/S2","980665e-5",9.80665,false],[false,"Torr","Torr","Torr","pressure",133322,[-1,-2,1,0,0,0,0],"Torr","const",false,null,null,1,false,false,0,0,"torrs","UCUM","Pres","Clinical","1 torr = 1 mmHg; unit used to measure blood pressure","Pa","PAL","133.322",133.322,false],[false,"standard atmosphere","atm","ATM","pressure",101325000,[-1,-2,1,0,0,0,0],"atm","const",false,null,null,1,false,false,0,0,"reference pressure; atmos; std atmosphere","UCUM","Pres","Clinical","defined as being precisely equal to 101,325 Pa","Pa","PAL","101325",101325,false],[false,"light-year","[ly]","[LY]","length",9460730472580800,[1,0,0,0,0,0,0],"l.y.","const",true,null,null,1,false,false,0,0,"light years; ly","UCUM","Len","Constant","unit of astronomal distance = 5.88×10^12 mi","[c].a_j","[C].ANN_J","1",1,false],[false,"gram-force","gf","GF","force",9.80665,[1,-2,1,0,0,0,0],"gf","const",true,null,null,1,false,false,0,0,"Newtons; gram forces","UCUM","Force","Clinical","May be specific to unit related to cardiac output","g.[g]","G.[G]","1",1,false],[false,"Kayser","Ky","KY","lineic number",100,[-1,0,0,0,0,0,0],"K","cgs",true,null,null,1,false,false,0,0,"wavenumbers; kaysers","UCUM","InvLen","Clinical","unit of wavelength equal to cm^-1","cm-1","CM-1","1",1,false],[false,"Gal","Gal","GL","acceleration",0.01,[1,-2,0,0,0,0,0],"Gal","cgs",true,null,null,1,false,false,0,0,"galileos; Gals","UCUM","Accel","Clinical","unit of acceleration used in gravimetry; equivalent to cm/s2 ","cm/s2","CM/S2","1",1,false],[false,"dyne","dyn","DYN","force",0.01,[1,-2,1,0,0,0,0],"dyn","cgs",true,null,null,1,false,false,0,0,"dynes","UCUM","Force","Clinical","unit of force equal to 10^-5 Newtons","g.cm/s2","G.CM/S2","1",1,false],[false,"erg","erg","ERG","energy",0.0001,[2,-2,1,0,0,0,0],"erg","cgs",true,null,null,1,false,false,0,0,"10^-7 Joules, 10-7 Joules; 100 nJ; 100 nanoJoules; 1 dyne cm; 1 g.cm2/s2","UCUM","Eng","Clinical","unit of energy = 1 dyne centimeter = 10^-7 Joules","dyn.cm","DYN.CM","1",1,false],[false,"Poise","P","P","dynamic viscosity",100.00000000000001,[-1,-1,1,0,0,0,0],"P","cgs",true,null,null,1,false,false,0,0,"dynamic viscosity; poises","UCUM","Visc","Clinical","unit of dynamic viscosity where 1 Poise = 1/10 Pascal second","dyn.s/cm2","DYN.S/CM2","1",1,false],[false,"Biot","Bi","BI","electric current",10,[0,-1,0,0,0,1,0],"Bi","cgs",true,null,null,1,false,false,0,0,"Bi; abamperes; abA","UCUM","ElpotRat","Clinical","equal to 10 amperes","A","A","10",10,false],[false,"Stokes","St","ST","kinematic viscosity",0.00009999999999999999,[2,-1,0,0,0,0,0],"St","cgs",true,null,null,1,false,false,0,0,"kinematic viscosity","UCUM","Visc","Clinical","unit of kimematic viscosity with units cm2/s","cm2/s","CM2/S","1",1,false],[false,"Maxwell","Mx","MX","flux of magnetic induction",0.00001,[2,-1,1,0,0,-1,0],"Mx","cgs",true,null,null,1,false,false,0,0,"magnetix flux; Maxwells","UCUM","","Clinical","unit of magnetic flux","Wb","WB","1e-8",1e-8,false],[false,"Gauss","G","GS","magnetic flux density",0.1,[0,-1,1,0,0,-1,0],"Gs","cgs",true,null,null,1,false,false,0,0,"magnetic fields; magnetic flux density; induction; B","UCUM","magnetic","Clinical","CGS unit of magnetic flux density, known as magnetic field B; defined as one maxwell unit per square centimeter (see Oersted for CGS unit for H field)","T","T","1e-4",0.0001,false],[false,"Oersted","Oe","OE","magnetic field intensity",79.57747154594767,[-1,-1,0,0,0,1,0],"Oe","cgs",true,null,null,1,false,false,0,0,"H magnetic B field; Oersteds","UCUM","","Clinical","CGS unit of the auxiliary magnetic field H defined as 1 dyne per unit pole = 1000/4π amperes per meter (see Gauss for CGS unit for B field)","A/m","/[PI].A/M","250",79.57747154594767,false],[false,"Gilbert","Gb","GB","magnetic tension",0.7957747154594768,[0,-1,0,0,0,1,0],"Gb","cgs",true,null,null,1,false,false,0,0,"Gi; magnetomotive force; Gilberts","UCUM","","Clinical","unit of magnetomotive force (magnetic potential)","Oe.cm","OE.CM","1",1,false],[false,"stilb","sb","SB","lum. intensity density",10000,[-2,0,0,0,0,0,1],"sb","cgs",true,null,null,1,false,false,0,0,"stilbs","UCUM","","Obsolete","unit of luminance; equal to and replaced by unit candela per square centimeter (cd/cm2)","cd/cm2","CD/CM2","1",1,false],[false,"Lambert","Lmb","LMB","brightness",3183.098861837907,[-2,0,0,0,0,0,1],"L","cgs",true,null,null,1,false,false,0,0,"luminance; lamberts","UCUM","","Clinical","unit of luminance defined as 1 lambert = 1/ π candela per square meter","cd/cm2/[pi]","CD/CM2/[PI]","1",1,false],[false,"phot","ph","PHT","illuminance",0.0001,[-2,0,0,2,0,0,1],"ph","cgs",true,null,null,1,false,false,0,0,"phots","UCUM","","Clinical","CGS photometric unit of illuminance, or luminous flux through an area equal to 10000 lumens per square meter = 10000 lux","lx","LX","1e-4",0.0001,false],[false,"Curie","Ci","CI","radioactivity",37000000000,[0,-1,0,0,0,0,0],"Ci","cgs",true,null,null,1,false,false,0,0,"curies","UCUM","","Obsolete","unit for measuring atomic disintegration rate; replaced by the Bequerel (Bq) unit","Bq","BQ","37e9",37000000000,false],[false,"Roentgen","R","ROE","ion dose",2.58e-7,[0,0,-1,0,0,1,0],"R","cgs",true,null,null,1,false,false,0,0,"röntgen; Roentgens","UCUM","","Clinical","unit of exposure of X-rays and gamma rays in air; unit used primarily in the US but strongly discouraged by NIST","C/kg","C/KG","2.58e-4",0.000258,false],[false,"radiation absorbed dose","RAD","[RAD]","energy dose",0.01,[2,-2,0,0,0,0,0],"RAD","cgs",true,null,null,1,false,false,0,0,"doses","UCUM","","Clinical","unit of radiation absorbed dose used primarily in the US with base units 100 ergs per gram of material. Also see the SI unit Gray (Gy).","erg/g","ERG/G","100",100,false],[false,"radiation equivalent man","REM","[REM]","dose equivalent",0.01,[2,-2,0,0,0,0,0],"REM","cgs",true,null,null,1,false,false,0,0,"Roentgen Equivalent in Man; rems; dose equivalents","UCUM","","Clinical","unit of equivalent dose which measures the effect of radiation on humans equal to 0.01 sievert. Used primarily in the US. Also see SI unit Sievert (Sv)","RAD","[RAD]","1",1,false],[false,"inch","[in_i]","[IN_I]","length",0.025400000000000002,[1,0,0,0,0,0,0],"in","intcust",false,null,null,1,false,false,0,0,"inches; in; international inch; body height","UCUM","Len","Clinical","standard unit for inch in the US and internationally","cm","CM","254e-2",2.54,false],[false,"foot","[ft_i]","[FT_I]","length",0.3048,[1,0,0,0,0,0,0],"ft","intcust",false,null,null,1,false,false,0,0,"ft; fts; foot; international foot; feet; international feet; height","UCUM","Len","Clinical","unit used in the US and internationally","[in_i]","[IN_I]","12",12,false],[false,"yard","[yd_i]","[YD_I]","length",0.9144000000000001,[1,0,0,0,0,0,0],"yd","intcust",false,null,null,1,false,false,0,0,"international yards; yds; distance","UCUM","Len","Clinical","standard unit used in the US and internationally","[ft_i]","[FT_I]","3",3,false],[false,"mile","[mi_i]","[MI_I]","length",1609.344,[1,0,0,0,0,0,0],"mi","intcust",false,null,null,1,false,false,0,0,"international miles; mi I; statute mile","UCUM","Len","Clinical","standard unit used in the US and internationally","[ft_i]","[FT_I]","5280",5280,false],[false,"fathom","[fth_i]","[FTH_I]","depth of water",1.8288000000000002,[1,0,0,0,0,0,0],"fth","intcust",false,null,null,1,false,false,0,0,"international fathoms","UCUM","Len","Nonclinical","unit used in the US and internationally to measure depth of water; same length as the US fathom","[ft_i]","[FT_I]","6",6,false],[false,"nautical mile","[nmi_i]","[NMI_I]","length",1852,[1,0,0,0,0,0,0],"n.mi","intcust",false,null,null,1,false,false,0,0,"nautical mile; nautical miles; international nautical mile; international nautical miles; nm; n.m.; nmi","UCUM","Len","Nonclinical","standard unit used in the US and internationally","m","M","1852",1852,false],[false,"knot","[kn_i]","[KN_I]","velocity",0.5144444444444445,[1,-1,0,0,0,0,0],"knot","intcust",false,null,null,1,false,false,0,0,"kn; kt; international knots","UCUM","Vel","Nonclinical","defined as equal to one nautical mile (1.852 km) per hour","[nmi_i]/h","[NMI_I]/H","1",1,false],[false,"square inch","[sin_i]","[SIN_I]","area",0.0006451600000000001,[2,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"in2; in^2; inches squared; sq inch; inches squared; international","UCUM","Area","Clinical","standard unit used in the US and internationally","[in_i]2","[IN_I]2","1",1,false],[false,"square foot","[sft_i]","[SFT_I]","area",0.09290304,[2,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"ft2; ft^2; ft squared; sq ft; feet; international","UCUM","Area","Clinical","standard unit used in the US and internationally","[ft_i]2","[FT_I]2","1",1,false],[false,"square yard","[syd_i]","[SYD_I]","area",0.8361273600000002,[2,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"yd2; yd^2; sq. yds; yards squared; international","UCUM","Area","Clinical","standard unit used in the US and internationally","[yd_i]2","[YD_I]2","1",1,false],[false,"cubic inch","[cin_i]","[CIN_I]","volume",0.000016387064000000006,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"in3; in^3; in*3; inches^3; inches*3; cu. in; cu in; cubic inches; inches cubed; cin","UCUM","Vol","Clinical","standard unit used in the US and internationally","[in_i]3","[IN_I]3","1",1,false],[false,"cubic foot","[cft_i]","[CFT_I]","volume",0.028316846592000004,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"ft3; ft^3; ft*3; cu. ft; cubic feet; cubed; [ft_i]3; international","UCUM","Vol","Clinical","","[ft_i]3","[FT_I]3","1",1,false],[false,"cubic yard","[cyd_i]","[CYD_I]","volume",0.7645548579840002,[3,0,0,0,0,0,0],"cu.yd","intcust",false,null,null,1,false,false,0,0,"cubic yards; cubic yds; cu yards; CYs; yards^3; yd^3; yds^3; yd3; yds3","UCUM","Vol","Nonclinical","standard unit used in the US and internationally","[yd_i]3","[YD_I]3","1",1,false],[false,"board foot","[bf_i]","[BF_I]","volume",0.0023597372160000006,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"BDFT; FBM; BF; board feet; international","UCUM","Vol","Nonclinical","unit of volume used to measure lumber","[in_i]3","[IN_I]3","144",144,false],[false,"cord","[cr_i]","[CR_I]","volume",3.6245563637760005,[3,0,0,0,0,0,0],null,"intcust",false,null,null,1,false,false,0,0,"crd I; international cords","UCUM","Vol","Nonclinical","unit of measure of dry volume used to measure firewood equal 128 ft3","[ft_i]3","[FT_I]3","128",128,false],[false,"mil","[mil_i]","[MIL_I]","length",0.000025400000000000004,[1,0,0,0,0,0,0],"mil","intcust",false,null,null,1,false,false,0,0,"thou, thousandth; mils; international","UCUM","Len","Clinical","equal to 0.001 international inch","[in_i]","[IN_I]","1e-3",0.001,false],[false,"circular mil","[cml_i]","[CML_I]","area",5.067074790974979e-10,[2,0,0,0,0,0,0],"circ.mil","intcust",false,null,null,1,false,false,0,0,"circular mils; cml I; international","UCUM","Area","Clinical","","[pi]/4.[mil_i]2","[PI]/4.[MIL_I]2","1",1,false],[false,"hand","[hd_i]","[HD_I]","height of horses",0.10160000000000001,[1,0,0,0,0,0,0],"hd","intcust",false,null,null,1,false,false,0,0,"hands; international","UCUM","Len","Nonclinical","used to measure horse height","[in_i]","[IN_I]","4",4,false],[false,"foot - US","[ft_us]","[FT_US]","length",0.3048006096012192,[1,0,0,0,0,0,0],"ftus","us-lengths",false,null,null,1,false,false,0,0,"US foot; foot US; us ft; ft us; height; visual distance; feet","UCUM","Len","Obsolete","Better to use [ft_i] which refers to the length used worldwide, including in the US; [ft_us] may be confused with land survey units. ","m/3937","M/3937","1200",1200,false],[false,"yard - US","[yd_us]","[YD_US]","length",0.9144018288036575,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"US yards; us yds; distance","UCUM","Len; Nrat","Obsolete","Better to use [yd_i] which refers to the length used worldwide, including in the US; [yd_us] refers to unit used in land surveys in the US","[ft_us]","[FT_US]","3",3,false],[false,"inch - US","[in_us]","[IN_US]","length",0.0254000508001016,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"US inches; in us; us in; inch US","UCUM","Len","Obsolete","Better to use [in_i] which refers to the length used worldwide, including in the US","[ft_us]/12","[FT_US]/12","1",1,false],[false,"rod - US","[rd_us]","[RD_US]","length",5.029210058420117,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"US rod; US rods; rd US; US rd","UCUM","Len","Obsolete","","[ft_us]","[FT_US]","16.5",16.5,false],[false,"Gunter's chain - US","[ch_us]","[CH_US]","length",20.116840233680467,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"surveyor's chain; Surveyor's chain USA; Gunter’s measurement; surveyor’s measurement; Gunter's Chain USA","UCUM","Len","Obsolete","historical unit used for land survey used only in the US","[rd_us]","[RD_US]","4",4,false],[false,"link for Gunter's chain - US","[lk_us]","[LK_US]","length",0.20116840233680466,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"Links for Gunter's Chain USA","UCUM","Len","Obsolete","","[ch_us]/100","[CH_US]/100","1",1,false],[false,"Ramden's chain - US","[rch_us]","[RCH_US]","length",30.480060960121918,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"Ramsden's chain; engineer's chains","UCUM","Len","Obsolete","distance measuring device used for land survey","[ft_us]","[FT_US]","100",100,false],[false,"link for Ramden's chain - US","[rlk_us]","[RLK_US]","length",0.3048006096012192,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"links for Ramsden's chain","UCUM","Len","Obsolete","","[rch_us]/100","[RCH_US]/100","1",1,false],[false,"fathom - US","[fth_us]","[FTH_US]","length",1.828803657607315,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"US fathoms; fathom USA; fth us","UCUM","Len","Obsolete","same length as the international fathom - better to use international fathom ([fth_i])","[ft_us]","[FT_US]","6",6,false],[false,"furlong - US","[fur_us]","[FUR_US]","length",201.16840233680466,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"US furlongs; fur us","UCUM","Len","Nonclinical","distance unit in horse racing","[rd_us]","[RD_US]","40",40,false],[false,"mile - US","[mi_us]","[MI_US]","length",1609.3472186944373,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"U.S. Survey Miles; US statute miles; survey mi; US mi; distance","UCUM","Len","Nonclinical","Better to use [mi_i] which refers to the length used worldwide, including in the US","[fur_us]","[FUR_US]","8",8,false],[false,"acre - US","[acr_us]","[ACR_US]","area",4046.872609874252,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"Acre USA Survey; Acre USA; survey acres","UCUM","Area","Nonclinical","an older unit based on pre 1959 US statute lengths that is still sometimes used in the US only for land survey purposes. ","[rd_us]2","[RD_US]2","160",160,false],[false,"square rod - US","[srd_us]","[SRD_US]","area",25.292953811714074,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"rod2; rod^2; sq. rod; rods squared","UCUM","Area","Nonclinical","Used only in the US to measure land area, based on US statute land survey length units","[rd_us]2","[RD_US]2","1",1,false],[false,"square mile - US","[smi_us]","[SMI_US]","area",2589998.470319521,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"mi2; mi^2; sq mi; miles squared","UCUM","Area","Nonclinical","historical unit used only in the US for land survey purposes (based on the US survey mile), not the internationally recognized [mi_i]","[mi_us]2","[MI_US]2","1",1,false],[false,"section","[sct]","[SCT]","area",2589998.470319521,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"sct; sections","UCUM","Area","Nonclinical","tract of land approximately equal to 1 mile square containing 640 acres","[mi_us]2","[MI_US]2","1",1,false],[false,"township","[twp]","[TWP]","area",93239944.93150276,[2,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"twp; townships","UCUM","Area","Nonclinical","land measurement equal to 6 mile square","[sct]","[SCT]","36",36,false],[false,"mil - US","[mil_us]","[MIL_US]","length",0.0000254000508001016,[1,0,0,0,0,0,0],null,"us-lengths",false,null,null,1,false,false,0,0,"thou, thousandth; mils","UCUM","Len","Obsolete","better to use [mil_i] which is based on the internationally recognized inch","[in_us]","[IN_US]","1e-3",0.001,false],[false,"inch - British","[in_br]","[IN_BR]","length",0.025399980000000003,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"imperial inches; imp in; br in; british inches","UCUM","Len","Obsolete","","cm","CM","2.539998",2.539998,false],[false,"foot - British","[ft_br]","[FT_BR]","length",0.30479976000000003,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British Foot; Imperial Foot; feet; imp fts; br fts","UCUM","Len","Obsolete","","[in_br]","[IN_BR]","12",12,false],[false,"rod - British","[rd_br]","[RD_BR]","length",5.02919604,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British rods; br rd","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","16.5",16.5,false],[false,"Gunter's chain - British","[ch_br]","[CH_BR]","length",20.11678416,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"Gunter's Chain British; Gunters Chain British; Surveyor's Chain British","UCUM","Len","Obsolete","historical unit used for land survey used only in Great Britain","[rd_br]","[RD_BR]","4",4,false],[false,"link for Gunter's chain - British","[lk_br]","[LK_BR]","length",0.2011678416,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"Links for Gunter's Chain British","UCUM","Len","Obsolete","","[ch_br]/100","[CH_BR]/100","1",1,false],[false,"fathom - British","[fth_br]","[FTH_BR]","length",1.82879856,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British fathoms; imperial fathoms; br fth; imp fth","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","6",6,false],[false,"pace - British","[pc_br]","[PC_BR]","length",0.7619994000000001,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British paces; br pc","UCUM","Len","Nonclinical","traditional unit of length equal to 152.4 centimeters, or 1.52 meter. ","[ft_br]","[FT_BR]","2.5",2.5,false],[false,"yard - British","[yd_br]","[YD_BR]","length",0.91439928,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British yards; Br yds; distance","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","3",3,false],[false,"mile - British","[mi_br]","[MI_BR]","length",1609.3427328000002,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"imperial miles; British miles; English statute miles; imp mi, br mi","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","5280",5280,false],[false,"nautical mile - British","[nmi_br]","[NMI_BR]","length",1853.1825408000002,[1,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British nautical miles; Imperial nautical miles; Admiralty miles; n.m. br; imp nm","UCUM","Len","Obsolete","","[ft_br]","[FT_BR]","6080",6080,false],[false,"knot - British","[kn_br]","[KN_BR]","velocity",0.5147729280000001,[1,-1,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"British knots; kn br; kt","UCUM","Vel","Obsolete","based on obsolete British nautical mile ","[nmi_br]/h","[NMI_BR]/H","1",1,false],[false,"acre","[acr_br]","[ACR_BR]","area",4046.850049400269,[2,0,0,0,0,0,0],null,"brit-length",false,null,null,1,false,false,0,0,"Imperial acres; British; a; ac; ar; acr","UCUM","Area","Nonclinical","the standard unit for acre used in the US and internationally","[yd_br]2","[YD_BR]2","4840",4840,false],[false,"gallon - US","[gal_us]","[GAL_US]","fluid volume",0.0037854117840000014,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US gallons; US liquid gallon; gal us; Queen Anne's wine gallon","UCUM","Vol","Nonclinical","only gallon unit used in the US; [gal_us] is only used in some other countries in South American and Africa to measure gasoline volume","[in_i]3","[IN_I]3","231",231,false],[false,"barrel - US","[bbl_us]","[BBL_US]","fluid volume",0.15898729492800007,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"bbl","UCUM","Vol","Nonclinical","[bbl_us] is the standard unit for oil barrel, which is a unit only used in the US to measure the volume oil. ","[gal_us]","[GAL_US]","42",42,false],[false,"quart - US","[qt_us]","[QT_US]","fluid volume",0.0009463529460000004,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US quarts; us qts","UCUM","Vol","Clinical","Used only in the US","[gal_us]/4","[GAL_US]/4","1",1,false],[false,"pint - US","[pt_us]","[PT_US]","fluid volume",0.0004731764730000002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US pints; pint US; liquid pint; pt us; us pt","UCUM","Vol","Clinical","Used only in the US","[qt_us]/2","[QT_US]/2","1",1,false],[false,"gill - US","[gil_us]","[GIL_US]","fluid volume",0.00011829411825000005,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US gills; gil us","UCUM","Vol","Nonclinical","only used in the context of alcohol volume in the US","[pt_us]/4","[PT_US]/4","1",1,false],[false,"fluid ounce - US","[foz_us]","[FOZ_US]","fluid volume",0.00002957352956250001,[3,0,0,0,0,0,0],"oz fl","us-volumes",false,null,null,1,false,false,0,0,"US fluid ounces; fl ozs; FO; fl. oz.; foz us","UCUM","Vol","Clinical","unit used only in the US","[gil_us]/4","[GIL_US]/4","1",1,false],[false,"fluid dram - US","[fdr_us]","[FDR_US]","fluid volume",0.0000036966911953125014,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US fluid drams; fdr us","UCUM","Vol","Nonclinical","equal to 1/8 US fluid ounce = 3.69 mL; used informally to mean small amount of liquor, especially Scotch whiskey","[foz_us]/8","[FOZ_US]/8","1",1,false],[false,"minim - US","[min_us]","[MIN_US]","fluid volume",6.161151992187503e-8,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"min US; US min; ♏ US","UCUM","Vol","Obsolete","","[fdr_us]/60","[FDR_US]/60","1",1,false],[false,"cord - US","[crd_us]","[CRD_US]","fluid volume",3.6245563637760005,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US cord; US cords; crd us; us crd","UCUM","Vol","Nonclinical","unit of measure of dry volume used to measure firewood equal 128 ft3 (the same as international cord [cr_i])","[ft_i]3","[FT_I]3","128",128,false],[false,"bushel - US","[bu_us]","[BU_US]","dry volume",0.035239070166880014,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US bushels; US bsh; US bu","UCUM","Vol","Obsolete","Historical unit of dry volume that is rarely used today","[in_i]3","[IN_I]3","2150.42",2150.42,false],[false,"gallon - historical","[gal_wi]","[GAL_WI]","dry volume",0.004404883770860002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"Corn Gallon British; Dry Gallon US; Gallons Historical; Grain Gallon British; Winchester Corn Gallon; historical winchester gallons; wi gal","UCUM","Vol","Obsolete","historical unit of dry volume no longer used","[bu_us]/8","[BU_US]/8","1",1,false],[false,"peck - US","[pk_us]","[PK_US]","dry volume",0.008809767541720004,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"US pecks; US pk","UCUM","Vol","Nonclinical","unit of dry volume rarely used today (can be used to measure volume of apples)","[bu_us]/4","[BU_US]/4","1",1,false],[false,"dry quart - US","[dqt_us]","[DQT_US]","dry volume",0.0011012209427150004,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"dry quarts; dry quart US; US dry quart; dry qt; us dry qt; dqt; dqt us","UCUM","Vol","Nonclinical","historical unit of dry volume only in the US, but is rarely used today","[pk_us]/8","[PK_US]/8","1",1,false],[false,"dry pint - US","[dpt_us]","[DPT_US]","dry volume",0.0005506104713575002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"dry pints; dry pint US; US dry pint; dry pt; dpt; dpt us","UCUM","Vol","Nonclinical","historical unit of dry volume only in the US, but is rarely used today","[dqt_us]/2","[DQT_US]/2","1",1,false],[false,"tablespoon - US","[tbs_us]","[TBS_US]","volume",0.000014786764781250006,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"Tbs; tbsp; tbs us; US tablespoons","UCUM","Vol","Clinical","unit defined as 0.5 US fluid ounces or 3 teaspoons - used only in the US. See [tbs_m] for the unit used internationally and in the US for nutrional labelling. ","[foz_us]/2","[FOZ_US]/2","1",1,false],[false,"teaspoon - US","[tsp_us]","[TSP_US]","volume",0.000004928921593750002,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"tsp; t; US teaspoons","UCUM","Vol","Nonclinical","unit defined as 1/6 US fluid ounces - used only in the US. See [tsp_m] for the unit used internationally and in the US for nutrional labelling. ","[tbs_us]/3","[TBS_US]/3","1",1,false],[false,"cup - US customary","[cup_us]","[CUP_US]","volume",0.0002365882365000001,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"cup us; us cups","UCUM","Vol","Nonclinical","Unit defined as 1/2 US pint or 16 US tablespoons ≈ 236.59 mL, which is not the standard unit defined by the FDA of 240 mL - see [cup_m] (metric cup)","[tbs_us]","[TBS_US]","16",16,false],[false,"fluid ounce - metric","[foz_m]","[FOZ_M]","fluid volume",0.000029999999999999997,[3,0,0,0,0,0,0],"oz fl","us-volumes",false,null,null,1,false,false,0,0,"metric fluid ounces; fozs m; fl ozs m","UCUM","Vol","Clinical","unit used only in the US for nutritional labelling, as set by the FDA","mL","ML","30",30,false],[false,"cup - US legal","[cup_m]","[CUP_M]","volume",0.00023999999999999998,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"cup m; metric cups","UCUM","Vol","Clinical","standard unit equal to 240 mL used in the US for nutritional labelling, as defined by the FDA. Note that this is different from the US customary cup (236.59 mL) and the metric cup used in Commonwealth nations (250 mL).","mL","ML","240",240,false],[false,"teaspoon - metric","[tsp_m]","[TSP_M]","volume",0.0000049999999999999996,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"tsp; t; metric teaspoons","UCUM","Vol","Clinical","standard unit used in the US and internationally","mL","mL","5",5,false],[false,"tablespoon - metric","[tbs_m]","[TBS_M]","volume",0.000014999999999999999,[3,0,0,0,0,0,0],null,"us-volumes",false,null,null,1,false,false,0,0,"metric tablespoons; Tbs; tbsp; T; tbs m","UCUM","Vol","Clinical","standard unit used in the US and internationally","mL","mL","15",15,false],[false,"gallon- British","[gal_br]","[GAL_BR]","volume",0.004546090000000001,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"imperial gallons, UK gallons; British gallons; br gal; imp gal","UCUM","Vol","Nonclinical","Used only in Great Britain and other Commonwealth countries","l","L","4.54609",4.54609,false],[false,"peck - British","[pk_br]","[PK_BR]","volume",0.009092180000000002,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"imperial pecks; British pecks; br pk; imp pk","UCUM","Vol","Nonclinical","unit of dry volume rarely used today (can be used to measure volume of apples)","[gal_br]","[GAL_BR]","2",2,false],[false,"bushel - British","[bu_br]","[BU_BR]","volume",0.03636872000000001,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"British bushels; imperial; br bsh; br bu; imp","UCUM","Vol","Obsolete","Historical unit of dry volume that is rarely used today","[pk_br]","[PK_BR]","4",4,false],[false,"quart - British","[qt_br]","[QT_BR]","volume",0.0011365225000000002,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"British quarts; imperial quarts; br qts","UCUM","Vol","Clinical","Used only in Great Britain and other Commonwealth countries","[gal_br]/4","[GAL_BR]/4","1",1,false],[false,"pint - British","[pt_br]","[PT_BR]","volume",0.0005682612500000001,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"British pints; imperial pints; pt br; br pt; imp pt; pt imp","UCUM","Vol","Clinical","Used only in Great Britain and other Commonwealth countries","[qt_br]/2","[QT_BR]/2","1",1,false],[false,"gill - British","[gil_br]","[GIL_BR]","volume",0.00014206531250000003,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"imperial gills; British gills; imp gill, br gill","UCUM","Vol","Nonclinical","only used in the context of alcohol volume in Great Britain","[pt_br]/4","[PT_BR]/4","1",1,false],[false,"fluid ounce - British","[foz_br]","[FOZ_BR]","volume",0.000028413062500000005,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"British fluid ounces; Imperial fluid ounces; br fozs; imp fozs; br fl ozs","UCUM","Vol","Clinical","Used only in Great Britain and other Commonwealth countries","[gil_br]/5","[GIL_BR]/5","1",1,false],[false,"fluid dram - British","[fdr_br]","[FDR_BR]","volume",0.0000035516328125000006,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"British fluid drams; fdr br","UCUM","Vol","Nonclinical","equal to 1/8 Imperial fluid ounce = 3.55 mL; used informally to mean small amount of liquor, especially Scotch whiskey","[foz_br]/8","[FOZ_BR]/8","1",1,false],[false,"minim - British","[min_br]","[MIN_BR]","volume",5.919388020833334e-8,[3,0,0,0,0,0,0],null,"brit-volumes",false,null,null,1,false,false,0,0,"min br; br min; ♏ br","UCUM","Vol","Obsolete","","[fdr_br]/60","[FDR_BR]/60","1",1,false],[false,"grain","[gr]","[GR]","mass",0.06479891,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"gr; grains","UCUM","Mass","Nonclinical","an apothecary measure of mass rarely used today","mg","MG","64.79891",64.79891,false],[false,"pound","[lb_av]","[LB_AV]","mass",453.59237,[0,0,1,0,0,0,0],"lb","avoirdupois",false,null,null,1,false,false,0,0,"avoirdupois pounds, international pounds; av lbs; pounds","UCUM","Mass","Clinical","standard unit used in the US and internationally","[gr]","[GR]","7000",7000,false],[false,"pound force - US","[lbf_av]","[LBF_AV]","force",4448.2216152605,[1,-2,1,0,0,0,0],"lbf","const",false,null,null,1,false,false,0,0,"lbfs; US lbf; US pound forces","UCUM","Force","Clinical","only rarely needed in health care - see [lb_av] which is the more common unit to express weight","[lb_av].[g]","[LB_AV].[G]","1",1,false],[false,"ounce","[oz_av]","[OZ_AV]","mass",28.349523125,[0,0,1,0,0,0,0],"oz","avoirdupois",false,null,null,1,false,false,0,0,"ounces; international ounces; avoirdupois ounces; av ozs","UCUM","Mass","Clinical","standard unit used in the US and internationally","[lb_av]/16","[LB_AV]/16","1",1,false],[false,"Dram mass unit","[dr_av]","[DR_AV]","mass",1.7718451953125,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"Dram; drams avoirdupois; avoidupois dram; international dram","UCUM","Mass","Clinical","unit from the avoirdupois system, which is used in the US and internationally","[oz_av]/16","[OZ_AV]/16","1",1,false],[false,"short hundredweight","[scwt_av]","[SCWT_AV]","mass",45359.237,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"hundredweights; s cwt; scwt; avoirdupois","UCUM","Mass","Nonclinical","Used only in the US to equal 100 pounds","[lb_av]","[LB_AV]","100",100,false],[false,"long hundredweight","[lcwt_av]","[LCWT_AV]","mass",50802.345440000005,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"imperial hundredweights; imp cwt; lcwt; avoirdupois","UCUM","Mass","Obsolete","","[lb_av]","[LB_AV]","112",112,false],[false,"short ton - US","[ston_av]","[STON_AV]","mass",907184.74,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"ton; US tons; avoirdupois tons","UCUM","Mass","Clinical","Used only in the US","[scwt_av]","[SCWT_AV]","20",20,false],[false,"long ton - British","[lton_av]","[LTON_AV]","mass",1016046.9088000001,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"imperial tons; weight tons; British long tons; long ton avoirdupois","UCUM","Mass","Nonclinical","Used only in Great Britain and other Commonwealth countries","[lcwt_av]","[LCWT_AV]","20",20,false],[false,"stone - British","[stone_av]","[STONE_AV]","mass",6350.293180000001,[0,0,1,0,0,0,0],null,"avoirdupois",false,null,null,1,false,false,0,0,"British stones; avoirdupois","UCUM","Mass","Nonclinical","Used primarily in the UK and Ireland to measure body weight","[lb_av]","[LB_AV]","14",14,false],[false,"pennyweight - troy","[pwt_tr]","[PWT_TR]","mass",1.5551738400000001,[0,0,1,0,0,0,0],null,"troy",false,null,null,1,false,false,0,0,"dwt; denarius weights","UCUM","Mass","Obsolete","historical unit used to measure mass and cost of precious metals","[gr]","[GR]","24",24,false],[false,"ounce - troy","[oz_tr]","[OZ_TR]","mass",31.103476800000003,[0,0,1,0,0,0,0],null,"troy",false,null,null,1,false,false,0,0,"troy ounces; tr ozs","UCUM","Mass","Nonclinical","unit of mass for precious metals and gemstones only","[pwt_tr]","[PWT_TR]","20",20,false],[false,"pound - troy","[lb_tr]","[LB_TR]","mass",373.2417216,[0,0,1,0,0,0,0],null,"troy",false,null,null,1,false,false,0,0,"troy pounds; tr lbs","UCUM","Mass","Nonclinical","only used for weighing precious metals","[oz_tr]","[OZ_TR]","12",12,false],[false,"scruple","[sc_ap]","[SC_AP]","mass",1.2959782,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,0,"scruples; sc ap","UCUM","Mass","Obsolete","","[gr]","[GR]","20",20,false],[false,"dram - apothecary","[dr_ap]","[DR_AP]","mass",3.8879346,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,0,"ʒ; drachm; apothecaries drams; dr ap; dram ap","UCUM","Mass","Nonclinical","unit still used in the US occasionally to measure amount of drugs in pharmacies","[sc_ap]","[SC_AP]","3",3,false],[false,"ounce - apothecary","[oz_ap]","[OZ_AP]","mass",31.1034768,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,0,"apothecary ounces; oz ap; ap ozs; ozs ap","UCUM","Mass","Obsolete","","[dr_ap]","[DR_AP]","8",8,false],[false,"pound - apothecary","[lb_ap]","[LB_AP]","mass",373.2417216,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,0,"apothecary pounds; apothecaries pounds; ap lb; lb ap; ap lbs; lbs ap","UCUM","Mass","Obsolete","","[oz_ap]","[OZ_AP]","12",12,false],[false,"ounce - metric","[oz_m]","[OZ_M]","mass",28,[0,0,1,0,0,0,0],null,"apoth",false,null,null,1,false,false,0,0,"metric ounces; m ozs","UCUM","Mass","Clinical","see [oz_av] (the avoirdupois ounce) for the standard ounce used internationally; [oz_m] is equal to 28 grams and is based on the apothecaries' system of mass units which is used in some US pharmacies. ","g","g","28",28,false],[false,"line","[lne]","[LNE]","length",0.002116666666666667,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"British lines; br L; L; l","UCUM","Len","Obsolete","","[in_i]/12","[IN_I]/12","1",1,false],[false,"point (typography)","[pnt]","[PNT]","length",0.0003527777777777778,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"DTP points; desktop publishing point; pt; pnt","UCUM","Len","Nonclinical","typography unit for typesetter's length","[lne]/6","[LNE]/6","1",1,false],[false,"pica (typography)","[pca]","[PCA]","length",0.004233333333333334,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"picas","UCUM","Len","Nonclinical","typography unit for typesetter's length","[pnt]","[PNT]","12",12,false],[false,"Printer's point (typography)","[pnt_pr]","[PNT_PR]","length",0.00035145980000000004,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"pnt pr","UCUM","Len","Nonclinical","typography unit for typesetter's length","[in_i]","[IN_I]","0.013837",0.013837,false],[false,"Printer's pica (typography)","[pca_pr]","[PCA_PR]","length",0.004217517600000001,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"pca pr; Printer's picas","UCUM","Len","Nonclinical","typography unit for typesetter's length","[pnt_pr]","[PNT_PR]","12",12,false],[false,"pied","[pied]","[PIED]","length",0.3248,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"pieds du roi; Paris foot; royal; French; feet","UCUM","Len","Obsolete","","cm","CM","32.48",32.48,false],[false,"pouce","[pouce]","[POUCE]","length",0.027066666666666666,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"historical French inches; French royal inches","UCUM","Len","Obsolete","","[pied]/12","[PIED]/12","1",1,false],[false,"ligne","[ligne]","[LIGNE]","length",0.0022555555555555554,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"Paris lines; lignes","UCUM","Len","Obsolete","","[pouce]/12","[POUCE]/12","1",1,false],[false,"didot","[didot]","[DIDOT]","length",0.0003759259259259259,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"Didot point; dd; Didots Point; didots; points","UCUM","Len","Obsolete","typography unit for typesetter's length","[ligne]/6","[LIGNE]/6","1",1,false],[false,"cicero","[cicero]","[CICERO]","length",0.004511111111111111,[1,0,0,0,0,0,0],null,"typeset",false,null,null,1,false,false,0,0,"Didot's pica; ciceros; picas","UCUM","Len","Obsolete","typography unit for typesetter's length","[didot]","[DIDOT]","12",12,false],[false,"degrees Fahrenheit","[degF]","[DEGF]","temperature",0.5555555555555556,[0,0,0,0,1,0,0],"°F","heat",false,null,"degF",1,true,false,0,0,"°F; deg F","UCUM","Temp","Clinical","","K",null,null,0.5555555555555556,false],[false,"degrees Rankine","[degR]","[degR]","temperature",0.5555555555555556,[0,0,0,0,1,0,0],"°R","heat",false,null,null,1,false,false,0,0,"°R; °Ra; Rankine","UCUM","Temp","Obsolete","Replaced by Kelvin","K/9","K/9","5",5,false],[false,"degrees Réaumur","[degRe]","[degRe]","temperature",1.25,[0,0,0,0,1,0,0],"°Ré","heat",false,null,"degRe",1,true,false,0,0,"°Ré, °Re, °r; Réaumur; degree Reaumur; Reaumur","UCUM","Temp","Obsolete","replaced by Celsius","K",null,null,1.25,false],[false,"calorie at 15°C","cal_[15]","CAL_[15]","energy",4185.8,[2,-2,1,0,0,0,0],"cal15°C","heat",true,null,null,1,false,false,0,0,"calorie 15 C; cals 15 C; calories at 15 C","UCUM","Enrg","Nonclinical","equal to 4.1855 joules; calorie most often used in engineering","J","J","4.18580",4.1858,false],[false,"calorie at 20°C","cal_[20]","CAL_[20]","energy",4181.9,[2,-2,1,0,0,0,0],"cal20°C","heat",true,null,null,1,false,false,0,0,"calorie 20 C; cal 20 C; calories at 20 C","UCUM","Enrg","Clinical","equal to 4.18190 joules. ","J","J","4.18190",4.1819,false],[false,"mean calorie","cal_m","CAL_M","energy",4190.0199999999995,[2,-2,1,0,0,0,0],"calm","heat",true,null,null,1,false,false,0,0,"mean cals; mean calories","UCUM","Enrg","Clinical","equal to 4.19002 joules. ","J","J","4.19002",4.19002,false],[false,"international table calorie","cal_IT","CAL_IT","energy",4186.8,[2,-2,1,0,0,0,0],"calIT","heat",true,null,null,1,false,false,0,0,"calories IT; IT cals; international steam table calories","UCUM","Enrg","Nonclinical","used in engineering steam tables and defined as 1/860 international watt-hour; equal to 4.1868 joules","J","J","4.1868",4.1868,false],[false,"thermochemical calorie","cal_th","CAL_TH","energy",4184,[2,-2,1,0,0,0,0],"calth","heat",true,null,null,1,false,false,0,0,"thermochemical calories; th cals","UCUM","Enrg","Clinical","equal to 4.184 joules; used as the unit in medicine and biochemistry (equal to cal)","J","J","4.184",4.184,false],[false,"calorie","cal","CAL","energy",4184,[2,-2,1,0,0,0,0],"cal","heat",true,null,null,1,false,false,0,0,"gram calories; small calories","UCUM","Enrg","Clinical","equal to 4.184 joules (the same value as the thermochemical calorie, which is the most common calorie used in medicine and biochemistry)","cal_th","CAL_TH","1",1,false],[false,"nutrition label Calories","[Cal]","[CAL]","energy",4184000,[2,-2,1,0,0,0,0],"Cal","heat",false,null,null,1,false,false,0,0,"food calories; Cal; kcal","UCUM","Eng","Clinical","","kcal_th","KCAL_TH","1",1,false],[false,"British thermal unit at 39°F","[Btu_39]","[BTU_39]","energy",1059670,[2,-2,1,0,0,0,0],"Btu39°F","heat",false,null,null,1,false,false,0,0,"BTU 39F; BTU 39 F; B.T.U. 39 F; B.Th.U. 39 F; BThU 39 F; British thermal units","UCUM","Eng","Nonclinical","equal to 1.05967 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05967",1.05967,false],[false,"British thermal unit at 59°F","[Btu_59]","[BTU_59]","energy",1054800,[2,-2,1,0,0,0,0],"Btu59°F","heat",false,null,null,1,false,false,0,0,"BTU 59 F; BTU 59F; B.T.U. 59 F; B.Th.U. 59 F; BThU 59F; British thermal units","UCUM","Eng","Nonclinical","equal to 1.05480 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05480",1.0548,false],[false,"British thermal unit at 60°F","[Btu_60]","[BTU_60]","energy",1054680,[2,-2,1,0,0,0,0],"Btu60°F","heat",false,null,null,1,false,false,0,0,"BTU 60 F; BTU 60F; B.T.U. 60 F; B.Th.U. 60 F; BThU 60 F; British thermal units 60 F","UCUM","Eng","Nonclinical","equal to 1.05468 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05468",1.05468,false],[false,"mean British thermal unit","[Btu_m]","[BTU_M]","energy",1055870,[2,-2,1,0,0,0,0],"Btum","heat",false,null,null,1,false,false,0,0,"BTU mean; B.T.U. mean; B.Th.U. mean; BThU mean; British thermal units mean; ","UCUM","Eng","Nonclinical","equal to 1.05587 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05587",1.05587,false],[false,"international table British thermal unit","[Btu_IT]","[BTU_IT]","energy",1055055.85262,[2,-2,1,0,0,0,0],"BtuIT","heat",false,null,null,1,false,false,0,0,"BTU IT; B.T.U. IT; B.Th.U. IT; BThU IT; British thermal units IT","UCUM","Eng","Nonclinical","equal to 1.055 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.05505585262",1.05505585262,false],[false,"thermochemical British thermal unit","[Btu_th]","[BTU_TH]","energy",1054350,[2,-2,1,0,0,0,0],"Btuth","heat",false,null,null,1,false,false,0,0,"BTU Th; B.T.U. Th; B.Th.U. Th; BThU Th; thermochemical British thermal units","UCUM","Eng","Nonclinical","equal to 1.054350 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","kJ","kJ","1.054350",1.05435,false],[false,"British thermal unit","[Btu]","[BTU]","energy",1054350,[2,-2,1,0,0,0,0],"btu","heat",false,null,null,1,false,false,0,0,"BTU; B.T.U. ; B.Th.U.; BThU; British thermal units","UCUM","Eng","Nonclinical","equal to the thermochemical British thermal unit equal to 1.054350 kJ; used as a measure of power in the electric power, steam generation, heating, and air conditioning industries","[Btu_th]","[BTU_TH]","1",1,false],[false,"horsepower - mechanical","[HP]","[HP]","power",745699.8715822703,[2,-3,1,0,0,0,0],null,"heat",false,null,null,1,false,false,0,0,"imperial horsepowers","UCUM","EngRat","Nonclinical","refers to mechanical horsepower, which is unit used to measure engine power primarily in the US. ","[ft_i].[lbf_av]/s","[FT_I].[LBF_AV]/S","550",550,false],[false,"tex","tex","TEX","linear mass density (of textile thread)",0.001,[-1,0,1,0,0,0,0],"tex","heat",true,null,null,1,false,false,0,0,"linear mass density; texes","UCUM","","Clinical","unit of linear mass density for fibers equal to gram per 1000 meters","g/km","G/KM","1",1,false],[false,"Denier (linear mass density)","[den]","[DEN]","linear mass density (of textile thread)",0.0001111111111111111,[-1,0,1,0,0,0,0],"den","heat",false,null,null,1,false,false,0,0,"den; deniers","UCUM","","Nonclinical","equal to the mass in grams per 9000 meters of the fiber (1 denier = 1 strand of silk)","g/9/km","G/9/KM","1",1,false],[false,"meter of water column","m[H2O]","M[H2O]","pressure",9806650,[-1,-2,1,0,0,0,0],"m HO2","clinical",true,null,null,1,false,false,0,0,"mH2O; m H2O; meters of water column; metres; pressure","UCUM","Pres","Clinical","","kPa","KPAL","980665e-5",9.80665,false],[false,"meter of mercury column","m[Hg]","M[HG]","pressure",133322000,[-1,-2,1,0,0,0,0],"m Hg","clinical",true,null,null,1,false,false,0,0,"mHg; m Hg; meters of mercury column; metres; pressure","UCUM","Pres","Clinical","","kPa","KPAL","133.3220",133.322,false],[false,"inch of water column","[in_i'H2O]","[IN_I'H2O]","pressure",249088.91000000003,[-1,-2,1,0,0,0,0],"in HO2","clinical",false,null,null,1,false,false,0,0,"inches WC; inAq; in H2O; inch of water gauge; iwg; pressure","UCUM","Pres","Clinical","unit of pressure, especially in respiratory and ventilation care","m[H2O].[in_i]/m","M[H2O].[IN_I]/M","1",1,false],[false,"inch of mercury column","[in_i'Hg]","[IN_I'HG]","pressure",3386378.8000000003,[-1,-2,1,0,0,0,0],"in Hg","clinical",false,null,null,1,false,false,0,0,"inHg; in Hg; pressure; inches","UCUM","Pres","Clinical","unit of pressure used in US to measure barometric pressure and occasionally blood pressure (see mm[Hg] for unit used internationally)","m[Hg].[in_i]/m","M[HG].[IN_I]/M","1",1,false],[false,"peripheral vascular resistance unit","[PRU]","[PRU]","fluid resistance",133322000000,[-4,-1,1,0,0,0,0],"P.R.U.","clinical",false,null,null,1,false,false,0,0,"peripheral vascular resistance units; peripheral resistance unit; peripheral resistance units; PRU","UCUM","FldResist","Clinical","used to assess blood flow in the capillaries; equal to 1 mmH.min/mL = 133.3 Pa·min/mL","mm[Hg].s/ml","MM[HG].S/ML","1",1,false],[false,"Wood unit","[wood'U]","[WOOD'U]","fluid resistance",7999320000,[-4,-1,1,0,0,0,0],"Wood U.","clinical",false,null,null,1,false,false,0,0,"hybrid reference units; HRU; mmHg.min/L; vascular resistance","UCUM","Pres","Clinical","simplified unit of measurement for for measuring pulmonary vascular resistance that uses pressure; equal to mmHg.min/L","mm[Hg].min/L","MM[HG].MIN/L","1",1,false],[false,"diopter (lens)","[diop]","[DIOP]","refraction of a lens",1,[1,0,0,0,0,0,0],"dpt","clinical",false,null,"inv",1,false,false,0,0,"diopters; diop; dioptre; dpt; refractive power","UCUM","InvLen","Clinical","unit of optical power of lens represented by inverse meters (m^-1)","m","/M","1",1,false],[false,"prism diopter (magnifying power)","[p'diop]","[P'DIOP]","refraction of a prism",1,[0,0,0,1,0,0,0],"PD","clinical",false,null,"tanTimes100",1,true,false,0,0,"diopters; dioptres; p diops; pdiop; dpt; pdptr; Δ; cm/m; centimeter per meter; centimetre; metre","UCUM","Angle","Clinical","unit for prism correction in eyeglass prescriptions","rad",null,null,1,false],[false,"percent of slope","%[slope]","%[SLOPE]","slope",0.017453292519943295,[0,0,0,1,0,0,0],"%","clinical",false,null,"100tan",1,true,false,0,0,"% slope; %slope; percents slopes","UCUM","VelFr; ElpotRatFr; VelRtoFr; AccelFr","Clinical","","deg",null,null,1,false],[false,"mesh","[mesh_i]","[MESH_I]","lineic number",0.025400000000000002,[1,0,0,0,0,0,0],null,"clinical",false,null,"inv",1,false,false,0,0,"meshes","UCUM","NLen (lineic number)","Clinical","traditional unit of length defined as the number of strands or particles per inch","[in_i]","/[IN_I]","1",1,false],[false,"French (catheter gauge) ","[Ch]","[CH]","gauge of catheters",0.0003333333333333333,[1,0,0,0,0,0,0],"Ch","clinical",false,null,null,1,false,false,0,0,"Charrières, French scales; French gauges; Fr, Fg, Ga, FR, Ch","UCUM","Len; Circ; Diam","Clinical","","mm/3","MM/3","1",1,false],[false,"drop - metric (1/20 mL)","[drp]","[DRP]","volume",5e-8,[3,0,0,0,0,0,0],"drp","clinical",false,null,null,1,false,false,0,0,"drop dosing units; metric drops; gtt","UCUM","Vol","Clinical","standard unit used in the US and internationally for clinical medicine but note that although [drp] is defined as 1/20 milliliter, in practice, drop sizes will vary due to external factors","ml/20","ML/20","1",1,false],[false,"Hounsfield unit","[hnsf'U]","[HNSF'U]","x-ray attenuation",1,[0,0,0,0,0,0,0],"HF","clinical",false,null,null,1,false,false,0,0,"HU; units","UCUM","","Clinical","used to measure X-ray attenuation, especially in CT scans.","1","1","1",1,false],[false,"Metabolic Equivalent of Task ","[MET]","[MET]","metabolic cost of physical activity",5.833333333333334e-11,[3,-1,-1,0,0,0,0],"MET","clinical",false,null,null,1,false,false,0,0,"metabolic equivalents","UCUM","RelEngRat","Clinical","unit used to measure rate of energy expenditure per power in treadmill and other functional tests","mL/min/kg","ML/MIN/KG","3.5",3.5,false],[false,"homeopathic potency of decimal series (retired)","[hp'_X]","[HP'_X]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"X","clinical",false,null,"hpX",1,true,false,0,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of centesimal series (retired)","[hp'_C]","[HP'_C]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"C","clinical",false,null,"hpC",1,true,false,0,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of millesimal series (retired)","[hp'_M]","[HP'_M]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"M","clinical",false,null,"hpM",1,true,false,0,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of quintamillesimal series (retired)","[hp'_Q]","[HP'_Q]","homeopathic potency (retired)",1,[0,0,0,0,0,0,0],"Q","clinical",false,null,"hpQ",1,true,false,0,0,null,"UCUM",null,null,null,"1",null,null,1,false],[false,"homeopathic potency of decimal hahnemannian series","[hp_X]","[HP_X]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"X","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of centesimal hahnemannian series","[hp_C]","[HP_C]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"C","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of millesimal hahnemannian series","[hp_M]","[HP_M]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"M","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of quintamillesimal hahnemannian series","[hp_Q]","[HP_Q]","homeopathic potency (Hahnemann)",1,[0,0,0,0,0,0,0],"Q","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of decimal korsakovian series","[kp_X]","[KP_X]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"X","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of centesimal korsakovian series","[kp_C]","[KP_C]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"C","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of millesimal korsakovian series","[kp_M]","[KP_M]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"M","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"homeopathic potency of quintamillesimal korsakovian series","[kp_Q]","[KP_Q]","homeopathic potency (Korsakov)",1,[0,0,0,0,0,0,0],"Q","clinical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"equivalent","eq","EQ","amount of substance",6.0221367e+23,[0,0,0,0,0,0,0],"eq","chemical",true,null,null,1,false,false,0,1,"equivalents","UCUM","Sub","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"osmole","osm","OSM","amount of substance (dissolved particles)",6.0221367e+23,[0,0,0,0,0,0,0],"osm","chemical",true,null,null,1,false,false,1,0,"osmoles; osmols","UCUM","Osmol","Clinical","the number of moles of solute that contribute to the osmotic pressure of a solution","mol","MOL","1",1,false],[false,"pH","[pH]","[PH]","acidity",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"pH","chemical",false,null,"pH",1,true,false,0,0,"pH scale","UCUM","LogCnc","Clinical","Log concentration of H+","mol/l",null,null,1,false],[false,"gram percent","g%","G%","mass concentration",10000,[-3,0,1,0,0,0,0],"g%","chemical",true,null,null,1,false,false,0,0,"gram %; gram%; grams per deciliter; g/dL; gm per dL; gram percents","UCUM","MCnc","Clinical","equivalent to unit gram per deciliter (g/dL), a unit often used in medical tests to represent solution concentrations","g/dl","G/DL","1",1,false],[false,"Svedberg unit","[S]","[S]","sedimentation coefficient",1e-13,[0,1,0,0,0,0,0],"S","chemical",false,null,null,1,false,false,0,0,"Sv; 10^-13 seconds; 100 fs; 100 femtoseconds","UCUM","Time","Clinical","unit of time used in measuring particle's sedimentation rate, usually after centrifugation. ","s","10*-13.S","1",1e-13,false],[false,"high power field (microscope)","[HPF]","[HPF]","view area in microscope",1,[0,0,0,0,0,0,0],"HPF","chemical",false,null,null,1,false,false,0,0,"HPF","UCUM","Area","Clinical","area visible under the maximum magnification power of the objective in microscopy (usually 400x)\n","1","1","1",1,false],[false,"low power field (microscope)","[LPF]","[LPF]","view area in microscope",1,[0,0,0,0,0,0,0],"LPF","chemical",false,null,null,1,false,false,0,0,"LPF; fields","UCUM","Area","Clinical","area visible under the low magnification of the objective in microscopy (usually 100 x)\n","1","1","100",100,false],[false,"katal","kat","KAT","catalytic activity",6.0221367e+23,[0,-1,0,0,0,0,0],"kat","chemical",true,null,null,1,false,false,1,0,"mol/secs; moles per second; mol*sec-1; mol*s-1; mol.s-1; katals; catalytic activity; enzymatic; enzyme units; activities","UCUM","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"enzyme unit","U","U","catalytic activity",10036894500000000,[0,-1,0,0,0,0,0],"U","chemical",true,null,null,1,false,false,1,0,"micromoles per minute; umol/min; umol per minute; umol min-1; enzymatic activity; enzyme activity","UCUM","CAct","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"international unit - arbitrary","[iU]","[IU]","arbitrary",1,[0,0,0,0,0,0,0],"IU","chemical",true,null,null,1,false,true,0,0,"international units; IE; F2","UCUM","Arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","1","1","1",1,false],[false,"international unit - arbitrary","[IU]","[IU]","arbitrary",1,[0,0,0,0,0,0,0],"i.U.","chemical",true,null,null,1,false,true,0,0,"international units; IE; F2","UCUM","Arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"arbitary unit","[arb'U]","[ARB'U]","arbitrary",1,[0,0,0,0,0,0,0],"arb. U","chemical",false,null,null,1,false,true,0,0,"arbitary units; arb units; arbU","UCUM","Arb","Clinical","relative unit of measurement to show the ratio of test measurement to reference measurement","1","1","1",1,false],[false,"United States Pharmacopeia unit","[USP'U]","[USP'U]","arbitrary",1,[0,0,0,0,0,0,0],"U.S.P.","chemical",false,null,null,1,false,true,0,0,"USP U; USP'U","UCUM","Arb","Clinical","a dose unit to express potency of drugs and vitamins defined by the United States Pharmacopoeia; usually 1 USP = 1 IU","1","1","1",1,false],[false,"GPL unit","[GPL'U]","[GPL'U]","biologic activity of anticardiolipin IgG",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"GPL Units; GPL U; IgG anticardiolipin units; IgG Phospholipid","UCUM","ACnc; AMass","Clinical","Units for an antiphospholipid test","1","1","1",1,false],[false,"MPL unit","[MPL'U]","[MPL'U]","biologic activity of anticardiolipin IgM",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"MPL units; MPL U; MPL'U; IgM anticardiolipin units; IgM Phospholipid Units ","UCUM","ACnc","Clinical","units for antiphospholipid test","1","1","1",1,false],[false,"APL unit","[APL'U]","[APL'U]","biologic activity of anticardiolipin IgA",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"APL units; APL U; IgA anticardiolipin; IgA Phospholipid; biologic activity of","UCUM","AMass; ACnc","Clinical","Units for an anti phospholipid syndrome test","1","1","1",1,false],[false,"Bethesda unit","[beth'U]","[BETH'U]","biologic activity of factor VIII inhibitor",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"BU","UCUM","ACnc","Clinical","measures of blood coagulation inhibitior for many blood factors","1","1","1",1,false],[false,"anti factor Xa unit","[anti'Xa'U]","[ANTI'XA'U]","biologic activity of factor Xa inhibitor (heparin)",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"units","UCUM","ACnc","Clinical","[anti'Xa'U] unit is equivalent to and can be converted to IU/mL. ","1","1","1",1,false],[false,"Todd unit","[todd'U]","[TODD'U]","biologic activity antistreptolysin O",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"units","UCUM","InvThres; RtoThres","Clinical","the unit for the results of the testing for antistreptolysin O (ASO)","1","1","1",1,false],[false,"Dye unit","[dye'U]","[DYE'U]","biologic activity of amylase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"units","UCUM","CCnc","Obsolete","equivalent to the Somogyi unit, which is an enzyme unit for amylase but better to use U, the standard enzyme unit for measuring catalytic activity","1","1","1",1,false],[false,"Somogyi unit","[smgy'U]","[SMGY'U]","biologic activity of amylase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"Somogyi units; smgy U","UCUM","CAct","Clinical","measures the enzymatic activity of amylase in blood serum - better to use base units mg/mL ","1","1","1",1,false],[false,"Bodansky unit","[bdsk'U]","[BDSK'U]","biologic activity of phosphatase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"","UCUM","ACnc","Obsolete","Enzyme unit specific to alkaline phosphatase - better to use standard enzyme unit of U","1","1","1",1,false],[false,"King-Armstrong unit","[ka'U]","[KA'U]","biologic activity of phosphatase",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"King-Armstrong Units; King units","UCUM","AMass","Obsolete","enzyme units for acid phosphatase - better to use enzyme unit [U]","1","1","1",1,false],[false,"Kunkel unit","[knk'U]","[KNK'U]","arbitrary biologic activity",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,null,"UCUM",null,null,null,"1","1","1",1,false],[false,"Mac Lagan unit","[mclg'U]","[MCLG'U]","arbitrary biologic activity",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"galactose index; galactose tolerance test; thymol turbidity test unit; mclg U; units; indexes","UCUM","ACnc","Obsolete","unit for liver tests - previously used in thymol turbidity tests for liver disease diagnoses, and now is sometimes referred to in the oral galactose tolerance test","1","1","1",1,false],[false,"tuberculin unit","[tb'U]","[TB'U]","biologic activity of tuberculin",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"TU; units","UCUM","Arb","Clinical","amount of tuberculin antigen -usually in reference to a TB skin test ","1","1","1",1,false],[false,"50% cell culture infectious dose","[CCID_50]","[CCID_50]","biologic activity (infectivity) of an infectious agent preparation",1,[0,0,0,0,0,0,0],"CCID50","chemical",false,null,null,1,false,true,0,0,"CCID50; 50% cell culture infective doses","UCUM","NumThres","Clinical","","1","1","1",1,false],[false,"50% tissue culture infectious dose","[TCID_50]","[TCID_50]","biologic activity (infectivity) of an infectious agent preparation",1,[0,0,0,0,0,0,0],"TCID50","chemical",false,null,null,1,false,true,0,0,"TCID50; 50% tissue culture infective dose","UCUM","NumThres","Clinical","","1","1","1",1,false],[false,"50% embryo infectious dose","[EID_50]","[EID_50]","biologic activity (infectivity) of an infectious agent preparation",1,[0,0,0,0,0,0,0],"EID50","chemical",false,null,null,1,false,true,0,0,"EID50; 50% embryo infective doses; EID50 Egg Infective Dosage","UCUM","thresNum","Clinical","","1","1","1",1,false],[false,"plaque forming units","[PFU]","[PFU]","amount of an infectious agent",1,[0,0,0,0,0,0,0],"PFU","chemical",false,null,null,1,false,true,0,0,"PFU","UCUM","ACnc","Clinical","tests usually report unit as number of PFU per unit volume","1","1","1",1,false],[false,"focus forming units (cells)","[FFU]","[FFU]","amount of an infectious agent",1,[0,0,0,0,0,0,0],"FFU","chemical",false,null,null,1,false,true,0,0,"FFU","UCUM","EntNum","Clinical","","1","1","1",1,false],[false,"colony forming units","[CFU]","[CFU]","amount of a proliferating organism",1,[0,0,0,0,0,0,0],"CFU","chemical",false,null,null,1,false,true,0,0,"CFU","UCUM","Num","Clinical","","1","1","1",1,false],[false,"index of reactivity (allergen)","[IR]","[IR]","amount of an allergen callibrated through in-vivo testing using the Stallergenes® method.",1,[0,0,0,0,0,0,0],"IR","chemical",false,null,null,1,false,true,0,0,"IR; indexes","UCUM","Acnc","Clinical","amount of an allergen callibrated through in-vivo testing using the Stallergenes method. Usually reported in tests as IR/mL","1","1","1",1,false],[false,"bioequivalent allergen unit","[BAU]","[BAU]","amount of an allergen callibrated through in-vivo testing based on the ID50EAL method of (intradermal dilution for 50mm sum of erythema diameters",1,[0,0,0,0,0,0,0],"BAU","chemical",false,null,null,1,false,true,0,0,"BAU; Bioequivalent Allergy Units; bioequivalent allergen units","UCUM","Arb","Clinical","","1","1","1",1,false],[false,"allergy unit","[AU]","[AU]","procedure defined amount of an allergen using some reference standard",1,[0,0,0,0,0,0,0],"AU","chemical",false,null,null,1,false,true,0,0,"allergy units; allergen units; AU","UCUM","Arb","Clinical","Most standard test allergy units are reported as [IU] or as %. ","1","1","1",1,false],[false,"allergen unit for Ambrosia artemisiifolia","[Amb'a'1'U]","[AMB'A'1'U]","procedure defined amount of the major allergen of ragweed.",1,[0,0,0,0,0,0,0],"Amb a 1 U","chemical",false,null,null,1,false,true,0,0,"Amb a 1 unit; Antigen E; AgE U; allergen units","UCUM","Arb","Clinical","Amb a 1 is the major allergen in short ragweed, and can be converted Bioequivalent allergen units (BAU) where 350 Amb a 1 U/mL = 100,000 BAU/mL","1","1","1",1,false],[false,"protein nitrogen unit (allergen testing)","[PNU]","[PNU]","procedure defined amount of a protein substance",1,[0,0,0,0,0,0,0],"PNU","chemical",false,null,null,1,false,true,0,0,"protein nitrogen units; PNU","UCUM","Mass","Clinical","defined as 0.01 ug of phosphotungstic acid-precipitable protein nitrogen. Being replaced by bioequivalent allergy units (BAU).","1","1","1",1,false],[false,"Limit of flocculation","[Lf]","[LF]","procedure defined amount of an antigen substance",1,[0,0,0,0,0,0,0],"Lf","chemical",false,null,null,1,false,true,0,0,"Lf doses","UCUM","Arb","Clinical","the antigen content forming 1:1 ratio against 1 unit of antitoxin","1","1","1",1,false],[false,"D-antigen unit (polio)","[D'ag'U]","[D'AG'U]","procedure defined amount of a poliomyelitis d-antigen substance",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"DAgU; units","UCUM","Acnc","Clinical","unit of potency of poliovirus vaccine used for poliomyelitis prevention reported as D antigen units/mL. The unit is poliovirus type-specific.","1","1","1",1,false],[false,"fibrinogen equivalent units","[FEU]","[FEU]","amount of fibrinogen broken down into the measured d-dimers",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"FEU","UCUM","MCnc","Clinical","Note both the FEU and DDU units are used to report D-dimer measurements. 1 DDU = 1/2 FFU","1","1","1",1,false],[false,"ELISA unit","[ELU]","[ELU]","arbitrary ELISA unit",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"Enzyme-Linked Immunosorbent Assay Units; ELU; EL. U","UCUM","ACnc","Clinical","","1","1","1",1,false],[false,"Ehrlich units (urobilinogen)","[EU]","[EU]","Ehrlich unit",1,[0,0,0,0,0,0,0],null,"chemical",false,null,null,1,false,true,0,0,"EU/dL; mg{urobilinogen}/dL","UCUM","ACnc","Clinical","","1","1","1",1,false],[false,"neper","Np","NEP","level",1,[0,0,0,0,0,0,0],"Np","levels",true,null,"ln",1,true,false,0,0,"nepers","UCUM","LogRto","Clinical","logarithmic unit for ratios of measurements of physical field and power quantities, such as gain and loss of electronic signals","1",null,null,1,false],[false,"bel","B","B","level",1,[0,0,0,0,0,0,0],"B","levels",true,null,"lg",1,true,false,0,0,"bels","UCUM","LogRto","Clinical","Logarithm of the ratio of power- or field-type quantities; usually expressed in decibels ","1",null,null,1,false],[false,"bel sound pressure","B[SPL]","B[SPL]","pressure level",0.019999999999999997,[-1,-2,1,0,0,0,0],"B(SPL)","levels",true,null,"lgTimes2",1,true,false,0,0,"bel SPL; B SPL; sound pressure bels","UCUM","LogRto","Clinical","used to measure sound level in acoustics","Pa",null,null,0.000019999999999999998,false],[false,"bel volt","B[V]","B[V]","electric potential level",1000,[2,-2,1,0,0,-1,0],"B(V)","levels",true,null,"lgTimes2",1,true,false,0,0,"bel V; B V; volts bels","UCUM","LogRtoElp","Clinical","used to express power gain in electrical circuits","V",null,null,1,false],[false,"bel millivolt","B[mV]","B[MV]","electric potential level",1,[2,-2,1,0,0,-1,0],"B(mV)","levels",true,null,"lgTimes2",1,true,false,0,0,"bel mV; B mV; millivolt bels; 10^-3V bels; 10*-3V ","UCUM","LogRtoElp","Clinical","used to express power gain in electrical circuits","mV",null,null,1,false],[false,"bel microvolt","B[uV]","B[UV]","electric potential level",0.001,[2,-2,1,0,0,-1,0],"B(μV)","levels",true,null,"lgTimes2",1,true,false,0,0,"bel uV; B uV; microvolts bels; 10^-6V bel; 10*-6V bel","UCUM","LogRto","Clinical","used to express power gain in electrical circuits","uV",null,null,1,false],[false,"bel 10 nanovolt","B[10.nV]","B[10.NV]","electric potential level",0.000010000000000000003,[2,-2,1,0,0,-1,0],"B(10 nV)","levels",true,null,"lgTimes2",1,true,false,0,0,"bel 10 nV; B 10 nV; 10 nanovolts bels","UCUM","LogRtoElp","Clinical","used to express power gain in electrical circuits","nV",null,null,10,false],[false,"bel watt","B[W]","B[W]","power level",1000,[2,-3,1,0,0,0,0],"B(W)","levels",true,null,"lg",1,true,false,0,0,"bel W; b W; b Watt; Watts bels","UCUM","LogRto","Clinical","used to express power","W",null,null,1,false],[false,"bel kilowatt","B[kW]","B[KW]","power level",1000000,[2,-3,1,0,0,0,0],"B(kW)","levels",true,null,"lg",1,true,false,0,0,"bel kW; B kW; kilowatt bel; kW bel; kW B","UCUM","LogRto","Clinical","used to express power","kW",null,null,1,false],[false,"stere","st","STR","volume",1,[3,0,0,0,0,0,0],"st","misc",true,null,null,1,false,false,0,0,"stère; m3; cubic meter; m^3; meters cubed; metre","UCUM","Vol","Nonclinical","equal to one cubic meter, usually used for measuring firewood","m3","M3","1",1,false],[false,"Ångström","Ao","AO","length",1.0000000000000002e-10,[1,0,0,0,0,0,0],"Å","misc",false,null,null,1,false,false,0,0,"Å; Angstroms; Ao; Ångströms","UCUM","Len","Clinical","equal to 10^-10 meters; used to express wave lengths and atom scaled differences ","nm","NM","0.1",0.1,false],[false,"barn","b","BRN","action area",1.0000000000000001e-28,[2,0,0,0,0,0,0],"b","misc",false,null,null,1,false,false,0,0,"barns","UCUM","Area","Clinical","used in high-energy physics to express cross-sectional areas","fm2","FM2","100",100,false],[false,"technical atmosphere","att","ATT","pressure",98066500,[-1,-2,1,0,0,0,0],"at","misc",false,null,null,1,false,false,0,0,"at; tech atm; tech atmosphere; kgf/cm2; atms; atmospheres","UCUM","Pres","Obsolete","non-SI unit of pressure equal to one kilogram-force per square centimeter","kgf/cm2","KGF/CM2","1",1,false],[false,"mho","mho","MHO","electric conductance",0.001,[-2,1,-1,0,0,2,0],"mho","misc",true,null,null,1,false,false,0,0,"siemens; ohm reciprocals; Ω^−1; Ω-1 ","UCUM","","Obsolete","unit of electric conductance (the inverse of electrical resistance) equal to ohm^-1","S","S","1",1,false],[false,"pound per square inch","[psi]","[PSI]","pressure",6894757.293168359,[-1,-2,1,0,0,0,0],"psi","misc",false,null,null,1,false,false,0,0,"psi; lb/in2; lb per in2","UCUM","Pres","Clinical","","[lbf_av]/[in_i]2","[LBF_AV]/[IN_I]2","1",1,false],[false,"circle - plane angle","circ","CIRC","plane angle",6.283185307179586,[0,0,0,1,0,0,0],"circ","misc",false,null,null,1,false,false,0,0,"angles; circles","UCUM","Angle","Clinical","","[pi].rad","[PI].RAD","2",2,false],[false,"spere - solid angle","sph","SPH","solid angle",12.566370614359172,[0,0,0,2,0,0,0],"sph","misc",false,null,null,1,false,false,0,0,"speres","UCUM","Angle","Clinical","equal to the solid angle of an entire sphere = 4πsr (sr = steradian) ","[pi].sr","[PI].SR","4",4,false],[false,"metric carat","[car_m]","[CAR_M]","mass",0.2,[0,0,1,0,0,0,0],"ctm","misc",false,null,null,1,false,false,0,0,"carats; ct; car m","UCUM","Mass","Nonclinical","unit of mass for gemstones","g","G","2e-1",0.2,false],[false,"carat of gold alloys","[car_Au]","[CAR_AU]","mass fraction",0.041666666666666664,[0,0,0,0,0,0,0],"ctAu","misc",false,null,null,1,false,false,0,0,"karats; k; kt; car au; carats","UCUM","MFr","Nonclinical","unit of purity for gold alloys","/24","/24","1",1,false],[false,"Smoot","[smoot]","[SMOOT]","length",1.7018000000000002,[1,0,0,0,0,0,0],null,"misc",false,null,null,1,false,false,0,0,"","UCUM","Len","Nonclinical","prank unit of length from MIT","[in_i]","[IN_I]","67",67,false],[false,"meter per square seconds per square root of hertz","[m/s2/Hz^(1/2)]","[M/S2/HZ^(1/2)]","amplitude spectral density",1,[2,-3,0,0,0,0,0],null,"misc",false,null,"sqrt",1,true,false,0,0,"m/s2/(Hz^.5); m/s2/(Hz^(1/2)); m per s2 per Hz^1/2","UCUM","","Constant","measures amplitude spectral density, and is equal to the square root of power spectral density\n ","m2/s4/Hz",null,null,1,false],[false,"bit - logarithmic","bit_s","BIT_S","amount of information",1,[0,0,0,0,0,0,0],"bits","infotech",false,null,"ld",1,true,false,0,0,"bit-s; bit s; bit logarithmic","UCUM","LogA","Nonclinical","defined as the log base 2 of the number of distinct signals; cannot practically be used to express more than 1000 bits\n\nIn information theory, the definition of the amount of self-information and information entropy is often expressed with the binary logarithm (log base 2)","1",null,null,1,false],[false,"bit","bit","BIT","amount of information",1,[0,0,0,0,0,0,0],"bit","infotech",true,null,null,1,false,false,0,0,"bits","UCUM","","Nonclinical","dimensionless information unit of 1 used in computing and digital communications","1","1","1",1,false],[false,"byte","By","BY","amount of information",8,[0,0,0,0,0,0,0],"B","infotech",true,null,null,1,false,false,0,0,"bytes","UCUM","","Nonclinical","equal to 8 bits","bit","bit","8",8,false],[false,"baud","Bd","BD","signal transmission rate",1,[0,1,0,0,0,0,0],"Bd","infotech",true,null,"inv",1,false,false,0,0,"Bd; bauds","UCUM","Freq","Nonclinical","unit to express rate in symbols per second or pulses per second. ","s","/s","1",1,false],[false,"per twelve hour","/(12.h)","1/(12.HR)","",0.000023148148148148147,[0,-1,0,0,0,0,0],"/h",null,false,null,null,1,false,false,0,0,"per 12 hours; 12hrs; 12 hrs; /12hrs","LOINC","Rat","Clinical","",null,null,null,null,false],[false,"per arbitrary unit","/[arb'U]","1/[ARB'U]","",1,[0,0,0,0,0,0,0],"/arb/ U",null,false,null,null,1,false,true,0,0,"/arbU","LOINC","InvA ","Clinical","",null,null,null,null,false],[false,"per high power field","/[HPF]","1/[HPF]","",1,[0,0,0,0,0,0,0],"/HPF",null,false,null,null,1,false,false,0,0,"/HPF; per HPF","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"per international unit","/[IU]","1/[IU]","",1,[0,0,0,0,0,0,0],"/i/U.",null,false,null,null,1,false,true,0,0,"international units; /IU; per IU","LOINC","InvA","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)",null,null,null,null,false],[false,"per low power field","/[LPF]","1/[LPF]","",1,[0,0,0,0,0,0,0],"/LPF",null,false,null,null,1,false,false,0,0,"/LPF; per LPF","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"per 10 billion ","/10*10","1/(10*10)","",1e-10,[0,0,0,0,0,0,0],"/1010",null,false,null,null,1,false,false,0,0,"/10^10; per 10*10","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per trillion ","/10*12","1/(10*12)","",1e-12,[0,0,0,0,0,0,0],"/1012",null,false,null,null,1,false,false,0,0,"/10^12; per 10*12","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per thousand","/10*3","1/(10*3)","",0.001,[0,0,0,0,0,0,0],"/103",null,false,null,null,1,false,false,0,0,"/10^3; per 10*3","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per million","/10*6","1/(10*6)","",0.000001,[0,0,0,0,0,0,0],"/106",null,false,null,null,1,false,false,0,0,"/10^6; per 10*6;","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per billion","/10*9","1/(10*9)","",1e-9,[0,0,0,0,0,0,0],"/109",null,false,null,null,1,false,false,0,0,"/10^9; per 10*9","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per 100","/100","1/100","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"per hundred; 10^2; 10*2","LOINC","NFr","Clinical","used for counting entities, e.g. blood cells; usually these kinds of terms have numerators such as moles or milligrams, and counting that amount per the number in the denominator",null,null,null,null,false],[false,"per 100 cells","/100{cells}","/100{CELLS}","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"/100 cells; /100cells; per hundred","LOINC","EntMass; EntNum; NFr","Clinical","",null,null,null,null,false],[false,"per 100 neutrophils","/100{neutrophils}","/100{NEUTROPHILS}","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"/100 neutrophils; /100neutrophils; per hundred","LOINC","EntMass; EntNum; NFr","Clinical","",null,null,null,null,false],[false,"per 100 spermatozoa","/100{spermatozoa}","/100{SPERMATOZOA}","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"/100 spermatozoa; /100spermatozoa; per hundred","LOINC","NFr","Clinical","",null,null,null,null,false],[false,"per 100 white blood cells","/100{WBCs}","/100{WBCS}","",0.01,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"/100 WBCs; /100WBCs; per hundred","LOINC","Ratio; NFr","Clinical","",null,null,null,null,false],[false,"per year","/a","1/ANN","",3.168808781402895e-8,[0,-1,0,0,0,0,0],"/a",null,false,null,null,1,false,false,0,0,"/Years; /yrs; yearly","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per centimeter of water","/cm[H2O]","1/CM[H2O]","",0.000010197162129779282,[1,2,-1,0,0,0,0],"/cm HO2",null,false,null,null,1,false,false,0,0,"/cmH2O; /cm H2O; centimeters; centimetres","LOINC","InvPress","Clinical","",null,null,null,null,false],[false,"per day","/d","1/D","",0.000011574074074074073,[0,-1,0,0,0,0,0],"/d",null,false,null,null,1,false,false,0,0,"/dy; per day","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per deciliter","/dL","1/DL","",10000,[-3,0,0,0,0,0,0],"/dL",null,false,null,null,1,false,false,0,0,"per dL; /deciliter; decilitre","LOINC","NCnc","Clinical","",null,null,null,null,false],[false,"per gram","/g","1/G","",1,[0,0,-1,0,0,0,0],"/g",null,false,null,null,1,false,false,0,0,"/gm; /gram; per g","LOINC","NCnt","Clinical","",null,null,null,null,false],[false,"per hour","/h","1/HR","",0.0002777777777777778,[0,-1,0,0,0,0,0],"/h",null,false,null,null,1,false,false,0,0,"/hr; /hour; per hr","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per kilogram","/kg","1/KG","",0.001,[0,0,-1,0,0,0,0],"/kg",null,false,null,null,1,false,false,0,0,"per kg; per kilogram","LOINC","NCnt","Clinical","",null,null,null,null,false],[false,"per liter","/L","1/L","",1000,[-3,0,0,0,0,0,0],"/L",null,false,null,null,1,false,false,0,0,"/liter; litre","LOINC","NCnc","Clinical","",null,null,null,null,false],[false,"per square meter","/m2","1/M2","",1,[-2,0,0,0,0,0,0],"/m2",null,false,null,null,1,false,false,0,0,"/m^2; /m*2; /sq. m; per square meter; meter squared; metre","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"per cubic meter","/m3","1/M3","",1,[-3,0,0,0,0,0,0],"/m3",null,false,null,null,1,false,false,0,0,"/m^3; /m*3; /cu. m; per cubic meter; meter cubed; per m3; metre","LOINC","NCncn","Clinical","",null,null,null,null,false],[false,"per milligram","/mg","1/MG","",1000,[0,0,-1,0,0,0,0],"/mg",null,false,null,null,1,false,false,0,0,"/milligram; per mg","LOINC","NCnt","Clinical","",null,null,null,null,false],[false,"per minute","/min","1/MIN","",0.016666666666666666,[0,-1,0,0,0,0,0],"/min",null,false,null,null,1,false,false,0,0,"/minute; per mins; breaths beats per minute","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per milliliter","/mL","1/ML","",1000000,[-3,0,0,0,0,0,0],"/mL",null,false,null,null,1,false,false,0,0,"/milliliter; per mL; millilitre","LOINC","NCncn","Clinical","",null,null,null,null,false],[false,"per millimeter","/mm","1/MM","",1000,[-1,0,0,0,0,0,0],"/mm",null,false,null,null,1,false,false,0,0,"/millimeter; per mm; millimetre","LOINC","InvLen","Clinical","",null,null,null,null,false],[false,"per month","/mo","1/MO","",3.802570537683474e-7,[0,-1,0,0,0,0,0],"/mo",null,false,null,null,1,false,false,0,0,"/month; per mo; monthly; month","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per second","/s","1/S","",1,[0,-1,0,0,0,0,0],"/s",null,false,null,null,1,false,false,0,0,"/second; /sec; per sec; frequency; Hertz; Herz; Hz; becquerels; Bq; s-1; s^-1","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"per enzyme unit","/U","1/U","",9.963241120049633e-17,[0,1,0,0,0,0,0],"/U",null,false,null,null,1,false,false,-1,0,"/enzyme units; per U","LOINC","InvC; NCat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)",null,null,null,null,false],[false,"per microliter","/uL","1/UL","",999999999.9999999,[-3,0,0,0,0,0,0],"/μL",null,false,null,null,1,false,false,0,0,"/microliter; microlitre; /mcl; per uL","LOINC","ACnc","Clinical","",null,null,null,null,false],[false,"per week","/wk","1/WK","",0.0000016534391534391535,[0,-1,0,0,0,0,0],"/wk",null,false,null,null,1,false,false,0,0,"/week; per wk; weekly, weeks","LOINC","NRat","Clinical","",null,null,null,null,false],[false,"APL unit per milliliter","[APL'U]/mL","[APL'U]/ML","biologic activity of anticardiolipin IgA",1000000,[-3,0,0,0,0,0,0],"/mL","chemical",false,null,null,1,false,true,0,0,"APL/mL; APL'U/mL; APL U/mL; APL/milliliter; IgA anticardiolipin units per milliliter; IgA Phospholipid Units; millilitre; biologic activity of","LOINC","ACnc","Clinical","Units for an anti phospholipid syndrome test","1","1","1",1,false],[false,"arbitrary unit per milliliter","[arb'U]/mL","[ARB'U]/ML","arbitrary",1000000,[-3,0,0,0,0,0,0],"(arb. U)/mL","chemical",false,null,null,1,false,true,0,0,"arb'U/mL; arbU/mL; arb U/mL; arbitrary units per milliliter; millilitre","LOINC","ACnc","Clinical","relative unit of measurement to show the ratio of test measurement to reference measurement","1","1","1",1,false],[false,"colony forming units per liter","[CFU]/L","[CFU]/L","amount of a proliferating organism",1000,[-3,0,0,0,0,0,0],"CFU/L","chemical",false,null,null,1,false,true,0,0,"CFU per Liter; CFU/L","LOINC","NCnc","Clinical","","1","1","1",1,false],[false,"colony forming units per milliliter","[CFU]/mL","[CFU]/ML","amount of a proliferating organism",1000000,[-3,0,0,0,0,0,0],"CFU/mL","chemical",false,null,null,1,false,true,0,0,"CFU per mL; CFU/mL","LOINC","NCnc","Clinical","","1","1","1",1,false],[false,"foot per foot - US","[ft_us]/[ft_us]","[FT_US]/[FT_US]","length",1,[0,0,0,0,0,0,0],"(ftus)/(ftus)","us-lengths",false,null,null,1,false,false,0,0,"ft/ft; ft per ft; feet per feet; visual acuity","","LenRto","Clinical","distance ratio to measure 20:20 vision","m/3937","M/3937","1200",1200,false],[false,"GPL unit per milliliter","[GPL'U]/mL","[GPL'U]/ML","biologic activity of anticardiolipin IgG",1000000,[-3,0,0,0,0,0,0],"/mL","chemical",false,null,null,1,false,true,0,0,"GPL U/mL; GPL'U/mL; GPL/mL; GPL U per mL; IgG Phospholipid Units per milliliters; IgG anticardiolipin units; millilitres ","LOINC","ACnc; AMass","Clinical","Units for an antiphospholipid test","1","1","1",1,false],[false,"international unit per 2 hour","[IU]/(2.h)","[IU]/(2.HR)","arbitrary",0.0001388888888888889,[0,-1,0,0,0,0,0],"(i.U.)/h","chemical",true,null,null,1,false,true,0,0,"IU/2hrs; IU/2 hours; IU per 2 hrs; international units per 2 hours","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per 24 hour","[IU]/(24.h)","[IU]/(24.HR)","arbitrary",0.000011574074074074073,[0,-1,0,0,0,0,0],"(i.U.)/h","chemical",true,null,null,1,false,true,0,0,"IU/24hr; IU/24 hours; IU per 24 hrs; international units per 24 hours","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per day","[IU]/d","[IU]/D","arbitrary",0.000011574074074074073,[0,-1,0,0,0,0,0],"(i.U.)/d","chemical",true,null,null,1,false,true,0,0,"IU/dy; IU/days; IU per dys; international units per day","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per deciliter","[IU]/dL","[IU]/DL","arbitrary",10000,[-3,0,0,0,0,0,0],"(i.U.)/dL","chemical",true,null,null,1,false,true,0,0,"IU/dL; IU per dL; international units per deciliters; decilitres","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per gram","[IU]/g","[IU]/G","arbitrary",1,[0,0,-1,0,0,0,0],"(i.U.)/g","chemical",true,null,null,1,false,true,0,0,"IU/gm; IU/gram; IU per gm; IU per g; international units per gram","LOINC","ACnt","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per hour","[IU]/h","[IU]/HR","arbitrary",0.0002777777777777778,[0,-1,0,0,0,0,0],"(i.U.)/h","chemical",true,null,null,1,false,true,0,0,"IU/hrs; IU per hours; international units per hour","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per kilogram","[IU]/kg","[IU]/KG","arbitrary",0.001,[0,0,-1,0,0,0,0],"(i.U.)/kg","chemical",true,null,null,1,false,true,0,0,"IU/kg; IU/kilogram; IU per kg; units","LOINC","ACnt","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per kilogram per day","[IU]/kg/d","([IU]/KG)/D","arbitrary",1.1574074074074074e-8,[0,-1,-1,0,0,0,0],"((i.U.)/kg)/d","chemical",true,null,null,1,false,true,0,0,"IU/kg/dy; IU/kg/day; IU/kilogram/day; IU per kg per day; units","LOINC","ACntRat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per liter","[IU]/L","[IU]/L","arbitrary",1000,[-3,0,0,0,0,0,0],"(i.U.)/L","chemical",true,null,null,1,false,true,0,0,"IU/L; IU/liter; IU per liter; units; litre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per minute","[IU]/min","[IU]/MIN","arbitrary",0.016666666666666666,[0,-1,0,0,0,0,0],"(i.U.)/min","chemical",true,null,null,1,false,true,0,0,"IU/min; IU/minute; IU per minute; international units","LOINC","ARat","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"international unit per milliliter","[IU]/mL","[IU]/ML","arbitrary",1000000,[-3,0,0,0,0,0,0],"(i.U.)/mL","chemical",true,null,null,1,false,true,0,0,"IU/mL; IU per mL; international units per milliliter; millilitre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"MPL unit per milliliter","[MPL'U]/mL","[MPL'U]/ML","biologic activity of anticardiolipin IgM",1000000,[-3,0,0,0,0,0,0],"/mL","chemical",false,null,null,1,false,true,0,0,"MPL/mL; MPL U/mL; MPL'U/mL; IgM anticardiolipin units; IgM Phospholipid Units; millilitre ","LOINC","ACnc","Clinical","units for antiphospholipid test\n","1","1","1",1,false],[false,"number per high power field","{#}/[HPF]","{#}/[HPF]","",1,[0,0,0,0,0,0,0],"/HPF",null,false,null,null,1,false,false,0,0,"#/HPF; # per HPF; number/HPF; numbers per high power field","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"number per low power field","{#}/[LPF]","{#}/[LPF]","",1,[0,0,0,0,0,0,0],"/LPF",null,false,null,null,1,false,false,0,0,"#/LPF; # per LPF; number/LPF; numbers per low power field","LOINC","Naric","Clinical","",null,null,null,null,false],[false,"IgA antiphosphatidylserine unit ","{APS'U}","{APS'U}","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"APS Unit; Phosphatidylserine Antibody IgA Units","LOINC","ACnc","Clinical","unit for antiphospholipid test",null,null,null,null,false],[false,"EIA index","{EIA_index}","{EIA_index}","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"enzyme immunoassay index","LOINC","ACnc","Clinical","",null,null,null,null,false],[false,"kaolin clotting time","{KCT'U}","{KCT'U}","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"KCT","LOINC","Time","Clinical","sensitive test to detect lupus anticoagulants; measured in seconds",null,null,null,null,false],[false,"IgM antiphosphatidylserine unit","{MPS'U}","{MPS'U}","",1,[0,0,0,0,0,0,0],null,null,false,null,null,1,false,false,0,0,"Phosphatidylserine Antibody IgM Measurement ","LOINC","ACnc","Clinical","",null,null,null,null,false],[false,"trillion per liter","10*12/L","(10*12)/L","number",1000000000000000,[-3,0,0,0,0,0,0],"(1012)/L","dimless",false,null,null,1,false,false,0,0,"10^12/L; 10*12 per Liter; trillion per liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10^3 (used for cell count)","10*3","10*3","number",1000,[0,0,0,0,0,0,0],"103","dimless",false,null,null,1,false,false,0,0,"10^3; thousand","LOINC","Num","Clinical","usually used for counting entities (e.g. blood cells) per volume","1","1","10",10,false],[false,"thousand per liter","10*3/L","(10*3)/L","number",1000000,[-3,0,0,0,0,0,0],"(103)/L","dimless",false,null,null,1,false,false,0,0,"10^3/L; 10*3 per liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"thousand per milliliter","10*3/mL","(10*3)/ML","number",1000000000,[-3,0,0,0,0,0,0],"(103)/mL","dimless",false,null,null,1,false,false,0,0,"10^3/mL; 10*3 per mL; thousand per milliliter; millilitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"thousand per microliter","10*3/uL","(10*3)/UL","number",999999999999.9999,[-3,0,0,0,0,0,0],"(103)/μL","dimless",false,null,null,1,false,false,0,0,"10^3/uL; 10*3 per uL; thousand per microliter; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10 thousand per microliter","10*4/uL","(10*4)/UL","number",10000000000000,[-3,0,0,0,0,0,0],"(104)/μL","dimless",false,null,null,1,false,false,0,0,"10^4/uL; 10*4 per uL; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10^5 ","10*5","10*5","number",100000,[0,0,0,0,0,0,0],"105","dimless",false,null,null,1,false,false,0,0,"one hundred thousand","LOINC","Num","Clinical","","1","1","10",10,false],[false,"10^6","10*6","10*6","number",1000000,[0,0,0,0,0,0,0],"106","dimless",false,null,null,1,false,false,0,0,"","LOINC","Num","Clinical","","1","1","10",10,false],[false,"million colony forming unit per liter","10*6.[CFU]/L","((10*6).[CFU])/L","number",1000000000,[-3,0,0,0,0,0,0],"((106).CFU)/L","dimless",false,null,null,1,false,true,0,0,"10*6 CFU/L; 10^6 CFU/L; 10^6CFU; 10^6 CFU per liter; million colony forming units; litre","LOINC","ACnc","Clinical","","1","1","10",10,false],[false,"million international unit","10*6.[IU]","(10*6).[IU]","number",1000000,[0,0,0,0,0,0,0],"(106).(i.U.)","dimless",false,null,null,1,false,true,0,0,"10*6 IU; 10^6 IU; international units","LOINC","arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","1","1","10",10,false],[false,"million per 24 hour","10*6/(24.h)","(10*6)/(24.HR)","number",11.574074074074074,[0,-1,0,0,0,0,0],"(106)/h","dimless",false,null,null,1,false,false,0,0,"10*6/24hrs; 10^6/24 hrs; 10*6 per 24 hrs; 10^6 per 24 hours","LOINC","NRat","Clinical","","1","1","10",10,false],[false,"million per kilogram","10*6/kg","(10*6)/KG","number",1000,[0,0,-1,0,0,0,0],"(106)/kg","dimless",false,null,null,1,false,false,0,0,"10^6/kg; 10*6 per kg; 10*6 per kilogram; millions","LOINC","NCnt","Clinical","","1","1","10",10,false],[false,"million per liter","10*6/L","(10*6)/L","number",1000000000,[-3,0,0,0,0,0,0],"(106)/L","dimless",false,null,null,1,false,false,0,0,"10^6/L; 10*6 per Liter; 10^6 per Liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"million per milliliter","10*6/mL","(10*6)/ML","number",1000000000000,[-3,0,0,0,0,0,0],"(106)/mL","dimless",false,null,null,1,false,false,0,0,"10^6/mL; 10*6 per mL; 10*6 per milliliter; millilitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"million per microliter","10*6/uL","(10*6)/UL","number",1000000000000000,[-3,0,0,0,0,0,0],"(106)/μL","dimless",false,null,null,1,false,false,0,0,"10^6/uL; 10^6 per uL; 10^6/mcl; 10^6 per mcl; 10^6 per microliter; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10^8","10*8","10*8","number",100000000,[0,0,0,0,0,0,0],"108","dimless",false,null,null,1,false,false,0,0,"100 million; one hundred million; 10^8","LOINC","Num","Clinical","","1","1","10",10,false],[false,"billion per liter","10*9/L","(10*9)/L","number",1000000000000,[-3,0,0,0,0,0,0],"(109)/L","dimless",false,null,null,1,false,false,0,0,"10^9/L; 10*9 per Liter; litre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"billion per milliliter","10*9/mL","(10*9)/ML","number",1000000000000000,[-3,0,0,0,0,0,0],"(109)/mL","dimless",false,null,null,1,false,false,0,0,"10^9/mL; 10*9 per mL; 10^9 per mL; 10*9 per milliliter; millilitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"billion per microliter","10*9/uL","(10*9)/UL","number",1000000000000000000,[-3,0,0,0,0,0,0],"(109)/μL","dimless",false,null,null,1,false,false,0,0,"10^9/uL; 10^9 per uL; 10^9/mcl; 10^9 per mcl; 10*9 per uL; 10*9 per mcl; 10*9/mcl; 10^9 per microliter; microlitre","LOINC","NCncn","Clinical","","1","1","10",10,false],[false,"10 liter per minute per square meter","10.L/(min.m2)","(10.L)/(MIN.M2)","",0.00016666666666666666,[1,-1,0,0,0,0,0],"L/(min.(m2))",null,false,null,null,1,false,false,0,0,"10 liters per minutes per square meter; 10 L per min per m2; m^2; 10 L/(min*m2); 10L/(min*m^2); litres; sq. meter; metre; meters squared","LOINC","ArVRat","Clinical","",null,null,null,null,false],[false,"10 liter per minute","10.L/min","(10.L)/MIN","",0.00016666666666666666,[3,-1,0,0,0,0,0],"L/min",null,false,null,null,1,false,false,0,0,"10 liters per minute; 10 L per min; 10L; 10 L/min; litre","LOINC","VRat","Clinical","",null,null,null,null,false],[false,"10 micronewton second per centimeter to the fifth power per square meter","10.uN.s/(cm5.m2)","((10.UN).S)/(CM5.M2)","",100000000,[-6,-1,1,0,0,0,0],"(μN.s)/(cm5).(m2)",null,false,null,null,1,false,false,0,0,"dyne seconds per centimeter5 and square meter; dyn.s/(cm5.m2); dyn.s/cm5/m2; cm^5; m^2","LOINC","","Clinical","unit to measure systemic vascular resistance per body surface area",null,null,null,null,false],[false,"24 hour","24.h","24.HR","",86400,[0,1,0,0,0,0,0],"h",null,false,null,null,1,false,false,0,0,"24hrs; 24 hrs; 24 hours; days; dy","LOINC","Time","Clinical","",null,null,null,null,false],[false,"ampere per meter","A/m","A/M","electric current",1,[-1,-1,0,0,0,1,0],"A/m","si",true,null,null,1,false,false,0,0,"A/m; amp/meter; magnetic field strength; H; B; amperes per meter; metre","LOINC","","Clinical","unit of magnetic field strength","C/s","C/S","1",1,false],[false,"centigram","cg","CG","mass",0.01,[0,0,1,0,0,0,0],"cg",null,false,"M",null,1,false,false,0,0,"centigrams; cg; cgm","LOINC","Mass","Clinical","",null,null,null,null,false],[false,"centiliter","cL","CL","volume",0.00001,[3,0,0,0,0,0,0],"cL","iso1000",true,null,null,1,false,false,0,0,"centiliters; centilitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"centimeter","cm","CM","length",0.01,[1,0,0,0,0,0,0],"cm",null,false,"L",null,1,false,false,0,0,"centimeters; centimetres","LOINC","Len","Clinical","",null,null,null,null,false],[false,"centimeter of water","cm[H2O]","CM[H2O]","pressure",98066.5,[-1,-2,1,0,0,0,0],"cm HO2","clinical",true,null,null,1,false,false,0,0,"cm H2O; cmH2O; centimetres; pressure","LOINC","Pres","Clinical","unit of pressure mostly applies to blood pressure","kPa","KPAL","980665e-5",9.80665,false],[false,"centimeter of water per liter per second","cm[H2O]/L/s","(CM[H2O]/L)/S","pressure",98066500,[-4,-3,1,0,0,0,0],"((cm HO2)/L)/s","clinical",true,null,null,1,false,false,0,0,"cm[H2O]/(L/s); cm[H2O].s/L; cm H2O/L/sec; cmH2O/L/sec; cmH2O/Liter; cmH2O per L per secs; centimeters of water per liters per second; centimetres; litres; cm[H2O]/(L/s)","LOINC","PresRat","Clinical","unit used to measure mean pulmonary resistance","kPa","KPAL","980665e-5",9.80665,false],[false,"centimeter of water per second per meter","cm[H2O]/s/m","(CM[H2O]/S)/M","pressure",98066.5,[-2,-3,1,0,0,0,0],"((cm HO2)/s)/m","clinical",true,null,null,1,false,false,0,0,"cm[H2O]/(s.m); cm H2O/s/m; cmH2O; cmH2O/sec/m; cmH2O per secs per meters; centimeters of water per seconds per meter; centimetres; metre","LOINC","PresRat","Clinical","unit used to measure pulmonary pressure time product","kPa","KPAL","980665e-5",9.80665,false],[false,"centimeter of mercury","cm[Hg]","CM[HG]","pressure",1333220,[-1,-2,1,0,0,0,0],"cm Hg","clinical",true,null,null,1,false,false,0,0,"centimeters of mercury; centimetres; cmHg; cm Hg","LOINC","Pres","Clinical","unit of pressure where 1 cmHg = 10 torr","kPa","KPAL","133.3220",133.322,false],[false,"square centimeter","cm2","CM2","length",0.0001,[2,0,0,0,0,0,0],"cm2",null,false,"L",null,1,false,false,0,0,"cm^2; sq cm; centimeters squared; square centimeters; centimetre; area","LOINC","Area","Clinical","",null,null,null,null,false],[false,"square centimeter per second","cm2/s","CM2/S","length",0.0001,[2,-1,0,0,0,0,0],"(cm2)/s",null,false,"L",null,1,false,false,0,0,"cm^2/sec; square centimeters per second; sq cm per sec; cm2; centimeters squared; centimetres","LOINC","AreaRat","Clinical","",null,null,null,null,false],[false,"centipoise","cP","CP","dynamic viscosity",1.0000000000000002,[-1,-1,1,0,0,0,0],"cP","cgs",true,null,null,1,false,false,0,0,"cps; centiposes","LOINC","Visc","Clinical","unit of dynamic viscosity in the CGS system with base units: 10^−3 Pa.s = 1 mPa·.s (1 millipascal second)","dyn.s/cm2","DYN.S/CM2","1",1,false],[false,"centistoke","cSt","CST","kinematic viscosity",0.000001,[2,-1,0,0,0,0,0],"cSt","cgs",true,null,null,1,false,false,0,0,"centistokes","LOINC","Visc","Clinical","unit for kinematic viscosity with base units of mm^2/s (square millimeter per second)","cm2/s","CM2/S","1",1,false],[false,"dekaliter per minute","daL/min","DAL/MIN","volume",0.00016666666666666666,[3,-1,0,0,0,0,0],"daL/min","iso1000",true,null,null,1,false,false,0,0,"dekalitres; dekaliters per minute; per min","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"dekaliter per minute per square meter","daL/min/m2","(DAL/MIN)/M2","volume",0.00016666666666666666,[1,-1,0,0,0,0,0],"(daL/min)/(m2)","iso1000",true,null,null,1,false,false,0,0,"daL/min/m^2; daL/minute/m2; sq. meter; dekaliters per minutes per square meter; meter squared; dekalitres; metre","LOINC","ArVRat","Clinical","The area usually is the body surface area used to normalize cardiovascular measures for patient's size","l",null,"1",1,false],[false,"decibel","dB","DB","level",1,[0,0,0,0,0,0,0],"dB","levels",true,null,"lg",0.1,true,false,0,0,"decibels","LOINC","LogRto","Clinical","unit most commonly used in acoustics as unit of sound pressure level. (also see B[SPL] or bel sound pressure level). ","1",null,null,1,false],[false,"degree per second","deg/s","DEG/S","plane angle",0.017453292519943295,[0,-1,0,1,0,0,0],"°/s","iso1000",false,null,null,1,false,false,0,0,"deg/sec; deg per sec; °/sec; twist rate; angular speed; rotational speed","LOINC","ARat","Clinical","unit of angular (rotational) speed used to express turning rate","[pi].rad/360","[PI].RAD/360","2",2,false],[false,"decigram","dg","DG","mass",0.1,[0,0,1,0,0,0,0],"dg",null,false,"M",null,1,false,false,0,0,"decigrams; dgm; 0.1 grams; 1/10 gm","LOINC","Mass","Clinical","equal to 1/10 gram",null,null,null,null,false],[false,"deciliter","dL","DL","volume",0.0001,[3,0,0,0,0,0,0],"dL","iso1000",true,null,null,1,false,false,0,0,"deciliters; decilitres; 0.1 liters; 1/10 L","LOINC","Vol","Clinical","equal to 1/10 liter","l",null,"1",1,false],[false,"decimeter","dm","DM","length",0.1,[1,0,0,0,0,0,0],"dm",null,false,"L",null,1,false,false,0,0,"decimeters; decimetres; 0.1 meters; 1/10 m; 10 cm; centimeters","LOINC","Len","Clinical","equal to 1/10 meter or 10 centimeters",null,null,null,null,false],[false,"square decimeter per square second","dm2/s2","DM2/S2","length",0.010000000000000002,[2,-2,0,0,0,0,0],"(dm2)/(s2)",null,false,"L",null,1,false,false,0,0,"dm2 per s2; dm^2/s^2; decimeters squared per second squared; sq dm; sq sec","LOINC","EngMass (massic energy)","Clinical","units for energy per unit mass or Joules per kilogram (J/kg = kg.m2/s2/kg = m2/s2) ",null,null,null,null,false],[false,"dyne second per centimeter per square meter","dyn.s/(cm.m2)","(DYN.S)/(CM.M2)","force",1,[-2,-1,1,0,0,0,0],"(dyn.s)/(cm.(m2))","cgs",true,null,null,1,false,false,0,0,"(dyn*s)/(cm*m2); (dyn*s)/(cm*m^2); dyn s per cm per m2; m^2; dyne seconds per centimeters per square meter; centimetres; sq. meter; squared","LOINC","","Clinical","","g.cm/s2","G.CM/S2","1",1,false],[false,"dyne second per centimeter","dyn.s/cm","(DYN.S)/CM","force",1,[0,-1,1,0,0,0,0],"(dyn.s)/cm","cgs",true,null,null,1,false,false,0,0,"(dyn*s)/cm; dyn sec per cm; seconds; centimetre; dyne seconds","LOINC","","Clinical","","g.cm/s2","G.CM/S2","1",1,false],[false,"equivalent per liter","eq/L","EQ/L","amount of substance",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"eq/L","chemical",true,null,null,1,false,false,0,1,"eq/liter; eq/litre; eqs; equivalents per liter; litre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"equivalent per milliliter","eq/mL","EQ/ML","amount of substance",6.0221367e+29,[-3,0,0,0,0,0,0],"eq/mL","chemical",true,null,null,1,false,false,0,1,"equivalent/milliliter; equivalents per milliliter; eq per mL; millilitre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"equivalent per millimole","eq/mmol","EQ/MMOL","amount of substance",1000,[0,0,0,0,0,0,0],"eq/mmol","chemical",true,null,null,1,false,false,-1,1,"equivalent/millimole; equivalents per millimole; eq per mmol","LOINC","SRto","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"equivalent per micromole","eq/umol","EQ/UMOL","amount of substance",1000000,[0,0,0,0,0,0,0],"eq/μmol","chemical",true,null,null,1,false,false,-1,1,"equivalent/micromole; equivalents per micromole; eq per umol","LOINC","SRto","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"femtogram","fg","FG","mass",1e-15,[0,0,1,0,0,0,0],"fg",null,false,"M",null,1,false,false,0,0,"fg; fgm; femtograms; weight","LOINC","Mass","Clinical","equal to 10^-15 grams",null,null,null,null,false],[false,"femtoliter","fL","FL","volume",1e-18,[3,0,0,0,0,0,0],"fL","iso1000",true,null,null,1,false,false,0,0,"femtolitres; femtoliters","LOINC","Vol; EntVol","Clinical","equal to 10^-15 liters","l",null,"1",1,false],[false,"femtometer","fm","FM","length",1e-15,[1,0,0,0,0,0,0],"fm",null,false,"L",null,1,false,false,0,0,"femtometres; femtometers","LOINC","Len","Clinical","equal to 10^-15 meters",null,null,null,null,false],[false,"femtomole","fmol","FMOL","amount of substance",602213670,[0,0,0,0,0,0,0],"fmol","si",true,null,null,1,false,false,1,0,"femtomoles","LOINC","EntSub","Clinical","equal to 10^-15 moles","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per gram","fmol/g","FMOL/G","amount of substance",602213670,[0,0,-1,0,0,0,0],"fmol/g","si",true,null,null,1,false,false,1,0,"femtomoles; fmol/gm; fmol per gm","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per liter","fmol/L","FMOL/L","amount of substance",602213670000,[-3,0,0,0,0,0,0],"fmol/L","si",true,null,null,1,false,false,1,0,"femtomoles; fmol per liter; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per milligram","fmol/mg","FMOL/MG","amount of substance",602213670000,[0,0,-1,0,0,0,0],"fmol/mg","si",true,null,null,1,false,false,1,0,"fmol per mg; femtomoles","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"femtomole per milliliter","fmol/mL","FMOL/ML","amount of substance",602213670000000,[-3,0,0,0,0,0,0],"fmol/mL","si",true,null,null,1,false,false,1,0,"femtomoles; millilitre; fmol per mL; fmol per milliliter","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"gram meter","g.m","G.M","mass",1,[1,0,1,0,0,0,0],"g.m",null,false,"M",null,1,false,false,0,0,"g*m; gxm; meters; metres","LOINC","Enrg","Clinical","Unit for measuring stroke work (heart work)",null,null,null,null,false],[false,"gram per 100 gram","g/(100.g)","G/(100.G)","mass",0.01,[0,0,0,0,0,0,0],"g/g",null,false,"M",null,1,false,false,0,0,"g/100 gm; 100gm; grams per 100 grams; gm per 100 gm","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"gram per 12 hour","g/(12.h)","G/(12.HR)","mass",0.000023148148148148147,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/12hrs; 12 hrs; gm per 12 hrs; 12hrs; grams per 12 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 24 hour","g/(24.h)","G/(24.HR)","mass",0.000011574074074074073,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/24hrs; gm/24 hrs; gm per 24 hrs; 24hrs; grams per 24 hours; gm/dy; gm per dy; grams per day","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 3 days","g/(3.d)","G/(3.D)","mass",0.000003858024691358025,[0,-1,1,0,0,0,0],"g/d",null,false,"M",null,1,false,false,0,0,"gm/3dy; gm/3 dy; gm per 3 days; grams","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 4 hour","g/(4.h)","G/(4.HR)","mass",0.00006944444444444444,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/4hrs; gm/4 hrs; gm per 4 hrs; 4hrs; grams per 4 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 48 hour","g/(48.h)","G/(48.HR)","mass",0.000005787037037037037,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/48hrs; gm/48 hrs; gm per 48 hrs; 48hrs; grams per 48 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 5 hour","g/(5.h)","G/(5.HR)","mass",0.00005555555555555556,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/5hrs; gm/5 hrs; gm per 5 hrs; 5hrs; grams per 5 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 6 hour","g/(6.h)","G/(6.HR)","mass",0.000046296296296296294,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/6hrs; gm/6 hrs; gm per 6 hrs; 6hrs; grams per 6 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per 72 hour","g/(72.h)","G/(72.HR)","mass",0.000003858024691358025,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/72hrs; gm/72 hrs; gm per 72 hrs; 72hrs; grams per 72 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per cubic centimeter","g/cm3","G/CM3","mass",999999.9999999999,[-3,0,1,0,0,0,0],"g/(cm3)",null,false,"M",null,1,false,false,0,0,"g/cm^3; gm per cm3; g per cm^3; grams per centimeter cubed; cu. cm; centimetre; g/mL; gram per milliliter; millilitre","LOINC","MCnc","Clinical","g/cm3 = g/mL",null,null,null,null,false],[false,"gram per day","g/d","G/D","mass",0.000011574074074074073,[0,-1,1,0,0,0,0],"g/d",null,false,"M",null,1,false,false,0,0,"gm/dy; gm per dy; grams per day; gm/24hrs; gm/24 hrs; gm per 24 hrs; 24hrs; grams per 24 hours; serving","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per deciliter","g/dL","G/DL","mass",10000,[-3,0,1,0,0,0,0],"g/dL",null,false,"M",null,1,false,false,0,0,"gm/dL; gm per dL; grams per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"gram per gram","g/g","G/G","mass",1,[0,0,0,0,0,0,0],"g/g",null,false,"M",null,1,false,false,0,0,"gm; grams","LOINC","MRto ","Clinical","",null,null,null,null,false],[false,"gram per hour","g/h","G/HR","mass",0.0002777777777777778,[0,-1,1,0,0,0,0],"g/h",null,false,"M",null,1,false,false,0,0,"gm/hr; gm per hr; grams; intake; output","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per hour per square meter","g/h/m2","(G/HR)/M2","mass",0.0002777777777777778,[-2,-1,1,0,0,0,0],"(g/h)/(m2)",null,false,"M",null,1,false,false,0,0,"gm/hr/m2; gm/h/m2; /m^2; sq. m; g per hr per m2; grams per hours per square meter; meter squared; metre","LOINC","ArMRat","Clinical","",null,null,null,null,false],[false,"gram per kilogram","g/kg ","G/KG","mass",0.001,[0,0,0,0,0,0,0],"g/kg",null,false,"M",null,1,false,false,0,0,"g per kg; gram per kilograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"gram per kilogram per 8 hour ","g/kg/(8.h)","(G/KG)/(8.HR)","mass",3.472222222222222e-8,[0,-1,0,0,0,0,0],"(g/kg)/h",null,false,"M",null,1,false,false,0,0,"g/(8.kg.h); gm/kg/8hrs; 8 hrs; g per kg per 8 hrs; 8hrs; grams per kilograms per 8 hours; shift","LOINC","MCntRat; RelMRat","Clinical","unit often used to describe mass in grams of protein consumed in a 8 hours, divided by the subject's body weight in kilograms. Also used to measure mass dose rate per body mass",null,null,null,null,false],[false,"gram per kilogram per day","g/kg/d","(G/KG)/D","mass",1.1574074074074074e-8,[0,-1,0,0,0,0,0],"(g/kg)/d",null,false,"M",null,1,false,false,0,0,"g/(kg.d); gm/kg/dy; gm per kg per dy; grams per kilograms per day","LOINC","RelMRat","Clinical","unit often used to describe mass in grams of protein consumed in a day, divided by the subject's body weight in kilograms. Also used to measure mass dose rate per body mass",null,null,null,null,false],[false,"gram per kilogram per hour","g/kg/h","(G/KG)/HR","mass",2.7777777777777776e-7,[0,-1,0,0,0,0,0],"(g/kg)/h",null,false,"M",null,1,false,false,0,0,"g/(kg.h); g/kg/hr; g per kg per hrs; grams per kilograms per hour","LOINC","MCntRat; RelMRat","Clinical","unit used to measure mass dose rate per body mass",null,null,null,null,false],[false,"gram per kilogram per minute","g/kg/min","(G/KG)/MIN","mass",0.000016666666666666667,[0,-1,0,0,0,0,0],"(g/kg)/min",null,false,"M",null,1,false,false,0,0,"g/(kg.min); g/kg/min; g per kg per min; grams per kilograms per minute","LOINC","MCntRat; RelMRat","Clinical","unit used to measure mass dose rate per body mass",null,null,null,null,false],[false,"gram per liter","g/L","G/L","mass",1000,[-3,0,1,0,0,0,0],"g/L",null,false,"M",null,1,false,false,0,0,"gm per liter; g/liter; grams per liter; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"gram per square meter","g/m2","G/M2","mass",1,[-2,0,1,0,0,0,0],"g/(m2)",null,false,"M",null,1,false,false,0,0,"g/m^2; gram/square meter; g/sq m; g per m2; g per m^2; grams per square meter; meters squared; metre","LOINC","ArMass","Clinical","Tests measure myocardial mass (heart ventricle system) per body surface area; unit used to measure mass dose per body surface area",null,null,null,null,false],[false,"gram per milligram","g/mg","G/MG","mass",1000,[0,0,0,0,0,0,0],"g/mg",null,false,"M",null,1,false,false,0,0,"g per mg; grams per milligram","LOINC","MCnt; MRto","Clinical","",null,null,null,null,false],[false,"gram per minute","g/min","G/MIN","mass",0.016666666666666666,[0,-1,1,0,0,0,0],"g/min",null,false,"M",null,1,false,false,0,0,"g per min; grams per minute; gram/minute","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"gram per milliliter","g/mL","G/ML","mass",1000000,[-3,0,1,0,0,0,0],"g/mL",null,false,"M",null,1,false,false,0,0,"g per mL; grams per milliliter; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"gram per millimole","g/mmol","G/MMOL","mass",1.6605401866749388e-21,[0,0,1,0,0,0,0],"g/mmol",null,false,"M",null,1,false,false,-1,0,"grams per millimole; g per mmol","LOINC","Ratio","Clinical","",null,null,null,null,false],[false,"joule per liter","J/L","J/L","energy",1000000,[-1,-2,1,0,0,0,0],"J/L","si",true,null,null,1,false,false,0,0,"joules per liter; litre; J per L","LOINC","EngCnc","Clinical","","N.m","N.M","1",1,false],[false,"degree Kelvin per Watt","K/W","K/W","temperature",0.001,[-2,3,-1,0,1,0,0],"K/W",null,false,"C",null,1,false,false,0,0,"degree Kelvin/Watt; K per W; thermal ohm; thermal resistance; degrees","LOINC","TempEngRat","Clinical","unit for absolute thermal resistance equal to the reciprocal of thermal conductance. Unit used for tests to measure work of breathing",null,null,null,null,false],[false,"kilo international unit per liter","k[IU]/L","K[IU]/L","arbitrary",1000000,[-3,0,0,0,0,0,0],"(ki.U.)/L","chemical",true,null,null,1,false,true,0,0,"kIU/L; kIU per L; kIU per liter; kilo international units; litre; allergens; allergy units","LOINC","ACnc","Clinical","IgE has an WHO reference standard so IgE allergen testing can be reported as k[IU]/L","[iU]","[IU]","1",1,false],[false,"kilo international unit per milliliter","k[IU]/mL","K[IU]/ML","arbitrary",1000000000,[-3,0,0,0,0,0,0],"(ki.U.)/mL","chemical",true,null,null,1,false,true,0,0,"kIU/mL; kIU per mL; kIU per milliliter; kilo international units; millilitre; allergens; allergy units","LOINC","ACnc","Clinical","IgE has an WHO reference standard so IgE allergen testing can be reported as k[IU]/mL","[iU]","[IU]","1",1,false],[false,"katal per kilogram","kat/kg","KAT/KG","catalytic activity",602213670000000000000,[0,-1,-1,0,0,0,0],"kat/kg","chemical",true,null,null,1,false,false,1,0,"kat per kg; katals per kilogram; mol/s/kg; moles per seconds per kilogram","LOINC","CCnt","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"katal per liter","kat/L","KAT/L","catalytic activity",6.0221366999999994e+26,[-3,-1,0,0,0,0,0],"kat/L","chemical",true,null,null,1,false,false,1,0,"kat per L; katals per liter; litre; mol/s/L; moles per seconds per liter","LOINC","CCnc","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"kilocalorie","kcal","KCAL","energy",4184000,[2,-2,1,0,0,0,0],"kcal","heat",true,null,null,1,false,false,0,0,"kilogram calories; large calories; food calories; kcals","LOINC","EngRat","Clinical","It is equal to 1000 calories (equal to 4.184 kJ). But in practical usage, kcal refers to food calories which excludes caloric content in fiber and other constitutes that is not digestible by humans. Also see nutrition label Calories ([Cal])","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per 24 hour","kcal/(24.h)","KCAL/(24.HR)","energy",48.425925925925924,[2,-3,1,0,0,0,0],"kcal/h","heat",true,null,null,1,false,false,0,0,"kcal/24hrs; kcal/24 hrs; kcal per 24hrs; kilocalories per 24 hours; kilojoules; kJ/24hr; kJ/(24.h); kJ/dy; kilojoules per days; intake; calories burned; metabolic rate; food calories","","EngRat","Clinical","","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per ounce","kcal/[oz_av]","KCAL/[OZ_AV]","energy",147586.25679704445,[2,-2,0,0,0,0,0],"kcal/oz","heat",true,null,null,1,false,false,0,0,"kcal/oz; kcal per ozs; large calories per ounces; food calories; servings; international","LOINC","EngCnt","Clinical","used in nutrition to represent calorie of food","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per day","kcal/d","KCAL/D","energy",48.425925925925924,[2,-3,1,0,0,0,0],"kcal/d","heat",true,null,null,1,false,false,0,0,"kcal/dy; kcal per day; kilocalories per days; kilojoules; kJ/dy; kilojoules per days; intake; calories burned; metabolic rate; food calories","LOINC","EngRat","Clinical","unit in nutrition for food intake (measured in calories) in a day","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per hour","kcal/h","KCAL/HR","energy",1162.2222222222222,[2,-3,1,0,0,0,0],"kcal/h","heat",true,null,null,1,false,false,0,0,"kcal/hrs; kcals per hr; intake; kilocalories per hours; kilojoules","LOINC","EngRat","Clinical","used in nutrition to represent caloric requirement or consumption","cal_th","CAL_TH","1",1,false],[false,"kilocalorie per kilogram per 24 hour","kcal/kg/(24.h)","(KCAL/KG)/(24.HR)","energy",0.04842592592592593,[2,-3,0,0,0,0,0],"(kcal/kg)/h","heat",true,null,null,1,false,false,0,0,"kcal/kg/24hrs; 24 hrs; kcal per kg per 24hrs; kilocalories per kilograms per 24 hours; kilojoules","LOINC","EngCntRat","Clinical","used in nutrition to represent caloric requirement per day based on subject's body weight in kilograms","cal_th","CAL_TH","1",1,false],[false,"kilogram","kg","KG","mass",1000,[0,0,1,0,0,0,0],"kg",null,false,"M",null,1,false,false,0,0,"kilograms; kgs","LOINC","Mass","Clinical","",null,null,null,null,false],[false,"kilogram meter per second","kg.m/s","(KG.M)/S","mass",1000,[1,-1,1,0,0,0,0],"(kg.m)/s",null,false,"M",null,1,false,false,0,0,"kg*m/s; kg.m per sec; kg*m per sec; p; momentum","LOINC","","Clinical","unit for momentum = mass times velocity",null,null,null,null,false],[false,"kilogram per second per square meter","kg/(s.m2)","KG/(S.M2)","mass",1000,[-2,-1,1,0,0,0,0],"kg/(s.(m2))",null,false,"M",null,1,false,false,0,0,"kg/(s*m2); kg/(s*m^2); kg per s per m2; per sec; per m^2; kilograms per seconds per square meter; meter squared; metre","LOINC","ArMRat","Clinical","",null,null,null,null,false],[false,"kilogram per hour","kg/h","KG/HR","mass",0.2777777777777778,[0,-1,1,0,0,0,0],"kg/h",null,false,"M",null,1,false,false,0,0,"kg/hr; kg per hr; kilograms per hour","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"kilogram per liter","kg/L","KG/L","mass",1000000,[-3,0,1,0,0,0,0],"kg/L",null,false,"M",null,1,false,false,0,0,"kg per liter; litre; kilograms","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"kilogram per square meter","kg/m2","KG/M2","mass",1000,[-2,0,1,0,0,0,0],"kg/(m2)",null,false,"M",null,1,false,false,0,0,"kg/m^2; kg/sq. m; kg per m2; per m^2; per sq. m; kilograms; meter squared; metre; BMI","LOINC","Ratio","Clinical","units for body mass index (BMI)",null,null,null,null,false],[false,"kilogram per cubic meter","kg/m3","KG/M3","mass",1000,[-3,0,1,0,0,0,0],"kg/(m3)",null,false,"M",null,1,false,false,0,0,"kg/m^3; kg/cu. m; kg per m3; per m^3; per cu. m; kilograms; meters cubed; metre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"kilogram per minute","kg/min","KG/MIN","mass",16.666666666666668,[0,-1,1,0,0,0,0],"kg/min",null,false,"M",null,1,false,false,0,0,"kilogram/minute; kg per min; kilograms per minute","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"kilogram per mole","kg/mol","KG/MOL","mass",1.6605401866749388e-21,[0,0,1,0,0,0,0],"kg/mol",null,false,"M",null,1,false,false,-1,0,"kilogram/mole; kg per mol; kilograms per mole","LOINC","SCnt","Clinical","",null,null,null,null,false],[false,"kilogram per second","kg/s","KG/S","mass",1000,[0,-1,1,0,0,0,0],"kg/s",null,false,"M",null,1,false,false,0,0,"kg/sec; kilogram/second; kg per sec; kilograms; second","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"kiloliter","kL","KL","volume",1,[3,0,0,0,0,0,0],"kL","iso1000",true,null,null,1,false,false,0,0,"kiloliters; kilolitres; m3; m^3; meters cubed; metre","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"kilometer","km","KM","length",1000,[1,0,0,0,0,0,0],"km",null,false,"L",null,1,false,false,0,0,"kilometers; kilometres; distance","LOINC","Len","Clinical","",null,null,null,null,false],[false,"kilopascal","kPa","KPAL","pressure",1000000,[-1,-2,1,0,0,0,0],"kPa","si",true,null,null,1,false,false,0,0,"kilopascals; pressure","LOINC","Pres; PPresDiff","Clinical","","N/m2","N/M2","1",1,false],[false,"kilosecond","ks","KS","time",1000,[0,1,0,0,0,0,0],"ks",null,false,"T",null,1,false,false,0,0,"kiloseconds; ksec","LOINC","Time","Clinical","",null,null,null,null,false],[false,"kilo enzyme unit","kU","KU","catalytic activity",10036894500000000000,[0,-1,0,0,0,0,0],"kU","chemical",true,null,null,1,false,false,1,0,"units; mmol/min; millimoles per minute","LOINC","CAct","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"kilo enzyme unit per gram","kU/g","KU/G","catalytic activity",10036894500000000000,[0,-1,-1,0,0,0,0],"kU/g","chemical",true,null,null,1,false,false,1,0,"units per grams; kU per gm","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"kilo enzyme unit per liter","kU/L","KU/L","catalytic activity",1.00368945e+22,[-3,-1,0,0,0,0,0],"kU/L","chemical",true,null,null,1,false,false,1,0,"units per liter; litre; enzymatic activity; enzyme activity per volume; activities","LOINC","ACnc; CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"kilo enzyme unit per milliliter","kU/mL","KU/ML","catalytic activity",1.00368945e+25,[-3,-1,0,0,0,0,0],"kU/mL","chemical",true,null,null,1,false,false,1,0,"kU per mL; units per milliliter; millilitre; enzymatic activity per volume; enzyme activities","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 kU = 1 mmol/min","umol/min","UMOL/MIN","1",1,false],[false,"Liters per 24 hour","L/(24.h)","L/(24.HR)","volume",1.1574074074074074e-8,[3,-1,0,0,0,0,0],"L/h","iso1000",true,null,null,1,false,false,0,0,"L/24hrs; L/24 hrs; L per 24hrs; liters per 24 hours; day; dy; litres; volume flow rate","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per 8 hour","L/(8.h)","L/(8.HR)","volume",3.472222222222222e-8,[3,-1,0,0,0,0,0],"L/h","iso1000",true,null,null,1,false,false,0,0,"L/8hrs; L/8 hrs; L per 8hrs; liters per 8 hours; litres; volume flow rate; shift","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per minute per square meter","L/(min.m2) ","L/(MIN.M2)","volume",0.000016666666666666667,[1,-1,0,0,0,0,0],"L/(min.(m2))","iso1000",true,null,null,1,false,false,0,0,"L/(min.m2); L/min/m^2; L/min/sq. meter; L per min per m2; m^2; liters per minutes per square meter; meter squared; litres; metre ","LOINC","ArVRat","Clinical","unit for tests that measure cardiac output per body surface area (cardiac index)","l",null,"1",1,false],[false,"Liters per day","L/d","L/D","volume",1.1574074074074074e-8,[3,-1,0,0,0,0,0],"L/d","iso1000",true,null,null,1,false,false,0,0,"L/dy; L per day; 24hrs; 24 hrs; 24 hours; liters; litres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per hour","L/h","L/HR","volume",2.7777777777777776e-7,[3,-1,0,0,0,0,0],"L/h","iso1000",true,null,null,1,false,false,0,0,"L/hr; L per hr; litres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per kilogram","L/kg","L/KG","volume",0.000001,[3,0,-1,0,0,0,0],"L/kg","iso1000",true,null,null,1,false,false,0,0,"L per kg; litre","LOINC","VCnt","Clinical","","l",null,"1",1,false],[false,"Liters per liter","L/L","L/L","volume",1,[0,0,0,0,0,0,0],"L/L","iso1000",true,null,null,1,false,false,0,0,"L per L; liter/liter; litre","LOINC","VFr","Clinical","","l",null,"1",1,false],[false,"Liters per minute","L/min","L/MIN","volume",0.000016666666666666667,[3,-1,0,0,0,0,0],"L/min","iso1000",true,null,null,1,false,false,0,0,"liters per minute; litre","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"Liters per minute per square meter","L/min/m2","(L/MIN)/M2","volume",0.000016666666666666667,[1,-1,0,0,0,0,0],"(L/min)/(m2)","iso1000",true,null,null,1,false,false,0,0,"L/(min.m2); L/min/m^2; L/min/sq. meter; L per min per m2; m^2; liters per minutes per square meter; meter squared; litres; metre ","","ArVRat","Clinical","unit for tests that measure cardiac output per body surface area (cardiac index)","l",null,"1",1,false],[false,"Liters per second","L/s","L/S","volume",0.001,[3,-1,0,0,0,0,0],"L/s","iso1000",true,null,null,1,false,false,0,0,"L per sec; litres","LOINC","VRat","Clinical","unit used often to measure gas flow and peak expiratory flow","l",null,"1",1,false],[false,"Liters per second per square second","L/s/s2","(L/S)/S2","volume",0.001,[3,-3,0,0,0,0,0],"(L/s)/(s2)","iso1000",true,null,null,1,false,false,0,0,"L/s/s^2; L/sec/sec2; L/sec/sec^2; L/sec/sq. sec; L per s per s2; L per sec per sec2; s^2; sec^2; liters per seconds per square second; second squared; litres ","LOINC","ArVRat","Clinical","unit for tests that measure cardiac output/body surface area","l",null,"1",1,false],[false,"lumen square meter","lm.m2","LM.M2","luminous flux",1,[2,0,0,2,0,0,1],"lm.(m2)","si",true,null,null,1,false,false,0,0,"lm*m2; lm*m^2; lumen meters squared; lumen sq. meters; metres","LOINC","","Clinical","","cd.sr","CD.SR","1",1,false],[false,"meter per second","m/s","M/S","length",1,[1,-1,0,0,0,0,0],"m/s",null,false,"L",null,1,false,false,0,0,"meter/second; m per sec; meters per second; metres; velocity; speed","LOINC","Vel","Clinical","unit of velocity",null,null,null,null,false],[false,"meter per square second","m/s2","M/S2","length",1,[1,-2,0,0,0,0,0],"m/(s2)",null,false,"L",null,1,false,false,0,0,"m/s^2; m/sq. sec; m per s2; per s^2; meters per square second; second squared; sq second; metres; acceleration","LOINC","Accel","Clinical","unit of acceleration",null,null,null,null,false],[false,"milli international unit per liter","m[IU]/L","M[IU]/L","arbitrary",1,[-3,0,0,0,0,0,0],"(mi.U.)/L","chemical",true,null,null,1,false,true,0,0,"mIU/L; m IU/L; mIU per liter; units; litre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"milli international unit per milliliter","m[IU]/mL","M[IU]/ML","arbitrary",1000.0000000000001,[-3,0,0,0,0,0,0],"(mi.U.)/mL","chemical",true,null,null,1,false,true,0,0,"mIU/mL; m IU/mL; mIU per mL; milli international units per milliliter; millilitre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"square meter","m2","M2","length",1,[2,0,0,0,0,0,0],"m2",null,false,"L",null,1,false,false,0,0,"m^2; sq m; square meters; meters squared; metres","LOINC","Area","Clinical","unit often used to represent body surface area",null,null,null,null,false],[false,"square meter per second","m2/s","M2/S","length",1,[2,-1,0,0,0,0,0],"(m2)/s",null,false,"L",null,1,false,false,0,0,"m^2/sec; m2 per sec; m^2 per sec; sq m/sec; meters squared/seconds; sq m per sec; meters squared; metres","LOINC","ArRat","Clinical","",null,null,null,null,false],[false,"cubic meter per second","m3/s","M3/S","length",1,[3,-1,0,0,0,0,0],"(m3)/s",null,false,"L",null,1,false,false,0,0,"m^3/sec; m3 per sec; m^3 per sec; cu m/sec; cubic meters per seconds; meters cubed; metres","LOINC","VRat","Clinical","",null,null,null,null,false],[false,"milliampere","mA","MA","electric current",0.001,[0,-1,0,0,0,1,0],"mA","si",true,null,null,1,false,false,0,0,"mamp; milliamperes","LOINC","ElpotRat","Clinical","unit of electric current","C/s","C/S","1",1,false],[false,"millibar","mbar","MBAR","pressure",100000,[-1,-2,1,0,0,0,0],"mbar","iso1000",true,null,null,1,false,false,0,0,"millibars","LOINC","Pres","Clinical","unit of pressure","Pa","PAL","1e5",100000,false],[false,"millibar second per liter","mbar.s/L","(MBAR.S)/L","pressure",100000000,[-4,-1,1,0,0,0,0],"(mbar.s)/L","iso1000",true,null,null,1,false,false,0,0,"mbar*s/L; mbar.s per L; mbar*s per L; millibar seconds per liter; millibar second per litre","LOINC","","Clinical","unit to measure expiratory resistance","Pa","PAL","1e5",100000,false],[false,"millibar per liter per second","mbar/L/s","(MBAR/L)/S","pressure",100000000,[-4,-3,1,0,0,0,0],"(mbar/L)/s","iso1000",true,null,null,1,false,false,0,0,"mbar/(L.s); mbar/L/sec; mbar/liter/second; mbar per L per sec; mbar per liter per second; millibars per liters per seconds; litres","LOINC","PresCncRat","Clinical","unit to measure expiratory resistance","Pa","PAL","1e5",100000,false],[false,"milliequivalent","meq","MEQ","amount of substance",602213670000000000000,[0,0,0,0,0,0,0],"meq","chemical",true,null,null,1,false,false,0,1,"milliequivalents; meqs","LOINC","Sub","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per 2 hour","meq/(2.h)","MEQ/(2.HR)","amount of substance",83640787500000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,0,1,"meq/2hrs; meq/2 hrs; meq per 2 hrs; milliequivalents per 2 hours","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per 24 hour","meq/(24.h)","MEQ/(24.HR)","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,0,1,"meq/24hrs; meq/24 hrs; meq per 24 hrs; milliequivalents per 24 hours","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per 8 hour","meq/(8.h)","MEQ/(8.HR)","amount of substance",20910196875000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,0,1,"meq/8hrs; meq/8 hrs; meq per 8 hrs; milliequivalents per 8 hours; shift","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per day","meq/d","MEQ/D","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"meq/d","chemical",true,null,null,1,false,false,0,1,"meq/dy; meq per day; milliquivalents per days; meq/24hrs; meq/24 hrs; meq per 24 hrs; milliequivalents per 24 hours","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per deciliter","meq/dL","MEQ/DL","amount of substance",6.022136699999999e+24,[-3,0,0,0,0,0,0],"meq/dL","chemical",true,null,null,1,false,false,0,1,"meq per dL; milliequivalents per deciliter; decilitre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per gram","meq/g","MEQ/G","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"meq/g","chemical",true,null,null,1,false,false,0,1,"mgq/gm; meq per gm; milliequivalents per gram","LOINC","MCnt","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per hour","meq/h","MEQ/HR","amount of substance",167281575000000000,[0,-1,0,0,0,0,0],"meq/h","chemical",true,null,null,1,false,false,0,1,"meq/hrs; meq per hrs; milliequivalents per hour","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per kilogram","meq/kg","MEQ/KG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"meq/kg","chemical",true,null,null,1,false,false,0,1,"meq per kg; milliequivalents per kilogram","LOINC","SCnt","Clinical","equivalence equals moles per valence; used to measure dose per patient body mass","mol","MOL","1",1,false],[false,"milliequivalent per kilogram per hour","meq/kg/h","(MEQ/KG)/HR","amount of substance",167281575000000,[0,-1,-1,0,0,0,0],"(meq/kg)/h","chemical",true,null,null,1,false,false,0,1,"meq/(kg.h); meq/kg/hr; meq per kg per hr; milliequivalents per kilograms per hour","LOINC","SCntRat","Clinical","equivalence equals moles per valence; unit used to measure dose rate per patient body mass","mol","MOL","1",1,false],[false,"milliequivalent per liter","meq/L","MEQ/L","amount of substance",6.0221367e+23,[-3,0,0,0,0,0,0],"meq/L","chemical",true,null,null,1,false,false,0,1,"milliequivalents per liter; litre; meq per l; acidity","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per square meter","meq/m2","MEQ/M2","amount of substance",602213670000000000000,[-2,0,0,0,0,0,0],"meq/(m2)","chemical",true,null,null,1,false,false,0,1,"meq/m^2; meq/sq. m; milliequivalents per square meter; meter squared; metre","LOINC","ArSub","Clinical","equivalence equals moles per valence; note that the use of m2 in clinical units ofter refers to body surface area","mol","MOL","1",1,false],[false,"milliequivalent per minute","meq/min","MEQ/MIN","amount of substance",10036894500000000000,[0,-1,0,0,0,0,0],"meq/min","chemical",true,null,null,1,false,false,0,1,"meq per min; milliequivalents per minute","LOINC","SRat","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milliequivalent per milliliter","meq/mL","MEQ/ML","amount of substance",6.0221367e+26,[-3,0,0,0,0,0,0],"meq/mL","chemical",true,null,null,1,false,false,0,1,"meq per mL; milliequivalents per milliliter; millilitre","LOINC","SCnc","Clinical","equivalence equals moles per valence","mol","MOL","1",1,false],[false,"milligram","mg","MG","mass",0.001,[0,0,1,0,0,0,0],"mg",null,false,"M",null,1,false,false,0,0,"milligrams","LOINC","Mass","Clinical","",null,null,null,null,false],[false,"milligram per 10 hour","mg/(10.h)","MG/(10.HR)","mass",2.7777777777777777e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/10hrs; mg/10 hrs; mg per 10 hrs; milligrams per 10 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per 12 hour","mg/(12.h)","MG/(12.HR)","mass",2.3148148148148148e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/12hrs; mg/12 hrs; per 12 hrs; 12hrs; milligrams per 12 hours","LOINC","MRat","Clinical","units used for tests in urine",null,null,null,null,false],[false,"milligram per 2 hour","mg/(2.h)","MG/(2.HR)","mass",1.3888888888888888e-7,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/2hrs; mg/2 hrs; mg per 2 hrs; 2hrs; milligrams per 2 hours","LOINC","MRat","Clinical","units used for tests in urine",null,null,null,null,false],[false,"milligram per 24 hour","mg/(24.h)","MG/(24.HR)","mass",1.1574074074074074e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/24hrs; mg/24 hrs; milligrams per 24 hours; mg/kg/dy; mg per kg per day; milligrams per kilograms per days","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per 6 hour","mg/(6.h)","MG/(6.HR)","mass",4.6296296296296295e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/6hrs; mg/6 hrs; mg per 6 hrs; 6hrs; milligrams per 6 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per 72 hour","mg/(72.h)","MG/(72.HR)","mass",3.858024691358025e-9,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/72hrs; mg/72 hrs; 72 hrs; 72hrs; milligrams per 72 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per 8 hour","mg/(8.h)","MG/(8.HR)","mass",3.472222222222222e-8,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/8hrs; mg/8 hrs; milligrams per 8 hours; shift","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per day","mg/d","MG/D","mass",1.1574074074074074e-8,[0,-1,1,0,0,0,0],"mg/d",null,false,"M",null,1,false,false,0,0,"mg/24hrs; mg/24 hrs; milligrams per 24 hours; mg/dy; mg per day; milligrams","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per deciliter","mg/dL","MG/DL","mass",10,[-3,0,1,0,0,0,0],"mg/dL",null,false,"M",null,1,false,false,0,0,"mg per dL; milligrams per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"milligram per gram","mg/g","MG/G","mass",0.001,[0,0,0,0,0,0,0],"mg/g",null,false,"M",null,1,false,false,0,0,"mg per gm; milligrams per gram","LOINC","MCnt; MRto","Clinical","",null,null,null,null,false],[false,"milligram per hour","mg/h","MG/HR","mass",2.7777777777777776e-7,[0,-1,1,0,0,0,0],"mg/h",null,false,"M",null,1,false,false,0,0,"mg/hr; mg per hr; milligrams","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per kilogram","mg/kg","MG/KG","mass",0.000001,[0,0,0,0,0,0,0],"mg/kg",null,false,"M",null,1,false,false,0,0,"mg per kg; milligrams per kilograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"milligram per kilogram per 8 hour","mg/kg/(8.h)","(MG/KG)/(8.HR)","mass",3.472222222222222e-11,[0,-1,0,0,0,0,0],"(mg/kg)/h",null,false,"M",null,1,false,false,0,0,"mg/(8.h.kg); mg/kg/8hrs; mg/kg/8 hrs; mg per kg per 8hrs; 8 hrs; milligrams per kilograms per 8 hours; shift","LOINC","RelMRat; MCntRat","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"milligram per kilogram per day","mg/kg/d","(MG/KG)/D","mass",1.1574074074074074e-11,[0,-1,0,0,0,0,0],"(mg/kg)/d",null,false,"M",null,1,false,false,0,0,"mg/(kg.d); mg/(kg.24.h)mg/kg/dy; mg per kg per day; milligrams per kilograms per days; mg/kg/(24.h); mg/kg/24hrs; 24 hrs; 24 hours","LOINC","RelMRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"milligram per kilogram per hour","mg/kg/h","(MG/KG)/HR","mass",2.7777777777777777e-10,[0,-1,0,0,0,0,0],"(mg/kg)/h",null,false,"M",null,1,false,false,0,0,"mg/(kg.h); mg/kg/hr; mg per kg per hr; milligrams per kilograms per hour","LOINC","RelMRat; MCntRat","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"milligram per kilogram per minute","mg/kg/min","(MG/KG)/MIN","mass",1.6666666666666667e-8,[0,-1,0,0,0,0,0],"(mg/kg)/min",null,false,"M",null,1,false,false,0,0,"mg/(kg.min); mg per kg per min; milligrams per kilograms per minute","LOINC","RelMRat; MCntRat","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"milligram per liter","mg/L","MG/L","mass",1,[-3,0,1,0,0,0,0],"mg/L",null,false,"M",null,1,false,false,0,0,"mg per l; milligrams per liter; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"milligram per square meter","mg/m2","MG/M2","mass",0.001,[-2,0,1,0,0,0,0],"mg/(m2)",null,false,"M",null,1,false,false,0,0,"mg/m^2; mg/sq. m; mg per m2; mg per m^2; mg per sq. milligrams; meter squared; metre","LOINC","ArMass","Clinical","",null,null,null,null,false],[false,"milligram per cubic meter","mg/m3","MG/M3","mass",0.001,[-3,0,1,0,0,0,0],"mg/(m3)",null,false,"M",null,1,false,false,0,0,"mg/m^3; mg/cu. m; mg per m3; milligrams per cubic meter; meter cubed; metre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"milligram per milligram","mg/mg","MG/MG","mass",1,[0,0,0,0,0,0,0],"mg/mg",null,false,"M",null,1,false,false,0,0,"mg per mg; milligrams; milligram/milligram","LOINC","MRto","Clinical","",null,null,null,null,false],[false,"milligram per minute","mg/min","MG/MIN","mass",0.000016666666666666667,[0,-1,1,0,0,0,0],"mg/min",null,false,"M",null,1,false,false,0,0,"mg per min; milligrams per minutes; milligram/minute","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"milligram per milliliter","mg/mL","MG/ML","mass",1000.0000000000001,[-3,0,1,0,0,0,0],"mg/mL",null,false,"M",null,1,false,false,0,0,"mg per mL; milligrams per milliliters; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"milligram per millimole","mg/mmol","MG/MMOL","mass",1.660540186674939e-24,[0,0,1,0,0,0,0],"mg/mmol",null,false,"M",null,1,false,false,-1,0,"mg per mmol; milligrams per millimole; ","LOINC","Ratio","Clinical","",null,null,null,null,false],[false,"milligram per week","mg/wk","MG/WK","mass",1.6534391534391535e-9,[0,-1,1,0,0,0,0],"mg/wk",null,false,"M",null,1,false,false,0,0,"mg/week; mg per wk; milligrams per weeks; milligram/week","LOINC","Mrat","Clinical","",null,null,null,null,false],[false,"milliliter","mL","ML","volume",0.000001,[3,0,0,0,0,0,0],"mL","iso1000",true,null,null,1,false,false,0,0,"milliliters; millilitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"milliliter per 10 hour","mL/(10.h)","ML/(10.HR)","volume",2.7777777777777777e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/10hrs; ml/10 hrs; mL per 10hrs; 10 hrs; milliliters per 10 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 12 hour","mL/(12.h)","ML/(12.HR)","volume",2.3148148148148147e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/12hrs; ml/12 hrs; mL per 12hrs; 12 hrs; milliliters per 12 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 2 hour","mL/(2.h)","ML/(2.HR)","volume",1.3888888888888888e-10,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/2hrs; ml/2 hrs; mL per 2hrs; 2 hrs; milliliters per 2 hours; millilitres ","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 24 hour","mL/(24.h)","ML/(24.HR)","volume",1.1574074074074074e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/24hrs; ml/24 hrs; mL per 24hrs; 24 hrs; milliliters per 24 hours; millilitres; ml/dy; /day; ml per dy; days; fluid outputs; fluid inputs; flow rate","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 4 hour","mL/(4.h)","ML/(4.HR)","volume",6.944444444444444e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/4hrs; ml/4 hrs; mL per 4hrs; 4 hrs; milliliters per 4 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 5 hour","mL/(5.h)","ML/(5.HR)","volume",5.5555555555555553e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/5hrs; ml/5 hrs; mL per 5hrs; 5 hrs; milliliters per 5 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 6 hour","mL/(6.h)","ML/(6.HR)","volume",4.6296296296296294e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/6hrs; ml/6 hrs; mL per 6hrs; 6 hrs; milliliters per 6 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 72 hour","mL/(72.h)","ML/(72.HR)","volume",3.8580246913580245e-12,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/72hrs; ml/72 hrs; mL per 72hrs; 72 hrs; milliliters per 72 hours; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 8 hour","mL/(8.h)","ML/(8.HR)","volume",3.472222222222222e-11,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"ml/8hrs; ml/8 hrs; mL per 8hrs; 8 hrs; milliliters per 8 hours; millilitres; shift","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per 8 hour per kilogram","mL/(8.h)/kg","(ML/(8.HR))/KG","volume",3.472222222222222e-14,[3,-1,-1,0,0,0,0],"(mL/h)/kg","iso1000",true,null,null,1,false,false,0,0,"mL/kg/(8.h); ml/8h/kg; ml/8 h/kg; ml/8hr/kg; ml/8 hr/kgr; mL per 8h per kg; 8 h; 8hr; 8 hr; milliliters per 8 hours per kilogram; millilitres; shift","LOINC","VRatCnt","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per square inch (international)","mL/[sin_i]","ML/[SIN_I]","volume",0.0015500031000061998,[1,0,0,0,0,0,0],"mL","iso1000",true,null,null,1,false,false,0,0,"mL/sin; mL/in2; mL/in^2; mL per sin; in2; in^2; sq. in; milliliters per square inch; inch squared","LOINC","ArVol","Clinical","","l",null,"1",1,false],[false,"milliliter per centimeter of water","mL/cm[H2O]","ML/CM[H2O]","volume",1.0197162129779282e-11,[4,2,-1,0,0,0,0],"mL/(cm HO2)","iso1000",true,null,null,1,false,false,0,0,"milliliters per centimeter of water; millilitre per centimetre of water; millilitres per centimetre of water; mL/cmH2O; mL/cm H2O; mL per cmH2O; mL per cm H2O","LOINC","Compli","Clinical","unit used to measure dynamic lung compliance","l",null,"1",1,false],[false,"milliliter per day","mL/d","ML/D","volume",1.1574074074074074e-11,[3,-1,0,0,0,0,0],"mL/d","iso1000",true,null,null,1,false,false,0,0,"ml/day; ml per day; milliliters per day; 24 hours; 24hrs; millilitre;","LOINC","VRat","Clinical","usually used to measure fluid output or input; flow rate","l",null,"1",1,false],[false,"milliliter per deciliter","mL/dL","ML/DL","volume",0.009999999999999998,[0,0,0,0,0,0,0],"mL/dL","iso1000",true,null,null,1,false,false,0,0,"mL per dL; millilitres; decilitre; milliliters","LOINC","VFr; VFrDiff","Clinical","","l",null,"1",1,false],[false,"milliliter per hour","mL/h","ML/HR","volume",2.7777777777777777e-10,[3,-1,0,0,0,0,0],"mL/h","iso1000",true,null,null,1,false,false,0,0,"mL/hr; mL per hr; milliliters per hour; millilitres; fluid intake; fluid output","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per kilogram","mL/kg","ML/KG","volume",9.999999999999999e-10,[3,0,-1,0,0,0,0],"mL/kg","iso1000",true,null,null,1,false,false,0,0,"mL per kg; milliliters per kilogram; millilitres","LOINC","VCnt","Clinical","","l",null,"1",1,false],[false,"milliliter per kilogram per 8 hour","mL/kg/(8.h)","(ML/KG)/(8.HR)","volume",3.472222222222222e-14,[3,-1,-1,0,0,0,0],"(mL/kg)/h","iso1000",true,null,null,1,false,false,0,0,"mL/(8.h.kg); mL/kg/8hrs; mL/kg/8 hrs; mL per kg per 8hrs; 8 hrs; milliliters per kilograms per 8 hours; millilitres; shift","LOINC","VCntRat; RelEngRat","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per kilogram per day","mL/kg/d","(ML/KG)/D","volume",1.1574074074074072e-14,[3,-1,-1,0,0,0,0],"(mL/kg)/d","iso1000",true,null,null,1,false,false,0,0,"mL/(kg.d); mL/kg/dy; mL per kg per day; milliliters per kilograms per day; mg/kg/24hrs; 24 hrs; per 24 hours millilitres","LOINC","VCntRat; RelEngRat","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per kilogram per hour","mL/kg/h","(ML/KG)/HR","volume",2.7777777777777774e-13,[3,-1,-1,0,0,0,0],"(mL/kg)/h","iso1000",true,null,null,1,false,false,0,0,"mL/(kg.h); mL/kg/hr; mL per kg per hr; milliliters per kilograms per hour; millilitres","LOINC","VCntRat; RelEngRat","Clinical","unit used to measure renal excretion volume rate per body mass","l",null,"1",1,false],[false,"milliliter per kilogram per minute","mL/kg/min","(ML/KG)/MIN","volume",1.6666666666666664e-11,[3,-1,-1,0,0,0,0],"(mL/kg)/min","iso1000",true,null,null,1,false,false,0,0,"mL/(kg.min); mL/kg/dy; mL per kg per day; milliliters per kilograms per day; millilitres","LOINC","RelEngRat","Clinical","used for tests that measure activity metabolic rate compared to standard resting metabolic rate ","l",null,"1",1,false],[false,"milliliter per square meter","mL/m2","ML/M2","volume",0.000001,[1,0,0,0,0,0,0],"mL/(m2)","iso1000",true,null,null,1,false,false,0,0,"mL/m^2; mL/sq. meter; mL per m2; m^2; sq. meter; milliliters per square meter; millilitres; meter squared","LOINC","ArVol","Clinical","used for tests that relate to heart work - e.g. ventricular stroke volume; atrial volume per body surface area","l",null,"1",1,false],[false,"milliliter per millibar","mL/mbar","ML/MBAR","volume",1e-11,[4,2,-1,0,0,0,0],"mL/mbar","iso1000",true,null,null,1,false,false,0,0,"mL per mbar; milliliters per millibar; millilitres","LOINC","","Clinical","unit used to measure dynamic lung compliance","l",null,"1",1,false],[false,"milliliter per minute","mL/min","ML/MIN","volume",1.6666666666666667e-8,[3,-1,0,0,0,0,0],"mL/min","iso1000",true,null,null,1,false,false,0,0,"mL per min; milliliters; millilitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"milliliter per minute per square meter","mL/min/m2","(ML/MIN)/M2","volume",1.6666666666666667e-8,[1,-1,0,0,0,0,0],"(mL/min)/(m2)","iso1000",true,null,null,1,false,false,0,0,"ml/min/m^2; ml/min/sq. meter; mL per min per m2; m^2; sq. meter; milliliters per minutes per square meter; millilitres; metre; meter squared","LOINC","ArVRat","Clinical","unit used to measure volume per body surface area; oxygen consumption index","l",null,"1",1,false],[false,"milliliter per millimeter","mL/mm","ML/MM","volume",0.001,[2,0,0,0,0,0,0],"mL/mm","iso1000",true,null,null,1,false,false,0,0,"mL per mm; milliliters per millimeter; millilitres; millimetre","LOINC","Lineic Volume","Clinical","","l",null,"1",1,false],[false,"milliliter per second","mL/s","ML/S","volume",0.000001,[3,-1,0,0,0,0,0],"mL/s","iso1000",true,null,null,1,false,false,0,0,"ml/sec; mL per sec; milliliters per second; millilitres","LOINC","Vel; VelRat; VRat","Clinical","","l",null,"1",1,false],[false,"millimeter","mm","MM","length",0.001,[1,0,0,0,0,0,0],"mm",null,false,"L",null,1,false,false,0,0,"millimeters; millimetres; height; length; diameter; thickness; axis; curvature; size","LOINC","Len","Clinical","",null,null,null,null,false],[false,"millimeter per hour","mm/h","MM/HR","length",2.7777777777777776e-7,[1,-1,0,0,0,0,0],"mm/h",null,false,"L",null,1,false,false,0,0,"mm/hr; mm per hr; millimeters per hour; millimetres","LOINC","Vel","Clinical","unit to measure sedimentation rate",null,null,null,null,false],[false,"millimeter per minute","mm/min","MM/MIN","length",0.000016666666666666667,[1,-1,0,0,0,0,0],"mm/min",null,false,"L",null,1,false,false,0,0,"mm per min; millimeters per minute; millimetres","LOINC","Vel","Clinical","",null,null,null,null,false],[false,"millimeter of water","mm[H2O]","MM[H2O]","pressure",9806.65,[-1,-2,1,0,0,0,0],"mm HO2","clinical",true,null,null,1,false,false,0,0,"mmH2O; mm H2O; millimeters of water; millimetres","LOINC","Pres","Clinical","","kPa","KPAL","980665e-5",9.80665,false],[false,"millimeter of mercury","mm[Hg]","MM[HG]","pressure",133322,[-1,-2,1,0,0,0,0],"mm Hg","clinical",true,null,null,1,false,false,0,0,"mmHg; mm Hg; millimeters of mercury; millimetres","LOINC","Pres; PPres; Ratio","Clinical","1 mm[Hg] = 1 torr; unit to measure blood pressure","kPa","KPAL","133.3220",133.322,false],[false,"square millimeter","mm2","MM2","length",0.000001,[2,0,0,0,0,0,0],"mm2",null,false,"L",null,1,false,false,0,0,"mm^2; sq. mm.; sq. millimeters; millimeters squared; millimetres","LOINC","Area","Clinical","",null,null,null,null,false],[false,"millimole","mmol","MMOL","amount of substance",602213670000000000000,[0,0,0,0,0,0,0],"mmol","si",true,null,null,1,false,false,1,0,"millimoles","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 12 hour","mmol/(12.h)","MMOL/(12.HR)","amount of substance",13940131250000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/12hrs; mmol/12 hrs; mmol per 12 hrs; 12hrs; millimoles per 12 hours","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 2 hour","mmol/(2.h)","MMOL/(2.HR)","amount of substance",83640787500000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/2hrs; mmol/2 hrs; mmol per 2 hrs; 2hrs; millimoles per 2 hours","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 24 hour","mmol/(24.h)","MMOL/(24.HR)","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/24hrs; mmol/24 hrs; mmol per 24 hrs; 24hrs; millimoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 5 hour","mmol/(5.h)","MMOL/(5.HR)","amount of substance",33456315000000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/5hrs; mmol/5 hrs; mmol per 5 hrs; 5hrs; millimoles per 5 hours","LOINC","SRat","Clinical","unit for tests related to doses","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 6 hour","mmol/(6.h)","MMOL/(6.HR)","amount of substance",27880262500000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/6hrs; mmol/6 hrs; mmol per 6 hrs; 6hrs; millimoles per 6 hours","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per 8 hour","mmol/(8.h)","MMOL/(8.HR)","amount of substance",20910196875000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/8hrs; mmol/8 hrs; mmol per 8 hrs; 8hrs; millimoles per 8 hours; shift","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per day","mmol/d","MMOL/D","amount of substance",6970065625000000,[0,-1,0,0,0,0,0],"mmol/d","si",true,null,null,1,false,false,1,0,"mmol/24hrs; mmol/24 hrs; mmol per 24 hrs; 24hrs; millimoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per deciliter","mmol/dL","MMOL/DL","amount of substance",6.022136699999999e+24,[-3,0,0,0,0,0,0],"mmol/dL","si",true,null,null,1,false,false,1,0,"mmol per dL; millimoles; decilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per gram","mmol/g","MMOL/G","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"mmol/g","si",true,null,null,1,false,false,1,0,"mmol per gram; millimoles","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per hour","mmol/h","MMOL/HR","amount of substance",167281575000000000,[0,-1,0,0,0,0,0],"mmol/h","si",true,null,null,1,false,false,1,0,"mmol/hr; mmol per hr; millimoles per hour","LOINC","SRat","Clinical","unit for tests related to urine","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram","mmol/kg","MMOL/KG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"mmol/kg","si",true,null,null,1,false,false,1,0,"mmol per kg; millimoles per kilogram","LOINC","SCnt","Clinical","unit for tests related to stool","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per 8 hour","mmol/kg/(8.h)","(MMOL/KG)/(8.HR)","amount of substance",20910196875000,[0,-1,-1,0,0,0,0],"(mmol/kg)/h","si",true,null,null,1,false,false,1,0,"mmol/(8.h.kg); mmol/kg/8hrs; mmol/kg/8 hrs; mmol per kg per 8hrs; 8 hrs; millimoles per kilograms per 8 hours; shift","LOINC","CCnt","Clinical","unit used to measure molar dose rate per patient body mass","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per day","mmol/kg/d","(MMOL/KG)/D","amount of substance",6970065625000,[0,-1,-1,0,0,0,0],"(mmol/kg)/d","si",true,null,null,1,false,false,1,0,"mmol/kg/dy; mmol/kg/day; mmol per kg per dy; millimoles per kilograms per day","LOINC","RelSRat","Clinical","unit used to measure molar dose rate per patient body mass","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per hour","mmol/kg/h","(MMOL/KG)/HR","amount of substance",167281575000000,[0,-1,-1,0,0,0,0],"(mmol/kg)/h","si",true,null,null,1,false,false,1,0,"mmol/kg/hr; mmol per kg per hr; millimoles per kilograms per hour","LOINC","CCnt","Clinical","unit used to measure molar dose rate per patient body mass","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per kilogram per minute","mmol/kg/min","(MMOL/KG)/MIN","amount of substance",10036894500000000,[0,-1,-1,0,0,0,0],"(mmol/kg)/min","si",true,null,null,1,false,false,1,0,"mmol/(kg.min); mmol/kg/min; mmol per kg per min; millimoles per kilograms per minute","LOINC","CCnt","Clinical","unit used to measure molar dose rate per patient body mass; note that the unit for the enzyme unit U = umol/min. mmol/kg/min = kU/kg; ","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per liter","mmol/L","MMOL/L","amount of substance",6.0221367e+23,[-3,0,0,0,0,0,0],"mmol/L","si",true,null,null,1,false,false,1,0,"mmol per L; millimoles per liter; litre","LOINC","SCnc","Clinical","unit for tests related to doses","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per square meter","mmol/m2","MMOL/M2","amount of substance",602213670000000000000,[-2,0,0,0,0,0,0],"mmol/(m2)","si",true,null,null,1,false,false,1,0,"mmol/m^2; mmol/sq. meter; mmol per m2; m^2; sq. meter; millimoles; meter squared; metre","LOINC","ArSub","Clinical","unit used to measure molar dose per patient body surface area","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per minute","mmol/min","MMOL/MIN","amount of substance",10036894500000000000,[0,-1,0,0,0,0,0],"mmol/min","si",true,null,null,1,false,false,1,0,"mmol per min; millimoles per minute","LOINC","Srat; CAct","Clinical","unit for the enzyme unit U = umol/min. mmol/min = kU","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per millimole","mmol/mmol","MMOL/MMOL","amount of substance",1,[0,0,0,0,0,0,0],"mmol/mmol","si",true,null,null,1,false,false,0,0,"mmol per mmol; millimoles per millimole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per mole","mmol/mol","MMOL/MOL","amount of substance",0.001,[0,0,0,0,0,0,0],"mmol/mol","si",true,null,null,1,false,false,0,0,"mmol per mol; millimoles per mole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"millimole per second per liter","mmol/s/L","(MMOL/S)/L","amount of substance",6.0221367e+23,[-3,-1,0,0,0,0,0],"(mmol/s)/L","si",true,null,null,1,false,false,1,0,"mmol/sec/L; mmol per s per L; per sec; millimoles per seconds per liter; litre","LOINC","CCnc ","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per kilogram","mol/kg","MOL/KG","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"mol/kg","si",true,null,null,1,false,false,1,0,"mol per kg; moles; mols","LOINC","SCnt","Clinical","unit for tests related to stool","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per kilogram per second","mol/kg/s","(MOL/KG)/S","amount of substance",602213670000000000000,[0,-1,-1,0,0,0,0],"(mol/kg)/s","si",true,null,null,1,false,false,1,0,"mol/kg/sec; mol per kg per sec; moles per kilograms per second; mols","LOINC","CCnt","Clinical","unit of catalytic activity (mol/s) per mass (kg)","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per liter","mol/L","MOL/L","amount of substance",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"mol/L","si",true,null,null,1,false,false,1,0,"mol per L; moles per liter; litre; moles; mols","LOINC","SCnc","Clinical","unit often used in tests measuring oxygen content","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per cubic meter","mol/m3","MOL/M3","amount of substance",6.0221367e+23,[-3,0,0,0,0,0,0],"mol/(m3)","si",true,null,null,1,false,false,1,0,"mol/m^3; mol/cu. m; mol per m3; m^3; cu. meter; mols; moles; meters cubed; metre; mole per kiloliter; kilolitre; mol/kL","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per milliliter","mol/mL","MOL/ML","amount of substance",6.0221367e+29,[-3,0,0,0,0,0,0],"mol/mL","si",true,null,null,1,false,false,1,0,"mol per mL; moles; millilitre; mols","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per mole","mol/mol","MOL/MOL","amount of substance",1,[0,0,0,0,0,0,0],"mol/mol","si",true,null,null,1,false,false,0,0,"mol per mol; moles per mol; mols","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"mole per second","mol/s","MOL/S","amount of substance",6.0221367e+23,[0,-1,0,0,0,0,0],"mol/s","si",true,null,null,1,false,false,1,0,"mol per sec; moles per second; mols","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"milliosmole","mosm","MOSM","amount of substance (dissolved particles)",602213670000000000000,[0,0,0,0,0,0,0],"mosm","chemical",true,null,null,1,false,false,1,0,"milliosmoles","LOINC","Osmol","Clinical","equal to 1/1000 of an osmole","mol","MOL","1",1,false],[false,"milliosmole per kilogram","mosm/kg","MOSM/KG","amount of substance (dissolved particles)",602213670000000000,[0,0,-1,0,0,0,0],"mosm/kg","chemical",true,null,null,1,false,false,1,0,"mosm per kg; milliosmoles per kilogram","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"milliosmole per liter","mosm/L","MOSM/L","amount of substance (dissolved particles)",6.0221367e+23,[-3,0,0,0,0,0,0],"mosm/L","chemical",true,null,null,1,false,false,1,0,"mosm per liter; litre; milliosmoles","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"millipascal","mPa","MPAL","pressure",1,[-1,-2,1,0,0,0,0],"mPa","si",true,null,null,1,false,false,0,0,"millipascals","LOINC","Pres","Clinical","unit of pressure","N/m2","N/M2","1",1,false],[false,"millipascal second","mPa.s","MPAL.S","pressure",1,[-1,-1,1,0,0,0,0],"mPa.s","si",true,null,null,1,false,false,0,0,"mPa*s; millipoise; mP; dynamic viscosity","LOINC","Visc","Clinical","base units for millipoise, a measurement of dynamic viscosity","N/m2","N/M2","1",1,false],[false,"megasecond","Ms","MAS","time",1000000,[0,1,0,0,0,0,0],"Ms",null,false,"T",null,1,false,false,0,0,"megaseconds","LOINC","Time","Clinical","",null,null,null,null,false],[false,"millisecond","ms","MS","time",0.001,[0,1,0,0,0,0,0],"ms",null,false,"T",null,1,false,false,0,0,"milliseconds; duration","LOINC","Time","Clinical","",null,null,null,null,false],[false,"milli enzyme unit per gram","mU/g","MU/G","catalytic activity",10036894500000,[0,-1,-1,0,0,0,0],"mU/g","chemical",true,null,null,1,false,false,1,0,"mU per gm; milli enzyme units per gram; enzyme activity; enzymatic activity per mass","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per liter","mU/L","MU/L","catalytic activity",10036894500000000,[-3,-1,0,0,0,0,0],"mU/L","chemical",true,null,null,1,false,false,1,0,"mU per liter; litre; milli enzyme units enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per milligram","mU/mg","MU/MG","catalytic activity",10036894500000000,[0,-1,-1,0,0,0,0],"mU/mg","chemical",true,null,null,1,false,false,1,0,"mU per mg; milli enzyme units per milligram","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per milliliter","mU/mL","MU/ML","catalytic activity",10036894500000000000,[-3,-1,0,0,0,0,0],"mU/mL","chemical",true,null,null,1,false,false,1,0,"mU per mL; milli enzyme units per milliliter; millilitre; enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"milli enzyme unit per milliliter per minute","mU/mL/min","(MU/ML)/MIN","catalytic activity",167281575000000000,[-3,-2,0,0,0,0,0],"(mU/mL)/min","chemical",true,null,null,1,false,false,1,0,"mU per mL per min; mU per milliliters per minute; millilitres; milli enzyme units; enzymatic activity; enzyme activity","LOINC","CCncRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 mU = 1 nmol/min","umol/min","UMOL/MIN","1",1,false],[false,"millivolt","mV","MV","electric potential",1,[2,-2,1,0,0,-1,0],"mV","si",true,null,null,1,false,false,0,0,"millivolts","LOINC","Elpot","Clinical","unit of electric potential (voltage)","J/C","J/C","1",1,false],[false,"Newton centimeter","N.cm","N.CM","force",10,[2,-2,1,0,0,0,0],"N.cm","si",true,null,null,1,false,false,0,0,"N*cm; Ncm; N cm; Newton*centimeters; Newton* centimetres; torque; work","LOINC","","Clinical","as a measurement of work, N.cm = 1/100 Joules;\nnote that N.m is the standard unit of measurement for torque (although dimensionally equivalent to Joule), and N.cm can also be thought of as a torqe unit","kg.m/s2","KG.M/S2","1",1,false],[false,"Newton second","N.s","N.S","force",1000,[1,-1,1,0,0,0,0],"N.s","si",true,null,null,1,false,false,0,0,"Newton*seconds; N*s; N s; Ns; impulse; imp","LOINC","","Clinical","standard unit of impulse","kg.m/s2","KG.M/S2","1",1,false],[false,"nanogram","ng","NG","mass",1e-9,[0,0,1,0,0,0,0],"ng",null,false,"M",null,1,false,false,0,0,"nanograms","LOINC","Mass","Clinical","",null,null,null,null,false],[false,"nanogram per 24 hour","ng/(24.h)","NG/(24.HR)","mass",1.1574074074074075e-14,[0,-1,1,0,0,0,0],"ng/h",null,false,"M",null,1,false,false,0,0,"ng/24hrs; ng/24 hrs; nanograms per 24 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"nanogram per 8 hour","ng/(8.h)","NG/(8.HR)","mass",3.4722222222222224e-14,[0,-1,1,0,0,0,0],"ng/h",null,false,"M",null,1,false,false,0,0,"ng/8hrs; ng/8 hrs; nanograms per 8 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"nanogram per million","ng/10*6","NG/(10*6)","mass",1e-15,[0,0,1,0,0,0,0],"ng/(106)",null,false,"M",null,1,false,false,0,0,"ng/10^6; ng per 10*6; 10^6; nanograms","LOINC","MNum","Clinical","",null,null,null,null,false],[false,"nanogram per day","ng/d","NG/D","mass",1.1574074074074075e-14,[0,-1,1,0,0,0,0],"ng/d",null,false,"M",null,1,false,false,0,0,"ng/dy; ng per day; nanograms ","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"nanogram per deciliter","ng/dL","NG/DL","mass",0.00001,[-3,0,1,0,0,0,0],"ng/dL",null,false,"M",null,1,false,false,0,0,"ng per dL; nanograms per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"nanogram per gram","ng/g","NG/G","mass",1e-9,[0,0,0,0,0,0,0],"ng/g",null,false,"M",null,1,false,false,0,0,"ng/gm; ng per gm; nanograms per gram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"nanogram per hour","ng/h","NG/HR","mass",2.777777777777778e-13,[0,-1,1,0,0,0,0],"ng/h",null,false,"M",null,1,false,false,0,0,"ng/hr; ng per hr; nanograms per hour","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"nanogram per kilogram","ng/kg","NG/KG","mass",1e-12,[0,0,0,0,0,0,0],"ng/kg",null,false,"M",null,1,false,false,0,0,"ng per kg; nanograms per kilogram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"nanogram per kilogram per 8 hour","ng/kg/(8.h)","(NG/KG)/(8.HR)","mass",3.472222222222222e-17,[0,-1,0,0,0,0,0],"(ng/kg)/h",null,false,"M",null,1,false,false,0,0,"ng/(8.h.kg); ng/kg/8hrs; ng/kg/8 hrs; ng per kg per 8hrs; 8 hrs; nanograms per kilograms per 8 hours; shift","LOINC","MRtoRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"nanogram per kilogram per hour","ng/kg/h","(NG/KG)/HR","mass",2.7777777777777775e-16,[0,-1,0,0,0,0,0],"(ng/kg)/h",null,false,"M",null,1,false,false,0,0,"ng/(kg.h); ng/kg/hr; ng per kg per hr; nanograms per kilograms per hour","LOINC","MRtoRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"nanogram per kilogram per minute","ng/kg/min","(NG/KG)/MIN","mass",1.6666666666666667e-14,[0,-1,0,0,0,0,0],"(ng/kg)/min",null,false,"M",null,1,false,false,0,0,"ng/(kg.min); ng per kg per min; nanograms per kilograms per minute","LOINC","MRtoRat ","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"nanogram per liter","ng/L","NG/L","mass",0.000001,[-3,0,1,0,0,0,0],"ng/L",null,false,"M",null,1,false,false,0,0,"ng per L; nanograms per liter; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"nanogram per square meter","ng/m2","NG/M2","mass",1e-9,[-2,0,1,0,0,0,0],"ng/(m2)",null,false,"M",null,1,false,false,0,0,"ng/m^2; ng/sq. m; ng per m2; m^2; sq. meter; nanograms; meter squared; metre","LOINC","ArMass","Clinical","unit used to measure mass dose per patient body surface area",null,null,null,null,false],[false,"nanogram per milligram","ng/mg","NG/MG","mass",0.000001,[0,0,0,0,0,0,0],"ng/mg",null,false,"M",null,1,false,false,0,0,"ng per mg; nanograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"nanogram per milligram per hour","ng/mg/h","(NG/MG)/HR","mass",2.7777777777777777e-10,[0,-1,0,0,0,0,0],"(ng/mg)/h",null,false,"M",null,1,false,false,0,0,"ng/mg/hr; ng per mg per hr; nanograms per milligrams per hour","LOINC","MRtoRat ","Clinical","",null,null,null,null,false],[false,"nanogram per minute","ng/min","NG/MIN","mass",1.6666666666666667e-11,[0,-1,1,0,0,0,0],"ng/min",null,false,"M",null,1,false,false,0,0,"ng per min; nanograms","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"nanogram per millliiter","ng/mL","NG/ML","mass",0.001,[-3,0,1,0,0,0,0],"ng/mL",null,false,"M",null,1,false,false,0,0,"ng per mL; nanograms; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"nanogram per milliliter per hour","ng/mL/h","(NG/ML)/HR","mass",2.7777777777777776e-7,[-3,-1,1,0,0,0,0],"(ng/mL)/h",null,false,"M",null,1,false,false,0,0,"ng/mL/hr; ng per mL per mL; nanograms per milliliter per hour; nanogram per millilitre per hour; nanograms per millilitre per hour; enzymatic activity per volume; enzyme activity per milliliters","LOINC","CCnc","Clinical","tests that measure enzymatic activity",null,null,null,null,false],[false,"nanogram per second","ng/s","NG/S","mass",1e-9,[0,-1,1,0,0,0,0],"ng/s",null,false,"M",null,1,false,false,0,0,"ng/sec; ng per sec; nanograms per second","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"nanogram per enzyme unit","ng/U","NG/U","mass",9.963241120049634e-26,[0,1,1,0,0,0,0],"ng/U",null,false,"M",null,1,false,false,-1,0,"ng per U; nanograms per enzyme unit","LOINC","CMass","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)",null,null,null,null,false],[false,"nanokatal","nkat","NKAT","catalytic activity",602213670000000,[0,-1,0,0,0,0,0],"nkat","chemical",true,null,null,1,false,false,1,0,"nanokatals","LOINC","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"nanoliter","nL","NL","volume",1.0000000000000002e-12,[3,0,0,0,0,0,0],"nL","iso1000",true,null,null,1,false,false,0,0,"nanoliters; nanolitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"nanometer","nm","NM","length",1e-9,[1,0,0,0,0,0,0],"nm",null,false,"L",null,1,false,false,0,0,"nanometers; nanometres","LOINC","Len","Clinical","",null,null,null,null,false],[false,"nanometer per second per liter","nm/s/L","(NM/S)/L","length",0.000001,[-2,-1,0,0,0,0,0],"(nm/s)/L",null,false,"L",null,1,false,false,0,0,"nm/sec/liter; nm/sec/litre; nm per s per l; nm per sec per l; nanometers per second per liter; nanometre per second per litre; nanometres per second per litre","LOINC","VelCnc","Clinical","",null,null,null,null,false],[false,"nanomole","nmol","NMOL","amount of substance",602213670000000,[0,0,0,0,0,0,0],"nmol","si",true,null,null,1,false,false,1,0,"nanomoles","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per 24 hour","nmol/(24.h)","NMOL/(24.HR)","amount of substance",6970065625,[0,-1,0,0,0,0,0],"nmol/h","si",true,null,null,1,false,false,1,0,"nmol/24hr; nmol/24 hr; nanomoles per 24 hours; nmol/day; nanomoles per day; nmol per day; nanomole/day; nanomol/day","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per day","nmol/d","NMOL/D","amount of substance",6970065625,[0,-1,0,0,0,0,0],"nmol/d","si",true,null,null,1,false,false,1,0,"nmol/day; nanomoles per day; nmol per day; nanomole/day; nanomol/day; nmol/24hr; nmol/24 hr; nanomoles per 24 hours; ","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per deciliter","nmol/dL","NMOL/DL","amount of substance",6022136700000000000,[-3,0,0,0,0,0,0],"nmol/dL","si",true,null,null,1,false,false,1,0,"nmol per dL; nanomoles per deciliter; nanomole per decilitre; nanomoles per decilitre; nanomole/deciliter; nanomole/decilitre; nanomol/deciliter; nanomol/decilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per gram","nmol/g","NMOL/G","amount of substance",602213670000000,[0,0,-1,0,0,0,0],"nmol/g","si",true,null,null,1,false,false,1,0,"nmol per gram; nanomoles per gram; nanomole/gram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per hour per liter","nmol/h/L","(NMOL/HR)/L","amount of substance",167281575000000,[-3,-1,0,0,0,0,0],"(nmol/h)/L","si",true,null,null,1,false,false,1,0,"nmol/hrs/L; nmol per hrs per L; nanomoles per hours per liter; litre; enzymatic activity per volume; enzyme activities","LOINC","CCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per liter","nmol/L","NMOL/L","amount of substance",602213670000000000,[-3,0,0,0,0,0,0],"nmol/L","si",true,null,null,1,false,false,1,0,"nmol per L; nanomoles per liter; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milligram","nmol/mg","NMOL/MG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"nmol/mg","si",true,null,null,1,false,false,1,0,"nmol per mg; nanomoles per milligram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milligram per hour","nmol/mg/h","(NMOL/MG)/HR","amount of substance",167281575000000,[0,-1,-1,0,0,0,0],"(nmol/mg)/h","si",true,null,null,1,false,false,1,0,"nmol/mg/hr; nmol per mg per hr; nanomoles per milligrams per hour","LOINC","SCntRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milligram of protein","nmol/mg{prot}","NMOL/MG","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"nmol/mg","si",true,null,null,1,false,false,1,0,"nanomoles; nmol/mg prot; nmol per mg prot","LOINC","Ratio; CCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per minute","nmol/min","NMOL/MIN","amount of substance",10036894500000,[0,-1,0,0,0,0,0],"nmol/min","si",true,null,null,1,false,false,1,0,"nmol per min; nanomoles per minute; milli enzyme units; enzyme activity per volume; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. nmol/min = mU (milli enzyme unit)","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per minute per milliliter","nmol/min/mL","(NMOL/MIN)/ML","amount of substance",10036894500000000000,[-3,-1,0,0,0,0,0],"(nmol/min)/mL","si",true,null,null,1,false,false,1,0,"nmol per min per mL; nanomoles per minutes per milliliter; millilitre; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. nmol/mL/min = mU/mL","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milliliter","nmol/mL","NMOL/ML","amount of substance",602213670000000000000,[-3,0,0,0,0,0,0],"nmol/mL","si",true,null,null,1,false,false,1,0,"nmol per mL; nanomoles per milliliter; millilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milliliter per hour","nmol/mL/h","(NMOL/ML)/HR","amount of substance",167281575000000000,[-3,-1,0,0,0,0,0],"(nmol/mL)/h","si",true,null,null,1,false,false,1,0,"nmol/mL/hr; nmol per mL per hr; nanomoles per milliliters per hour; millilitres; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min.","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per milliliter per minute","nmol/mL/min","(NMOL/ML)/MIN","amount of substance",10036894500000000000,[-3,-1,0,0,0,0,0],"(nmol/mL)/min","si",true,null,null,1,false,false,1,0,"nmol per mL per min; nanomoles per milliliters per min; millilitres; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. nmol/mL/min = mU/mL","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per millimole","nmol/mmol","NMOL/MMOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"nmol/mmol","si",true,null,null,1,false,false,0,0,"nmol per mmol; nanomoles per millimole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per millimole of creatinine","nmol/mmol{creat}","NMOL/MMOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"nmol/mmol","si",true,null,null,1,false,false,0,0,"nanomoles","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per mole","nmol/mol","NMOL/MOL","amount of substance",1e-9,[0,0,0,0,0,0,0],"nmol/mol","si",true,null,null,1,false,false,0,0,"nmol per mole; nanomoles","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per nanomole","nmol/nmol","NMOL/NMOL","amount of substance",1,[0,0,0,0,0,0,0],"nmol/nmol","si",true,null,null,1,false,false,0,0,"nmol per nmol; nanomoles","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per second","nmol/s","NMOL/S","amount of substance",602213670000000,[0,-1,0,0,0,0,0],"nmol/s","si",true,null,null,1,false,false,1,0,"nmol/sec; nmol per sec; nanomoles per sercond; milli enzyme units; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min.","10*23","10*23","6.0221367",6.0221367,false],[false,"nanomole per second per liter","nmol/s/L","(NMOL/S)/L","amount of substance",602213670000000000,[-3,-1,0,0,0,0,0],"(nmol/s)/L","si",true,null,null,1,false,false,1,0,"nmol/sec/L; nmol per s per L; nmol per sec per L; nanomoles per seconds per liter; litre; milli enzyme units per volume; enzyme activity; enzymatic activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min.","10*23","10*23","6.0221367",6.0221367,false],[false,"nanosecond","ns","NS","time",1e-9,[0,1,0,0,0,0,0],"ns",null,false,"T",null,1,false,false,0,0,"nanoseconds","LOINC","Time","Clinical","",null,null,null,null,false],[false,"nanoenzyme unit per milliliter","nU/mL","NU/ML","catalytic activity",10036894500000,[-3,-1,0,0,0,0,0],"nU/mL","chemical",true,null,null,1,false,false,1,0,"nU per mL; nanoenzyme units per milliliter; millilitre; enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 fU = pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"Ohm meter","Ohm.m","OHM.M","electric resistance",1000,[3,-1,1,0,0,-2,0],"Ω.m","si",true,null,null,1,false,false,0,0,"electric resistivity; meters; metres","LOINC","","Clinical","unit of electric resistivity","V/A","V/A","1",1,false],[false,"osmole per kilogram","osm/kg","OSM/KG","amount of substance (dissolved particles)",602213670000000000000,[0,0,-1,0,0,0,0],"osm/kg","chemical",true,null,null,1,false,false,1,0,"osm per kg; osmoles per kilogram; osmols","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"osmole per liter","osm/L","OSM/L","amount of substance (dissolved particles)",6.0221366999999994e+26,[-3,0,0,0,0,0,0],"osm/L","chemical",true,null,null,1,false,false,1,0,"osm per L; osmoles per liter; litre; osmols","LOINC","Osmol","Clinical","","mol","MOL","1",1,false],[false,"picoampere","pA","PA","electric current",1e-12,[0,-1,0,0,0,1,0],"pA","si",true,null,null,1,false,false,0,0,"picoamperes","LOINC","","Clinical","equal to 10^-12 amperes","C/s","C/S","1",1,false],[false,"picogram","pg","PG","mass",1e-12,[0,0,1,0,0,0,0],"pg",null,false,"M",null,1,false,false,0,0,"picograms","LOINC","Mass; EntMass","Clinical","",null,null,null,null,false],[false,"picogram per deciliter","pg/dL","PG/DL","mass",9.999999999999999e-9,[-3,0,1,0,0,0,0],"pg/dL",null,false,"M",null,1,false,false,0,0,"pg per dL; picograms; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"picogram per liter","pg/L","PG/L","mass",1e-9,[-3,0,1,0,0,0,0],"pg/L",null,false,"M",null,1,false,false,0,0,"pg per L; picograms; litre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"picogram per milligram","pg/mg","PG/MG","mass",1e-9,[0,0,0,0,0,0,0],"pg/mg",null,false,"M",null,1,false,false,0,0,"pg per mg; picograms","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"picogram per milliliter","pg/mL","PG/ML","mass",0.000001,[-3,0,1,0,0,0,0],"pg/mL",null,false,"M",null,1,false,false,0,0,"pg per mL; picograms per milliliter; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"picogram per millimeter","pg/mm","PG/MM","mass",1e-9,[-1,0,1,0,0,0,0],"pg/mm",null,false,"M",null,1,false,false,0,0,"pg per mm; picogram/millimeter; picogram/millimetre; picograms per millimeter; millimetre","LOINC","Lineic Mass","Clinical","",null,null,null,null,false],[false,"picokatal","pkat","PKAT","catalytic activity",602213670000,[0,-1,0,0,0,0,0],"pkat","chemical",true,null,null,1,false,false,1,0,"pkats; picokatals","LOINC","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"picoliter","pL","PL","volume",1e-15,[3,0,0,0,0,0,0],"pL","iso1000",true,null,null,1,false,false,0,0,"picoliters; picolitres","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"picometer","pm","PM","length",1e-12,[1,0,0,0,0,0,0],"pm",null,false,"L",null,1,false,false,0,0,"picometers; picometres","LOINC","Len","Clinical","",null,null,null,null,false],[false,"picomole","pmol","PMOL","amount of substance",602213670000,[0,0,0,0,0,0,0],"pmol","si",true,null,null,1,false,false,1,0,"picomoles; pmols","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per 24 hour","pmol/(24.h)","PMOL/(24.HR)","amount of substance",6970065.625,[0,-1,0,0,0,0,0],"pmol/h","si",true,null,null,1,false,false,1,0,"pmol/24hrs; pmol/24 hrs; pmol per 24 hrs; 24hrs; days; dy; picomoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per day","pmol/d","PMOL/D","amount of substance",6970065.625,[0,-1,0,0,0,0,0],"pmol/d","si",true,null,null,1,false,false,1,0,"pmol/dy; pmol per day; 24 hours; 24hrs; 24 hrs; picomoles","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per deciliter","pmol/dL","PMOL/DL","amount of substance",6022136700000000,[-3,0,0,0,0,0,0],"pmol/dL","si",true,null,null,1,false,false,1,0,"pmol per dL; picomoles per deciliter; decilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per gram","pmol/g","PMOL/G","amount of substance",602213670000,[0,0,-1,0,0,0,0],"pmol/g","si",true,null,null,1,false,false,1,0,"pmol per gm; picomoles per gram; picomole/gram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per hour per milliliter ","pmol/h/mL","(PMOL/HR)/ML","amount of substance",167281575000000,[-3,-1,0,0,0,0,0],"(pmol/h)/mL","si",true,null,null,1,false,false,1,0,"pmol/hrs/mL; pmol per hrs per mL; picomoles per hour per milliliter; millilitre; micro enzyme units per volume; enzymatic activity; enzyme activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. ","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per liter","pmol/L","PMOL/L","amount of substance",602213670000000,[-3,0,0,0,0,0,0],"pmol/L","si",true,null,null,1,false,false,1,0,"picomole/liter; pmol per L; picomoles; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per minute","pmol/min","PMOL/MIN","amount of substance",10036894500,[0,-1,0,0,0,0,0],"pmol/min","si",true,null,null,1,false,false,1,0,"picomole/minute; pmol per min; picomoles per minute; micro enzyme units; enzymatic activity; enzyme activity","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. pmol/min = uU (micro enzyme unit)","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per milliliter","pmol/mL","PMOL/ML","amount of substance",602213670000000000,[-3,0,0,0,0,0,0],"pmol/mL","si",true,null,null,1,false,false,1,0,"picomole/milliliter; picomole/millilitre; pmol per mL; picomoles; millilitre; picomols; pmols","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picomole per micromole","pmol/umol","PMOL/UMOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"pmol/μmol","si",true,null,null,1,false,false,0,0,"pmol/mcgmol; picomole/micromole; pmol per umol; pmol per mcgmol; picomoles ","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"picosecond","ps","PS","time",1e-12,[0,1,0,0,0,0,0],"ps",null,false,"T",null,1,false,false,0,0,"picoseconds; psec","LOINC","Time","Clinical","",null,null,null,null,false],[false,"picotesla","pT","PT","magnetic flux density",1e-9,[0,-1,1,0,0,-1,0],"pT","si",true,null,null,1,false,false,0,0,"picoteslas","LOINC","","Clinical","SI unit of magnetic field strength for magnetic field B","Wb/m2","WB/M2","1",1,false],[false,"enzyme unit per 12 hour","U/(12.h)","U/(12.HR)","catalytic activity",232335520833.33334,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,0,"U/12hrs; U/ 12hrs; U per 12 hrs; 12hrs; enzyme units per 12 hours; enzyme activity; enzymatic activity per time; umol per min per 12 hours; micromoles per minute per 12 hours; umol/min/12hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 2 hour","U/(2.h)","U/(2.HR)","catalytic activity",1394013125000,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,0,"U/2hrs; U/ 2hrs; U per 2 hrs; 2hrs; enzyme units per 2 hours; enzyme activity; enzymatic activity per time; umol per minute per 2 hours; micromoles per minute; umol/min/2hr; umol per min per 2hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 24 hour","U/(24.h)","U/(24.HR)","catalytic activity",116167760416.66667,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,0,"U/24hrs; U/ 24hrs; U per 24 hrs; 24hrs; enzyme units per 24 hours; enzyme activity; enzymatic activity per time; micromoles per minute per 24 hours; umol/min/24hr; umol per min per 24hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 10","U/10","U/10","catalytic activity",1003689450000000,[0,-1,0,0,0,0,0],"U","chemical",true,null,null,1,false,false,1,0,"enzyme unit/10; U per 10; enzyme units per 10; enzymatic activity; enzyme activity; micromoles per minute; umol/min/10","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per 10 billion","U/10*10","U/(10*10)","catalytic activity",1003689.45,[0,-1,0,0,0,0,0],"U/(1010)","chemical",true,null,null,1,false,false,1,0,"U per 10*10; enzyme units per 10*10; U per 10 billion; enzyme units; enzymatic activity; micromoles per minute per 10 billion; umol/min/10*10","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per trillion","U/10*12","U/(10*12)","catalytic activity",10036.8945,[0,-1,0,0,0,0,0],"U/(1012)","chemical",true,null,null,1,false,false,1,0,"enzyme unit/10*12; U per 10*12; enzyme units per 10*12; enzyme units per trillion; enzymatic activity; micromoles per minute per trillion; umol/min/10*12; umol per min per 10*12","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per million","U/10*6","U/(10*6)","catalytic activity",10036894500,[0,-1,0,0,0,0,0],"U/(106)","chemical",true,null,null,1,false,false,1,0,"enzyme unit/10*6; U per 10*6; enzyme units per 10*6; enzyme units; enzymatic activity per volume; micromoles per minute per million; umol/min/10*6; umol per min per 10*6","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per billion","U/10*9","U/(10*9)","catalytic activity",10036894.5,[0,-1,0,0,0,0,0],"U/(109)","chemical",true,null,null,1,false,false,1,0,"enzyme unit/10*9; U per 10*9; enzyme units per 10*9; enzymatic activity per volume; micromoles per minute per billion; umol/min/10*9; umol per min per 10*9","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per day","U/d","U/D","catalytic activity",116167760416.66667,[0,-2,0,0,0,0,0],"U/d","chemical",true,null,null,1,false,false,1,0,"U/dy; enzyme units per day; enzyme units; enzyme activity; enzymatic activity per time; micromoles per minute per day; umol/min/day; umol per min per day","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per deciliter","U/dL","U/DL","catalytic activity",100368945000000000000,[-3,-1,0,0,0,0,0],"U/dL","chemical",true,null,null,1,false,false,1,0,"U per dL; enzyme units per deciliter; decilitre; micromoles per minute per deciliter; umol/min/dL; umol per min per dL","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per gram","U/g","U/G","catalytic activity",10036894500000000,[0,-1,-1,0,0,0,0],"U/g","chemical",true,null,null,1,false,false,1,0,"U/gm; U per gm; enzyme units per gram; micromoles per minute per gram; umol/min/g; umol per min per g","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per hour","U/h","U/HR","catalytic activity",2788026250000,[0,-2,0,0,0,0,0],"U/h","chemical",true,null,null,1,false,false,1,0,"U/hr; U per hr; enzyme units per hour; micromoles per minute per hour; umol/min/hr; umol per min per hr","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per liter","U/L","U/L","catalytic activity",10036894500000000000,[-3,-1,0,0,0,0,0],"U/L","chemical",true,null,null,1,false,false,1,0,"enzyme unit/liter; enzyme unit/litre; U per L; enzyme units per liter; enzyme unit per litre; micromoles per minute per liter; umol/min/L; umol per min per L","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per minute","U/min","U/MIN","catalytic activity",167281575000000,[0,-2,0,0,0,0,0],"U/min","chemical",true,null,null,1,false,false,1,0,"enzyme unit/minute; U per min; enzyme units; umol/min/min; micromoles per minute per minute; micromoles per min per min; umol","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per milliliter","U/mL","U/ML","catalytic activity",1.00368945e+22,[-3,-1,0,0,0,0,0],"U/mL","chemical",true,null,null,1,false,false,1,0,"U per mL; enzyme units per milliliter; millilitre; micromoles per minute per milliliter; umol/min/mL; umol per min per mL","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"enzyme unit per second","U/s","U/S","catalytic activity",10036894500000000,[0,-2,0,0,0,0,0],"U/s","chemical",true,null,null,1,false,false,1,0,"U/sec; U per second; enzyme units per second; micromoles per minute per second; umol/min/sec; umol per min per sec","LOINC","CRat","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min)","umol/min","UMOL/MIN","1",1,false],[false,"micro international unit","u[IU]","U[IU]","arbitrary",0.000001,[0,0,0,0,0,0,0],"μi.U.","chemical",true,null,null,1,false,true,0,0,"uIU; u IU; microinternational units","LOINC","Arb","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"micro international unit per liter","u[IU]/L","U[IU]/L","arbitrary",0.001,[-3,0,0,0,0,0,0],"(μi.U.)/L","chemical",true,null,null,1,false,true,0,0,"uIU/L; u IU/L; uIU per L; microinternational units per liter; litre; ","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"micro international unit per milliliter","u[IU]/mL","U[IU]/ML","arbitrary",1,[-3,0,0,0,0,0,0],"(μi.U.)/mL","chemical",true,null,null,1,false,true,0,0,"uIU/mL; u IU/mL; uIU per mL; microinternational units per milliliter; millilitre","LOINC","ACnc","Clinical","International units (IU) are analyte and reference specimen specific arbitrary units (held at WHO)","[iU]","[IU]","1",1,false],[false,"microequivalent","ueq","UEQ","amount of substance",602213670000000000,[0,0,0,0,0,0,0],"μeq","chemical",true,null,null,1,false,false,0,1,"microequivalents; 10^-6 equivalents; 10-6 equivalents","LOINC","Sub","Clinical","","mol","MOL","1",1,false],[false,"microequivalent per liter","ueq/L","UEQ/L","amount of substance",602213670000000000000,[-3,0,0,0,0,0,0],"μeq/L","chemical",true,null,null,1,false,false,0,1,"ueq per liter; litre; microequivalents","LOINC","MCnc","Clinical","","mol","MOL","1",1,false],[false,"microequivalent per milliliter","ueq/mL","UEQ/ML","amount of substance",6.0221367000000003e+23,[-3,0,0,0,0,0,0],"μeq/mL","chemical",true,null,null,1,false,false,0,1,"ueq per milliliter; millilitre; microequivalents","LOINC","MCnc","Clinical","","mol","MOL","1",1,false],[false,"microgram","ug","UG","mass",0.000001,[0,0,1,0,0,0,0],"μg",null,false,"M",null,1,false,false,0,0,"mcg; micrograms; 10^-6 grams; 10-6 grams","LOINC","Mass","Clinical","",null,null,null,null,false],[false,"microgram per 100 gram","ug/(100.g)","UG/(100.G)","mass",1e-8,[0,0,0,0,0,0,0],"μg/g",null,false,"M",null,1,false,false,0,0,"ug/100gm; ug/100 gm; mcg; ug per 100g; 100 gm; mcg per 100g; micrograms per 100 grams","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"microgram per 24 hour","ug/(24.h)","UG/(24.HR)","mass",1.1574074074074074e-11,[0,-1,1,0,0,0,0],"μg/h",null,false,"M",null,1,false,false,0,0,"ug/24hrs; ug/24 hrs; mcg/24hrs; ug per 24hrs; mcg per 24hrs; 24 hrs; micrograms per 24 hours","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"microgram per 8 hour","ug/(8.h)","UG/(8.HR)","mass",3.472222222222222e-11,[0,-1,1,0,0,0,0],"μg/h",null,false,"M",null,1,false,false,0,0,"ug/8hrs; ug/8 hrs; mcg/8hrs; ug per 8hrs; mcg per 8hrs; 8 hrs; micrograms per 8 hours; shift","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"microgram per square foot (international)","ug/[sft_i]","UG/[SFT_I]","mass",0.000010763910416709721,[-2,0,1,0,0,0,0],"μg",null,false,"M",null,1,false,false,0,0,"ug/sft; ug/ft2; ug/ft^2; ug/sq. ft; micrograms; sq. foot; foot squared","LOINC","ArMass","Clinical","",null,null,null,null,false],[false,"microgram per day","ug/d","UG/D","mass",1.1574074074074074e-11,[0,-1,1,0,0,0,0],"μg/d",null,false,"M",null,1,false,false,0,0,"ug/dy; mcg/dy; ug per day; mcg; micrograms per day","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"microgram per deciliter","ug/dL","UG/DL","mass",0.009999999999999998,[-3,0,1,0,0,0,0],"μg/dL",null,false,"M",null,1,false,false,0,0,"ug per dL; mcg/dl; mcg per dl; micrograms per deciliter; decilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"microgram per gram","ug/g","UG/G","mass",0.000001,[0,0,0,0,0,0,0],"μg/g",null,false,"M",null,1,false,false,0,0,"ug per gm; mcg/gm; mcg per g; micrograms per gram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"microgram per hour","ug/h","UG/HR","mass",2.7777777777777777e-10,[0,-1,1,0,0,0,0],"μg/h",null,false,"M",null,1,false,false,0,0,"ug/hr; mcg/hr; mcg per hr; ug per hr; ug per hour; micrograms","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"microgram per kilogram","ug/kg","UG/KG","mass",9.999999999999999e-10,[0,0,0,0,0,0,0],"μg/kg",null,false,"M",null,1,false,false,0,0,"ug per kg; mcg/kg; mcg per kg; micrograms per kilogram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"microgram per kilogram per 8 hour","ug/kg/(8.h)","(UG/KG)/(8.HR)","mass",3.472222222222222e-14,[0,-1,0,0,0,0,0],"(μg/kg)/h",null,false,"M",null,1,false,false,0,0,"ug/kg/8hrs; mcg/kg/8hrs; ug/kg/8 hrs; mcg/kg/8 hrs; ug per kg per 8hrs; 8 hrs; mcg per kg per 8hrs; micrograms per kilograms per 8 hours; shift","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"microgram per kilogram per day","ug/kg/d","(UG/KG)/D","mass",1.1574074074074072e-14,[0,-1,0,0,0,0,0],"(μg/kg)/d",null,false,"M",null,1,false,false,0,0,"ug/(kg.d); ug/kg/dy; mcg/kg/day; ug per kg per dy; 24 hours; 24hrs; mcg; kilograms; microgram per kilogram and day","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"microgram per kilogram per hour","ug/kg/h","(UG/KG)/HR","mass",2.7777777777777774e-13,[0,-1,0,0,0,0,0],"(μg/kg)/h",null,false,"M",null,1,false,false,0,0,"ug/(kg.h); ug/kg/hr; mcg/kg/hr; ug per kg per hr; mcg per kg per hr; kilograms","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"microgram per kilogram per minute","ug/kg/min","(UG/KG)/MIN","mass",1.6666666666666664e-11,[0,-1,0,0,0,0,0],"(μg/kg)/min",null,false,"M",null,1,false,false,0,0,"ug/kg/min; ug/kg/min; mcg/kg/min; ug per kg per min; mcg; micrograms per kilograms per minute ","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"microgram per liter","ug/L","UG/L","mass",0.001,[-3,0,1,0,0,0,0],"μg/L",null,false,"M",null,1,false,false,0,0,"mcg/L; ug per L; mcg; micrograms per liter; litre ","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"microgram per liter per 24 hour","ug/L/(24.h)","(UG/L)/(24.HR)","mass",1.1574074074074074e-8,[-3,-1,1,0,0,0,0],"(μg/L)/h",null,false,"M",null,1,false,false,0,0,"ug/L/24hrs; ug/L/24 hrs; mcg/L/24hrs; ug per L per 24hrs; 24 hrs; day; dy mcg; micrograms per liters per 24 hours; litres","LOINC","","Clinical","unit used to measure mass dose rate per patient body mass",null,null,null,null,false],[false,"microgram per square meter","ug/m2","UG/M2","mass",0.000001,[-2,0,1,0,0,0,0],"μg/(m2)",null,false,"M",null,1,false,false,0,0,"ug/m^2; ug/sq. m; mcg/m2; mcg/m^2; mcg/sq. m; ug per m2; m^2; sq. meter; mcg; micrograms per square meter; meter squared; metre","LOINC","ArMass","Clinical","unit used to measure mass dose per patient body surface area",null,null,null,null,false],[false,"microgram per cubic meter","ug/m3","UG/M3","mass",0.000001,[-3,0,1,0,0,0,0],"μg/(m3)",null,false,"M",null,1,false,false,0,0,"ug/m^3; ug/cu. m; mcg/m3; mcg/m^3; mcg/cu. m; ug per m3; ug per m^3; ug per cu. m; mcg; micrograms per cubic meter; meter cubed; metre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"microgram per milligram","ug/mg","UG/MG","mass",0.001,[0,0,0,0,0,0,0],"μg/mg",null,false,"M",null,1,false,false,0,0,"ug per mg; mcg/mg; mcg per mg; micromilligrams per milligram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"microgram per minute","ug/min","UG/MIN","mass",1.6666666666666667e-8,[0,-1,1,0,0,0,0],"μg/min",null,false,"M",null,1,false,false,0,0,"ug per min; mcg/min; mcg per min; microminutes per minute","LOINC","MRat","Clinical","",null,null,null,null,false],[false,"microgram per milliliter","ug/mL","UG/ML","mass",1,[-3,0,1,0,0,0,0],"μg/mL",null,false,"M",null,1,false,false,0,0,"ug per mL; mcg/mL; mcg per mL; micrograms per milliliter; millilitre","LOINC","MCnc","Clinical","",null,null,null,null,false],[false,"microgram per millimole","ug/mmol","UG/MMOL","mass",1.660540186674939e-27,[0,0,1,0,0,0,0],"μg/mmol",null,false,"M",null,1,false,false,-1,0,"ug per mmol; mcg/mmol; mcg per mmol; micrograms per millimole","LOINC","Ratio","Clinical","",null,null,null,null,false],[false,"microgram per nanogram","ug/ng","UG/NG","mass",999.9999999999999,[0,0,0,0,0,0,0],"μg/ng",null,false,"M",null,1,false,false,0,0,"ug per ng; mcg/ng; mcg per ng; micrograms per nanogram","LOINC","MCnt","Clinical","",null,null,null,null,false],[false,"microkatal","ukat","UKAT","catalytic activity",602213670000000000,[0,-1,0,0,0,0,0],"μkat","chemical",true,null,null,1,false,false,1,0,"microkatals; ukats","LOINC","CAct","Clinical","kat is a unit of catalytic activity with base units = mol/s. Rarely used because its units are too large to practically express catalytic activity. See enzyme unit [U] which is the standard unit for catalytic activity.","mol/s","MOL/S","1",1,false],[false,"microliter","uL","UL","volume",1e-9,[3,0,0,0,0,0,0],"μL","iso1000",true,null,null,1,false,false,0,0,"microliters; microlitres; mcl","LOINC","Vol","Clinical","","l",null,"1",1,false],[false,"microliter per 2 hour","uL/(2.h)","UL/(2.HR)","volume",1.388888888888889e-13,[3,-1,0,0,0,0,0],"μL/h","iso1000",true,null,null,1,false,false,0,0,"uL/2hrs; uL/2 hrs; mcg/2hr; mcg per 2hr; uL per 2hr; uL per 2 hrs; microliters per 2 hours; microlitres ","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"microliter per hour","uL/h","UL/HR","volume",2.777777777777778e-13,[3,-1,0,0,0,0,0],"μL/h","iso1000",true,null,null,1,false,false,0,0,"uL/hr; mcg/hr; mcg per hr; uL per hr; microliters per hour; microlitres","LOINC","VRat","Clinical","","l",null,"1",1,false],[false,"micrometer","um","UM","length",0.000001,[1,0,0,0,0,0,0],"μm",null,false,"L",null,1,false,false,0,0,"micrometers; micrometres; μm; microns","LOINC","Len","Clinical","Unit of length that is usually used in tests related to the eye",null,null,null,null,false],[false,"microns per second","um/s","UM/S","length",0.000001,[1,-1,0,0,0,0,0],"μm/s",null,false,"L",null,1,false,false,0,0,"um/sec; micron/second; microns/second; um per sec; micrometers per second; micrometres","LOINC","Vel","Clinical","",null,null,null,null,false],[false,"micromole","umol","UMOL","amount of substance",602213670000000000,[0,0,0,0,0,0,0],"μmol","si",true,null,null,1,false,false,1,0,"micromoles; umols","LOINC","Sub","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per 2 hour","umol/(2.h)","UMOL/(2.HR)","amount of substance",83640787500000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,0,"umol/2hrs; umol/2 hrs; umol per 2 hrs; 2hrs; micromoles per 2 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per 24 hour","umol/(24.h)","UMOL/(24.HR)","amount of substance",6970065625000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,0,"umol/24hrs; umol/24 hrs; umol per 24 hrs; per 24hrs; micromoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per 8 hour","umol/(8.h)","UMOL/(8.HR)","amount of substance",20910196875000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,0,"umol/8hr; umol/8 hr; umol per 8 hr; umol per 8hr; umols per 8hr; umol per 8 hours; micromoles per 8 hours; shift","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per day","umol/d","UMOL/D","amount of substance",6970065625000,[0,-1,0,0,0,0,0],"μmol/d","si",true,null,null,1,false,false,1,0,"umol/day; umol per day; umols per day; umol per days; micromoles per days; umol/24hr; umol/24 hr; umol per 24 hr; umol per 24hr; umols per 24hr; umol per 24 hours; micromoles per 24 hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per deciliter","umol/dL","UMOL/DL","amount of substance",6.0221367e+21,[-3,0,0,0,0,0,0],"μmol/dL","si",true,null,null,1,false,false,1,0,"micromole/deciliter; micromole/decilitre; umol per dL; micromoles per deciliters; micromole per decilitres","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per gram","umol/g","UMOL/G","amount of substance",602213670000000000,[0,0,-1,0,0,0,0],"μmol/g","si",true,null,null,1,false,false,1,0,"micromole/gram; umol per g; micromoles per gram","LOINC","SCnt; Ratio","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per hour","umol/h","UMOL/HR","amount of substance",167281575000000,[0,-1,0,0,0,0,0],"μmol/h","si",true,null,null,1,false,false,1,0,"umol/hr; umol per hr; umol per hour; micromoles per hours","LOINC","SRat","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per kilogram","umol/kg","UMOL/KG","amount of substance",602213670000000,[0,0,-1,0,0,0,0],"μmol/kg","si",true,null,null,1,false,false,1,0,"umol per kg; micromoles per kilogram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per liter","umol/L","UMOL/L","amount of substance",602213670000000000000,[-3,0,0,0,0,0,0],"μmol/L","si",true,null,null,1,false,false,1,0,"micromole/liter; micromole/litre; umol per liter; micromoles per liter; litre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per liter per hour","umol/L/h","(UMOL/L)/HR","amount of substance",167281575000000000,[-3,-1,0,0,0,0,0],"(μmol/L)/h","si",true,null,null,1,false,false,1,0,"umol/liter/hr; umol/litre/hr; umol per L per hr; umol per liter per hour; micromoles per liters per hour; litre","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min; umol/L/h is a derived unit of enzyme units","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per milligram","umol/mg","UMOL/MG","amount of substance",602213670000000000000,[0,0,-1,0,0,0,0],"μmol/mg","si",true,null,null,1,false,false,1,0,"micromole/milligram; umol per mg; micromoles per milligram","LOINC","SCnt","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per minute","umol/min","UMOL/MIN","amount of substance",10036894500000000,[0,-1,0,0,0,0,0],"μmol/min","si",true,null,null,1,false,false,1,0,"micromole/minute; umol per min; micromoles per minute; enzyme units","LOINC","CAct","Clinical","unit for the enzyme unit U = umol/min","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per minute per gram","umol/min/g","(UMOL/MIN)/G","amount of substance",10036894500000000,[0,-1,-1,0,0,0,0],"(μmol/min)/g","si",true,null,null,1,false,false,1,0,"umol/min/gm; umol per min per gm; micromoles per minutes per gram; U/g; enzyme units","LOINC","CCnt","Clinical","unit for the enzyme unit U = umol/min. umol/min/g = U/g","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per minute per liter","umol/min/L","(UMOL/MIN)/L","amount of substance",10036894500000000000,[-3,-1,0,0,0,0,0],"(μmol/min)/L","si",true,null,null,1,false,false,1,0,"umol/min/liter; umol/minute/liter; micromoles per minutes per liter; litre; enzyme units; U/L","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. umol/min/L = U/L","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per milliliter","umol/mL","UMOL/ML","amount of substance",6.0221367000000003e+23,[-3,0,0,0,0,0,0],"μmol/mL","si",true,null,null,1,false,false,1,0,"umol per mL; micromoles per milliliter; millilitre","LOINC","SCnc","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per milliliter per minute","umol/mL/min","(UMOL/ML)/MIN","amount of substance",1.00368945e+22,[-3,-1,0,0,0,0,0],"(μmol/mL)/min","si",true,null,null,1,false,false,1,0,"umol per mL per min; micromoles per milliliters per minute; millilitres","LOINC","CCnc","Clinical","unit for the enzyme unit U = umol/min. umol/mL/min = U/mL","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per millimole","umol/mmol","UMOL/MMOL","amount of substance",0.001,[0,0,0,0,0,0,0],"μmol/mmol","si",true,null,null,1,false,false,0,0,"umol per mmol; micromoles per millimole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per mole","umol/mol","UMOL/MOL","amount of substance",0.000001,[0,0,0,0,0,0,0],"μmol/mol","si",true,null,null,1,false,false,0,0,"umol per mol; micromoles per mole","LOINC","SRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"micromole per micromole","umol/umol","UMOL/UMOL","amount of substance",1,[0,0,0,0,0,0,0],"μmol/μmol","si",true,null,null,1,false,false,0,0,"umol per umol; micromoles per micromole","LOINC","Srto; SFr; EntSRto","Clinical","","10*23","10*23","6.0221367",6.0221367,false],[false,"microOhm","uOhm","UOHM","electric resistance",0.001,[2,-1,1,0,0,-2,0],"μΩ","si",true,null,null,1,false,false,0,0,"microOhms; µΩ","LOINC","","Clinical","unit of electric resistance","V/A","V/A","1",1,false],[false,"microsecond","us","US","time",0.000001,[0,1,0,0,0,0,0],"μs",null,false,"T",null,1,false,false,0,0,"microseconds","LOINC","Time","Clinical","",null,null,null,null,false],[false,"micro enzyme unit per gram","uU/g","UU/G","catalytic activity",10036894500,[0,-1,-1,0,0,0,0],"μU/g","chemical",true,null,null,1,false,false,1,0,"uU per gm; micro enzyme units per gram; micro enzymatic activity per mass; enzyme activity","LOINC","CCnt","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 uU = 1pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"micro enzyme unit per liter","uU/L","UU/L","catalytic activity",10036894500000,[-3,-1,0,0,0,0,0],"μU/L","chemical",true,null,null,1,false,false,1,0,"uU per L; micro enzyme units per liter; litre; enzymatic activity per volume; enzyme activity ","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 uU = 1pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"micro enzyme unit per milliliter","uU/mL","UU/ML","catalytic activity",10036894500000000,[-3,-1,0,0,0,0,0],"μU/mL","chemical",true,null,null,1,false,false,1,0,"uU per mL; micro enzyme units per milliliter; millilitre; enzymatic activity per volume; enzyme activity","LOINC","CCnc","Clinical","1 U is the standard enzyme unit which equals 1 micromole substrate catalyzed per minute (1 umol/min); 1 uU = 1pmol/min","umol/min","UMOL/MIN","1",1,false],[false,"microvolt","uV","UV","electric potential",0.001,[2,-2,1,0,0,-1,0],"μV","si",true,null,null,1,false,false,0,0,"microvolts","LOINC","Elpot","Clinical","unit of electric potential (voltage)","J/C","J/C","1",1,false]]}}
-
-},{}],62:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.Ucum = void 0;
-/*
- * This defines the namespace for the UCUM classes and provides
- * a place for the definition of global variables and constants.
- *
- * The javascript for this UCUM implementation uses syntax as
- * defined by the ECMAScript 6 standard
- */
-
-var Ucum = exports.Ucum = {
- /**
- * Flag indicating whether or not we're using case sensitive labels
- * I don't think we need this. I think we're just going with
- * case sensitive, per Clem. Gunther's code has this flag, but I
- * am removing it, at least for now. lm, 6/2016
- */
- //caseSensitive_: true ,
-
- /**
- * The number of elements in a Dimension array. Currently this
- * is set as a configuration variable, but when we get to the point
- * of loading the unit definitions from a file, this value will be
- * set from that.
- */
- dimLen_: 7,
- /**
- * The characters used as valid operators in a UCUM unit expression,
- * where '.' is for multiplication and '/' is for division.
- */
- validOps_: ['.', '/'],
- /**
- * The string used to separate a unit code and unit name when they
- * are displayed together
- */
- codeSep_: ': ',
- // Message text variations for validation methods and conversion methods
- valMsgStart_: 'Did you mean ',
- valMsgEnd_: '?',
- cnvMsgStart_: 'We assumed you meant ',
- cnvMsgEnd_: '.',
- /**
- * Default opening string used to emphasize portions of error messages.
- * Used when NOT displaying messages on a web site, i.e., for output
- * from the library methods or to a file.
- */
- openEmph_: ' ->',
- /**
- * Default closing string used to emphasize portions of error messages.
- * Used when NOT displaying messages on a web site, i.e., for output
- * from the library methods or to a file.
- */
- closeEmph_: '<- ',
- /**
- * Opening HTML used to emphasize portions of error messages. Used when
- * displaying messages on a web site; should be blank when output is
- * to a file.
- */
- openEmphHTML_: ' ',
- /**
- * Closing HTML used to emphasize portions of error messages. Used when
- * displaying messages on a web site; should be blank when output is
- * to a file.
- */
- closeEmphHTML_: ' ',
- /**
- * Message that is displayed when annotations are included in a unit
- * string, to let the user know how they are interpreted.
- */
- bracesMsg_: 'FYI - annotations (text in curly braces {}) are ignored, ' + 'except that an annotation without a leading symbol implies ' + 'the default unit 1 (the unity).',
- /**
- * Message that is displayed or returned when a conversion is requested
- * for two units where (only) a mass<->moles conversion is appropriate
- * but no molecular weight was specified.
- */
- needMoleWeightMsg_: 'Did you wish to convert between mass and moles? The ' + 'molecular weight of the substance represented by the ' + 'units is required to perform the conversion.',
- /**
- * Message that is returned when a mass<->eq conversion is requested
- * (which requires a molecular weight to calculate), but no molecular
- * weight was provided by the user.
- */
- needEqWeightMsg_: 'Did you wish to convert with equivalents? The ' + 'molecular weight of the substance is required to perform ' + 'the conversion.',
- /**
- * Message that is returned when a mass<->eq or a mol<->eq conversion
- * is requested (which requires a charge to calculate), but no charge
- * was provided by the user.
- */
- needEqChargeMsg_: 'Did you wish to convert with equivalents? The ' + 'charge of the substance is required to perform ' + 'the conversion.',
- /**
- * Hash that matches unit column names to names used in the csv file
- * that is submitted to the data updater.
- */
- csvCols_: {
- 'case-sensitive code': 'csCode_',
- 'LOINC property': 'loincProperty_',
- 'name (display)': 'name_',
- 'synonyms': 'synonyms_',
- 'source': 'source_',
- 'category': 'category_',
- 'Guidance': 'guidance_'
- },
- /**
- * Name of the column in the csv file that serves as the key
- */
- inputKey_: 'case-sensitive code',
- /**
- * Special codes that contain operators within brackets. The operator
- * within these codes causes them to parse incorrectly if they are preceded
- * by a prefix, because the parsing algorithm splits them up on the operator.
- * So we use this object to identify them and substitute placeholders to
- * avoid that.
- */
- specUnits_: {
- 'B[10.nV]': 'specialUnitOne',
- '[m/s2/Hz^(1/2)]': 'specialUnitTwo'
- }
-};
-
-
-},{}],63:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.Dimension = void 0;
-/**
- * This class implements an object containing the vector of exponents for
- * a unit and its operations for addition, subtraction, and multiplication
- * with a scalar.
- *
- * This object should exist for each unit that can be expressed as a
- * vector of numbers. This excludes arbitrary units, e.g., (10*23), and
- * units that are not numbers but are an expression based solely on numbers,
- * e.g., mol (mole) which is based on 10*23.
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- */
-var UC = require('./config.js');
-var isInteger = require("is-integer");
-class Dimension {
- /**
- * Constructor.
- *
- * @param dimSetting an optional parameter that may be:
- * null, which means that the dimVec_ attribute for this object will be null; or
- * an array, which must be the length defined by Ucum.dimLen_, and
- * whose contents will be copied to this new object's vector; or
- * an integer, which must be between 0 and 1 less than the vector length
- * defined by Ucum.dimLen_. This new object's vector will be
- * initialized to zero for all elements except the one whose index
- * matches the number passed in. That element will be set to one.
- * @throws an error if the dimSetting parameter does not meet the types
- * listed above.
- * An error will also be thrown if Ucum.dimLen_ has not been set yet,
- * i.e., is still zero. Currently that won't happen, because the
- * value is set in the config.js file. But further down the road
- * the setting will come from a definitions input file, so we check
- * here anyway.
- *
- */
- constructor(dimSetting) {
- if (UC.Ucum.dimLen_ === 0) {
- throw new Error('Dimension.setDimensionLen must be called before ' + 'Dimension constructor');
- }
- if (dimSetting === undefined || dimSetting === null) {
- this.assignZero();
- } else if (dimSetting instanceof Array) {
- if (dimSetting.length !== UC.Ucum.dimLen_) {
- throw new Error('Parameter error, incorrect length of vector passed to ' + `Dimension constructor, vector = ${JSON.stringify(dimSetting)}`);
- }
- this.dimVec_ = [];
- for (let d = 0; d < UC.Ucum.dimLen_; d++) this.dimVec_.push(dimSetting[d]);
- }
-
- // In es6 this should be Number.isInteger(dimSetting). But Babel
- // doesn't transpile that correctly, so we need to use the isInteger
- // module. :0
- else if (isInteger(dimSetting)) {
- if (dimSetting < 0 || dimSetting >= UC.Ucum.dimLen_) {
- throw new Error('Parameter error, invalid element number specified for ' + 'Dimension constructor');
- }
- this.assignZero();
- this.dimVec_[dimSetting] = 1;
- }
- } // end constructor
-
- /**
- * Sets the element at the specified position to a specified value. The
- * default value is 1. If the dimension vector is null when this is called
- * a zero-filled vector is created and then the indicated position is set.
- *
- * @param indexPos the index of the element to be set
- * @param value the value to assign to the specified element; optional,
- * default value is 1
- * @throws an exception if the specified position is invalid, i.e., not a
- * number or is less than 0 or greater than Ucum.dimLen_
- **/
- setElementAt(indexPos, value) {
- if (!isInteger(indexPos) || indexPos < 0 || indexPos >= UC.Ucum.dimLen_) {
- throw new Error(`Dimension.setElementAt called with an invalid index ` + `position (${indexPos})`);
- }
- if (!this.dimVec_) {
- this.assignZero();
- }
- if (value === undefined || value === null) value = 1;
- this.dimVec_[indexPos] = value;
- }
-
- /**
- * Gets the value of the element at the specified position
- *
- * @param indexPos the index of the element whose value is to be returned
- * @return the value of the element at indexPos, or null if the dimension
- * vector is null
- * @throws an exception if the specified position is invalid, i.e., not a
- * number or is less than 0 or greater than Ucum.dimLen_
- **/
- getElementAt(indexPos) {
- if (!isInteger(indexPos) || indexPos < 0 || indexPos >= UC.Ucum.dimLen_) {
- throw new Error(`Dimension.getElementAt called with an invalid index ` + `position (${indexPos})`);
- }
- let ret = null;
- if (this.dimVec_) ret = this.dimVec_[indexPos];
- return ret;
- }
-
- /**
- * This returns the value of the property named by the parameter
- * passed in. Although we currently only have one property, dimVec_,
- * that this will get, it's possible that we'll have additional
- * properties. If we don't this could just be replaced by a
- * getVector function.
- *
- * @param propertyName name of the property to be returned, with
- * or without the trailing underscore.
- * @return the requested property, if found for this Dimension
- * @throws an error if the property is not found for this Dimension
- */
- getProperty(propertyName) {
- let uProp = propertyName.charAt(propertyName.length - 1) === '_' ? propertyName : propertyName + '_';
- return this[uProp];
- } // end getProperty
-
- /**
- * Return a string that represents the dimension vector. Returns null if
- * the dimension vector is null.
- *
- * @return the string that represents the dimension vector. The
- * values are enclosed in square brackets, each separated
- * by a comma and a space
- **/
- toString() {
- let ret = null;
- if (this.dimVec_) ret = '[' + this.dimVec_.join(', ') + ']';
- return ret;
- }
-
- /**
- * Adds the vector of the dimension object passed in to this
- * dimension object's vector. This object's vector is changed.
- * If either dimension vector is null, no changes are made to this object.
- *
- *
- * @param dim2 the dimension whose vector is to be added to this one
- * @return this object
- * @throws an exception if dim2 is not a Dimension object
- **/
- add(dim2) {
- if (!(dim2 instanceof Dimension)) {
- throw new Error(`Dimension.add called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`);
- }
- if (this.dimVec_ && dim2.dimVec_) {
- for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] += dim2.dimVec_[i];
- }
- return this;
- }
-
- /**
- * Subtracts the vector of the dimension object passed in from this
- * dimension object's vector. This object's vector is changed.
- * If either dimension vector is null, no changes are made to this object.
- *
- * @param dim2 the dimension whose vector is to be subtracted from this one
- * @return this object
- * @throws an exception if dim2 is not a Dimension object
- **/
- sub(dim2) {
- if (!(dim2 instanceof Dimension)) {
- throw new Error(`Dimension.sub called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`);
- }
- if (this.dimVec_ && dim2.dimVec_) {
- for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] -= dim2.dimVec_[i];
- }
- return this;
- }
-
- /**
- * Inverts this dimension object's vector (by multiplying each element
- * by negative 1). This object's vector is changed - unless it is null,
- * in which case it stays that way.
- *
- * @return this object
- **/
- minus() {
- if (this.dimVec_) {
- for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] = -this.dimVec_[i];
- }
- return this;
- }
-
- /**
- * Multiplies this dimension object's vector with a scalar. This is used
- * when a unit is raised to a power. This object's vector is changed unless
- * the vector is null, in which case it stays that way.
- *
- * @param s the integer scalar to use
- * @return this object
- * @throws an exception if s is not an integer
- */
- mul(s) {
- if (!isInteger(s)) {
- throw new Error(`Dimension.mul called with an invalid parameter - ` + `${typeof s} instead of an integer`);
- }
- if (this.dimVec_) {
- for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] *= s;
- }
- return this;
- }
-
- /**
- * Tests for equality of this dimension object's vector and that of
- * the dimension object passed in. If the dimension vector for one of
- * the objects is null, the dimension vector for the other object must
- * also be null for the two to be equal. (I know - duh. still)
- *
- * @param dim2 the dimension object whose vector is to be compared to this one
- * @return true if the two vectors are equal; false otherwise.
- * @throws an exception if dim2 is not a Dimension object
- */
- equals(dim2) {
- if (!(dim2 instanceof Dimension)) {
- throw new Error(`Dimension.equals called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`);
- }
- let isEqual = true;
- let dimVec2 = dim2.dimVec_;
- if (this.dimVec_ && dimVec2) {
- for (let i = 0; isEqual && i < UC.Ucum.dimLen_; i++) isEqual = this.dimVec_[i] === dimVec2[i];
- } else {
- isEqual = this.dimVec_ === null && dimVec2 === null;
- }
- return isEqual;
- }
-
- /**
- * Assigns the contents of the vector belonging to the dimension object
- * passed in to this dimension's vector. If this dimension vector is null
- * and the other is not, this one will get the contents of the other. If
- * this dimension vector is not null but the one passed in is null, this
- * one will be set to null.
- *
- * @param dim2 the dimension object with the vector whose contents are
- * to be assigned to this dimension's vector
- * @return this object (not sure why)
- * @throws an exception if dim2 is not a Dimension object
- */
- assignDim(dim2) {
- if (!(dim2 instanceof Dimension)) {
- throw new Error(`Dimension.assignDim called with an invalid parameter - ` + `${typeof dim2} instead of a Dimension object`);
- }
- if (dim2.dimVec_ === null) this.dimVec_ = null;else {
- if (this.dimVec_ === null) {
- this.dimVec_ = [];
- }
- for (let i = 0; i < UC.Ucum.dimLen_; i++) this.dimVec_[i] = dim2.dimVec_[i];
- }
- return this;
- }
-
- /**
- * Sets all elements of this dimension object's vector to zero.
- * If this object's vector is null, it is created as a zero-filled vector.
- *
- * @return this object (not sure why)
- */
- assignZero() {
- if (this.dimVec_ === null || this.dimVec_ === undefined) this.dimVec_ = [];
- for (let i = 0; i < UC.Ucum.dimLen_; i++) {
- this.dimVec_.push(0);
- }
- return this;
- }
-
- /**
- * Tests for a dimension vector set to all zeroes.
- *
- * @return true if exponents (elements) of this dimension's vector are all
- * zero; false otherwise (including if the current vector is null).
- *
- */
- isZero() {
- let allZero = this.dimVec_ !== null;
- if (this.dimVec_) {
- for (let i = 0; allZero && i < UC.Ucum.dimLen_; i++) allZero = this.dimVec_[i] === 0;
- }
- return allZero;
- }
-
- /**
- * Tests for a Dimension object with no dimension vector (dimVec_ is null).
- *
- * @return true the dimension vector is null; false if it is not
- *
- */
- isNull() {
- return this.dimVec_ === null;
- }
-
- /**
- * Creates and returns a clone of this Dimension object
- *
- * @return the clone
- */
- clone() {
- let that = new Dimension();
- that.assignDim(this);
- return that;
- }
-} // end Dimension class
-exports.Dimension = Dimension;
-
-
-},{"./config.js":62,"is-integer":77}],64:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.packArray = packArray;
-exports.unpackArray = unpackArray;
-/**
- * This file provides functions to reduce the size of an array of objects of the same structure in JSON.
- */
-const pushFn = Array.prototype.push;
-function isObject(value) {
- return Object.prototype.toString.call(value) === '[object Object]';
-}
-
-/**
- * Makes human readable config used to pack/unpack array of objects of the same structure to store with packed data.
- * @param {Object} refObj - reference item of array of objects of the same structure
- * @returns {Array}
- */
-function createConfig(refObj) {
- return Object.keys(refObj).reduce((config, key) => {
- if (isObject(refObj[key])) {
- pushFn.apply(config, createConfig(refObj[key]).map(keyTail => [key, ...[].concat(keyTail)]));
- } else {
- config.push(key);
- }
- return config;
- }, []);
-}
-
-/**
- * Prepares config created with createConfig function to use in packItem/unpackItem functions.
- * @param {Array} config
- * @returns {Array}
- */
-function prepareConfig(config) {
- return config.map(key => Array.isArray(key) ? key : [key]);
-}
-
-/**
- * Converts an object to an array of values in the order of keys from configuration array.
- * @param {Array} config - configuration array
- * @param {Object} item - input object
- * @returns {Array}
- */
-function packItem(config, item) {
- if (config.join() !== prepareConfig(createConfig(item)).join()) {
- throw new Error('Object of unusual structure');
- }
- return config.map(keyArr => {
- let place = item;
- keyArr.forEach(key => {
- place = place[key];
- if (place === undefined) {
- throw new Error('Object of unusual structure');
- }
- });
- return place;
- });
-}
-
-/**
- * Performs the reverse of packItem function.
- * @param {Array} config - configuration array
- * @param {Array} item - input object
- * @returns {Object}
- */
-function unpackItem(config, item) {
- let result = {};
- config.forEach((keyArr, i) => {
- let place = result;
- for (let i = 0; i < keyArr.length - 1; i++) {
- place = place[keyArr[i]] = place[keyArr[i]] || {};
- }
- place[keyArr[keyArr.length - 1]] = item[i];
- });
- return result;
-}
-
-/**
- * Reduces size of an array of objects of the same structure before serialize it to JSON
- * @param {Array} arr
- * @returns {Object}
- */
-function packArray(arr) {
- if (arr && arr.length) {
- const config = createConfig(arr[0]),
- _config = prepareConfig(config);
- if (config.length) {
- return {
- config: config,
- data: arr.map(packItem.bind(null, _config))
- };
- }
- }
- return {
- config: [],
- data: arr
- };
-}
-
-/**
- * Restores an array of objects of the same structure after deserializing this object from JSON
- * @param {Object} obj
- * @returns {Array}
- */
-function unpackArray(obj) {
- const config = obj && obj.config;
- if (config) {
- if (config.length && obj.data) {
- const _config = prepareConfig(config);
- return obj.data.map(unpackItem.bind(null, _config));
- } else {
- return obj.data;
- }
- }
- return obj;
-}
-
-
-},{}],65:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.Prefix = void 0;
-/**
- * Prefix objects are defined in this file.
- */
-
-/**
- * This class implements the prefix object. Prefixes are used as multipliers
- * for units, e.g., km for kilometers
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- *
- */
-var Ucum = require('./config.js');
-class Prefix {
- /**
- * Creates a single prefix object.
- *
- * @param attrs a hash of the values to use in creating the prefix object.
- * They should be:
- * code_ - which is the case-sensitive code used for the prefix,
- * e.g., k for kilo
- * ciCode_ - which is the case-insensitive code used for the prefix,
- * e.g., K for kilo
- * name_ - which is the name of the prefix, e.g., kilo
- * printSymbol_ - which is the print symbol for the prefix, e.g., k for kilo
- * value_ - which is teh value to use in multiplying the magnitude of
- * a unit, e.g., for a prefix of c the value will be .01.
- * exp_ - which is the exponent used to get the value. For decimal based
- * prefixes the base is 10 and the exp_ is applied to 10, e.g., for a
- * prefix of c, the exponent will be -2. For prefixes that are not
- * decimal based, this will be null (but must not be undefined).
- *
- * @throws an error if the not all required parameters are provided
- */
- constructor(attrs) {
- if (attrs['code_'] === undefined || attrs['code_'] === null || attrs['name_'] === undefined || attrs['name_'] === null || attrs['value_'] === undefined || attrs['value_'] === null || attrs['exp_'] === undefined) {
- throw new Error('Prefix constructor called missing one or more parameters. ' + 'Prefix codes (cs or ci), name, value and exponent must all be specified ' + 'and all but the exponent must not be null.');
- }
-
- /**
- * The prefix code, e.g., k for kilo. This should be the case-sensitive
- * code. Since there's no way to check to see if it's the case-sensitive
- * one as opposed to the case-insensitive one (because although
- * case-insensitive codes all seem to be uppercase, some case-sensitive
- * codes are also all uppercase), we'll just have to believe that the
- * right one was passed in.
- */
- this.code_ = attrs['code_'];
-
- /**
- * The case-insensitive code, e.g., K for kilo
- */
- this.ciCode_ = attrs['ciCode_'];
-
- /**
- * The prefix name, e.g., kilo
- */
- this.name_ = attrs['name_'];
-
- /**
- * The printSymbol for the prefix, e.g., k for kilo
- */
- this.printSymbol_ = attrs['printSymbol_'];
-
- /**
- * The value to use in multiplying the magnitude of a unit
- */
- if (typeof attrs['value_'] === 'string') this.value_ = parseFloat(attrs['value_']);else this.value_ = attrs['value_'];
-
- /**
- * The exponent used to create the value from 10. For prefixes that are
- * not based on 10, this will be null.
- */
- this.exp_ = attrs['exp_'];
- } // end constructor
-
- /**
- * Returns the value for the current prefix object
- * @return the value for the prefix object with the specified code
- * */
- getValue() {
- return this.value_;
- }
-
- /**
- * Returns the prefix code for the current prefix object
- * @return the code for the current prefix object
- */
- getCode() {
- return this.code_;
- }
-
- /**
- * Returns the case-insensitive code for the current prefix object
- * @return the case_insensitive code for the current prefix object
- */
- getCiCode() {
- return this.ciCode_;
- }
-
- /**
- * Returns the prefix name for the current prefix object
- * @return the name for the current prefix object
- */
- getName() {
- return this.name_;
- }
-
- /**
- * Returns the print symbol for the current prefix object
- * @return the print symbol for the current prefix object
- */
- getPrintSymbol() {
- return this.printSymbol_;
- }
-
- /**
- * Returns the exponent for the current prefix object
- * @return the exponent for the current prefix object
- */
- getExp() {
- return this.exp_;
- }
-
- /**
- * Provides way to tell if one prefix equals another. The second prefix
- * must match all attribute values.
- *
- * @param prefix2 prefix object to check for a match
- * @return true for a match; false if one or more attributes don't match
- */
- equals(prefix2) {
- return this.code_ === prefix2.code_ && this.ciCode_ === prefix2.ciCode_ && this.name_ === prefix2.name_ && this.printSymbol_ === prefix2.printSymbol_ && this.value_ === prefix2.value_ && this.exp_ === prefix2.exp_;
- }
-} // end Prefix class
-exports.Prefix = Prefix;
-
-
-},{"./config.js":62}],66:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.PrefixTablesFactory = exports.PrefixTables = void 0;
-/**
- * The tables of defined prefixes is defined in this file.
- */
-
-/**
- * This class implements the table of multiplier prefixes.
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- *
- */
-class PrefixTablesFactory {
- /**
- * Constructor. This creates the empty PrefixTable hashes once.
- * There is one hash whose key is the prefix code and one whose
- * key is the prefix value.
- *
- * Implementation of this as a singleton is based on the UnitTables
- * implementation. See that class for details.
- */
- constructor() {
- this.byCode_ = {};
- this.byValue_ = {};
- }
-
- /**
- * Provides the number of prefix objects in each table
- * @returns count of the number of prefix objects in each table
- */
- prefixCount() {
- return Object.keys(this.byCode_).length;
- }
-
- /**
- * This is used to get all prefix objects by value. Currently it is used
- * to create a csv file with all prefixes and units.
- * @returns csv string containing all prefix objects, ordered by value.
- */
- allPrefixesByValue() {
- let prefixBuff = '';
- let pList = Object.keys(this.byValue_);
- //pList.sort() ;
- let pLen = pList.length;
- for (let p = 0; p < pLen; p++) {
- let pfx = this.getPrefixByValue(pList[p]);
- prefixBuff += pfx.code_ + ',' + pfx.name_ + ',,' + pfx.value_ + '\r\n';
- }
- return prefixBuff;
- }
-
- /**
- * This is used to get all prefix objects. Currently it is used
- * to get the objects to write to the json ucum definitions file
- * that is used to provide prefix and unit definition objects for
- * conversions and validations.
- *
- * @returns an array containing all prefix objects, ordered by code.
- */
- allPrefixesByCode() {
- let prefixList = [];
- let pList = Object.keys(this.byCode_);
- pList.sort();
- let pLen = pList.length;
- for (let p = 0; p < pLen; p++) {
- prefixList.push(this.getPrefixByCode(pList[p]));
- }
- return prefixList;
- }
-
- /**
- * Adds a prefix object to the tables
- *
- * @param prefixObj the object to be added to the tables
- */
- add(prefixObj) {
- this.byCode_[prefixObj.getCode()] = prefixObj;
- this.byValue_[prefixObj.getValue()] = prefixObj;
- }
-
- /**
- * Tests whether a prefix object is found for a specified code. This
- * is used to determine whether or not a prefix object has been created
- * for the code.
- *
- * @param code the code to be used to find the prefix object
- * @return boolean indicating whether or not a prefix object was found
- * for the specified code
- */
- isDefined(code) {
- return this.byCode_[code] !== null && this.byCode_[code] !== undefined;
- }
-
- /**
- * Obtains a prefix object for a specified code.
- *
- * @param code the code to be used to find the prefix object
- * @return the prefix object found, or null if nothing was found
- */
- getPrefixByCode(code) {
- return this.byCode_[code];
- }
-
- /**
- * Obtains a prefix object for a specified value.
- *
- * @param value the value to be used to find the prefix object
- * @return the prefix object found, or null if nothing was found
- */
- getPrefixByValue(value) {
- return this.byValue_[value];
- }
-} // end PrefixTablesFactory class
-
-// Create a singleton instance and (to preserve the existing API) an object that
-// provides that instance via getInstance().
-exports.PrefixTablesFactory = PrefixTablesFactory;
-var prefixTablesInstance = new PrefixTablesFactory();
-const PrefixTables = exports.PrefixTables = {
- getInstance: function () {
- return prefixTablesInstance;
- }
-};
-
-
-},{}],67:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = void 0;
-/*
- * This class manages the special functions used by some units.
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- *
- */
-
-class UcumFunctions {
- /**
- * Constructor
- *
- * Creates the singleton object that contains the list of functions used
- * to convert special units.
- */
- constructor() {
- // Create the hash containing the function pairs
- this.funcs = {};
-
- // Celsius - convert to Celsius from kelvin and from Celsius to kelvin
- // where kelvin is the base unit for temperature
- this.funcs['cel'] = {
- cnvTo: function (x) {
- return x - 273.15;
- },
- cnvFrom: function (x) {
- return x + 273.15;
- }
- };
-
- // Fahrenheit - convert to Fahrenheit from kelvin and from Fahrenheit to
- // kelvin - which is the base unit for temperature
- this.funcs['degf'] = {
- cnvTo: function (x) {
- return x - 459.67;
- },
- cnvFrom: function (x) {
- return x + 459.67;
- }
- };
-
- // Reaumur - convert between Reaumur and Kelvin. Because of the way the
- // calling code in the Units class is set up (in the convertFrom method),
- // what is given here as the convertTo function is actually the convert
- // from method and vice versa.
- //this.funcs['degre'] = {cnvTo : function(x){return x + 273.15;},
- // cnvFrom : function(x){return x - 273.15;}};
- this.funcs['degre'] = {
- cnvTo: function (x) {
- return x - 273.15;
- },
- cnvFrom: function (x) {
- return x + 273.15;
- }
- };
-
- // pH - convert to pH from moles per liter and from moles per liter to pH
- // where a mole is an amount of a substance (a count of particles)
- this.funcs['ph'] = {
- cnvTo: function (x) {
- return -Math.log(x) / Math.LN10;
- },
- cnvFrom: function (x) {
- return Math.pow(10, -x);
- }
- };
-
- // ln - natural logarithm (base e 2.71828) - apply (cnvTo) and invert (cnvFrom)
- // and 2ln - two times the natural logarithm
- this.funcs['ln'] = {
- cnvTo: function (x) {
- return Math.log(x);
- },
- cnvFrom: function (x) {
- return Math.exp(x);
- }
- };
- this.funcs['2ln'] = {
- cnvTo: function (x) {
- return 2 * Math.log(x);
- },
- cnvFrom: function (x) {
- return Math.exp(x / 2);
- }
- };
-
- // lg - the decadic logarithm (base 10)
- this.funcs['lg'] = {
- cnvTo: function (x) {
- return Math.log(x) / Math.LN10;
- },
- cnvFrom: function (x) {
- return Math.pow(10, x);
- }
- };
- this.funcs['10lg'] = {
- cnvTo: function (x) {
- return 10 * Math.log(x) / Math.LN10;
- },
- cnvFrom: function (x) {
- return Math.pow(10, x / 10);
- }
- };
- this.funcs['20lg'] = {
- cnvTo: function (x) {
- return 20 * Math.log(x) / Math.LN10;
- },
- cnvFrom: function (x) {
- return Math.pow(10, x / 20);
- }
- };
- // The plain text ucum units file uses '2lg'
- this.funcs['2lg'] = {
- cnvTo: function (x) {
- return 2 * Math.log(x) / Math.LN10;
- },
- cnvFrom: function (x) {
- return Math.pow(10, x / 2);
- }
- };
- // The xml essence ucum file uses lgTimes2
- this.funcs['lgtimes2'] = this.funcs['2lg'];
-
- // ld - dual logarithm (base 2)
- this.funcs['ld'] = {
- cnvTo: function (x) {
- return Math.log(x) / Math.LN2;
- },
- cnvFrom: function (x) {
- return Math.pow(2, x);
- }
- };
-
- // tan - tangent
- this.funcs['100tan'] = {
- cnvTo: function (x) {
- return Math.tan(x) * 100;
- },
- cnvFrom: function (x) {
- return Math.atan(x / 100);
- }
- };
- // the xml essence ucum file uses both 100tan and tanTimes100
- this.funcs['tanTimes100'] = this.funcs['100tan'];
-
- // sqrt - square root
- this.funcs['sqrt'] = {
- cnvTo: function (x) {
- return Math.sqrt(x);
- },
- cnvFrom: function (x) {
- return x * x;
- }
- };
-
- // inv - inverse
- this.funcs['inv'] = {
- cnvTo: function (x) {
- return 1.0 / x;
- },
- cnvFrom: function (x) {
- return 1.0 / x;
- }
- };
-
- // homeopathic potency functions
- this.funcs['hpX'] = {
- cnvTo: function (x) {
- return -this.funcs['lg'](x);
- },
- cnvFrom: function (x) {
- return Math.pow(10, -x);
- }
- };
- this.funcs['hpC'] = {
- cnvTo: function (x) {
- return -this.func['ln'](x) / this.funcs['ln'](100);
- },
- cnvFrom: function (x) {
- return Math.pow(100, -x);
- }
- };
- this.funcs['hpM'] = {
- cnvTo: function (x) {
- return -this.funcs['ln'](x) / this.funcs['ln'](1000);
- },
- cnvFrom: function (x) {
- return Math.pow(1000, -x);
- }
- };
- this.funcs['hpQ'] = {
- cnvTo: function (x) {
- return -this.funcs['ln'](x) / this.funcs['ln'](50000);
- },
- cnvFrom: function (x) {
- return Math.pow(50000, -x);
- }
- };
- } // end of constructor
-
- /**
- * Returns the function with the name specified
- *
- * @param fname name of the function to be returned
- * @return the function with the specified name
- * @throws an error message if the function is not found
- */
- forName(fname) {
- fname = fname.toLowerCase();
- let f = this.funcs[fname];
- if (f === null) throw new Error(`Requested function ${fname} is not defined`);
- return f;
- }
-
- /**
- * Returns a flag indicating whether or not the function has been
- * defined.
- *
- * @param fname name of the function in question
- * @return true if it has been defined; false if not
- */
- isDefined(fname) {
- fname = fname.toLowerCase();
- return this.funcs[fname] !== null;
- }
-} // end of UcumFunctions class
-var _default = exports.default = new UcumFunctions(); // one singleton instance
-
-
-},{}],68:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.getSynonyms = getSynonyms;
-exports.isIntegerUnit = isIntegerUnit;
-exports.isNumericString = isNumericString;
-/**
- * Internal utilities used by multiple UCUM classes. For example,
- * isNumericString is used by both the UnitString and UcumLhcUtils
- * classes. If it's in the UnitString class the UcumLhcUtils class
- * needs to require the UnitString class. But the checkSynonyms
- * class is used by the UnitString class - but was in the UcumLhcUtils
- * class. Requiring the UcumLhcUtils class from the UnitString class
- * made everything break (cyclical requires).
- *
- * So now they're here.
- */
-
-/**
- * This module implements internal ucum utilities.
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- *
- */
-
-var UnitTables = require('./unitTables.js').UnitTables;
-
-/**
- * This function tests a string to see if it contains only numbers (digits,
- * a period, leading - or +). This code was taken from a stackoverflow
- * solution:
- * https://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number/42356340#42356340
- *
- * @params theString
- * @returns true if the string contains only numbers; false otherwise
- */
-function isNumericString(theString) {
- let num = "" + theString; //coerce num to be a string
- return !isNaN(num) && !isNaN(parseFloat(num));
-} // end isNumericString
-
-/**
- * Checks whether a string qualifies as an integer unit. Section 2.2.8 ("integer
- * numbers", says, "A positive integer number may appear in place of a simple
- * unit symbol. Only a pure string of decimal digits (‘0’–‘9’) is
- * interpreted as a number."
- * Note: This leaves open the question of whether "0" is a valid unit, since
- * it is positive, but you can't measure anything in units of zero.
- * @param str the string to check
- */
-function isIntegerUnit(str) {
- return /^\d+$/.test(str);
-}
-
-/**
- * This method accepts a term and looks for units that include it as
- * a synonym - or that include the term in its name.
- *
- * @param theSyn the term to search for. This is assumed to be
- * a string and not undefined. The calling method should do any
- * necessary checking before calling this.
- * @returns a hash with up to three elements:
- * 'status' contains the status of the request, which can be 'error',
- * 'failed' or succeeded';
- * 'msg' which contains a message for an error or if no units were found; and
- * 'units' which is an array that contains one array for each unit found:
- * the unit's csCode_, the unit's name_, and the unit's guidance_
- *
- */
-function getSynonyms(theSyn) {
- let retObj = {};
- let utab = UnitTables.getInstance();
- let resp = {};
- resp = utab.getUnitBySynonym(theSyn);
-
- // If we didn't get any units, transfer the status and message
- if (!resp['units']) {
- retObj['status'] = resp['status'];
- retObj['msg'] = resp['msg'];
- } else {
- retObj['status'] = 'succeeded';
- let aLen = resp['units'].length;
- retObj['units'] = [];
- for (let a = 0; a < aLen; a++) {
- let theUnit = resp['units'][a];
- retObj['units'][a] = {
- 'code': theUnit.csCode_,
- 'name': theUnit.name_,
- 'guidance': theUnit.guidance_
- };
- } // end do for all units returned
- } // end if we got a units list
- return retObj;
-} // end getSynonyms
-
-
-},{"./unitTables.js":74}],69:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.ucumJsonDefs = exports.UcumJsonDefs = void 0;
-/**
- * This class handles opening, reading and loading the JSON file of ucum
- * definitions (prefixes, base units, and unit atoms).
- *
- * @author Lee Mericle
- *
- */
-
-var Pfx = require("./prefix.js");
-var PfxT = require("./prefixTables.js");
-var Un = require("./unit.js");
-var Utab = require('./unitTables.js');
-var unpackArray = require('./jsonArrayPack.js').unpackArray;
-class UcumJsonDefs {
- /**
- * This method loads the JSON prefix and unit objects into the prefix and
- * unit tables.
- *
- * @returns nothing
- */
- loadJsonDefs() {
- // requiring the file will take care of opening it for use
- const jsonDefs = require('../data/ucumDefs.min.json');
- jsonDefs.prefixes = unpackArray(jsonDefs.prefixes);
- jsonDefs.units = unpackArray(jsonDefs.units);
- if (Utab.UnitTables.getInstance().unitsCount() === 0) {
- let pTab = PfxT.PrefixTables.getInstance();
- let prefixes = jsonDefs["prefixes"];
- let plen = prefixes.length;
- for (let p = 0; p < plen; p++) {
- let newPref = new Pfx.Prefix(prefixes[p]);
- pTab.add(newPref);
- }
- let uTab = Utab.UnitTables.getInstance();
- let units = jsonDefs["units"];
- let ulen = units.length;
- for (let u = 0; u < ulen; u++) {
- let newUnit = new Un.Unit(units[u]);
- uTab.addUnit(newUnit);
- }
- } // end if the data has not already been loaded
- } // end loadJsonDefs
-} // end UcumJsonDefs class
-exports.UcumJsonDefs = UcumJsonDefs;
-var ucumJsonDefs = exports.ucumJsonDefs = new UcumJsonDefs();
-
-
-},{"../data/ucumDefs.min.json":61,"./jsonArrayPack.js":64,"./prefix.js":65,"./prefixTables.js":66,"./unit.js":72,"./unitTables.js":74}],70:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.UcumLhcUtils = void 0;
-var _ucumJsonDefs = require("./ucumJsonDefs.js");
-var intUtils_ = _interopRequireWildcard(require("./ucumInternalUtils.js"));
-function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
-/**
- * This class provides a single point of access to the LHC UCUM utilities
- *
- * @author Lee Mericle
- *
- */
-var Ucum = require('./config.js').Ucum;
-var UnitTables = require('./unitTables.js').UnitTables;
-var UnitString = require('./unitString.js').UnitString;
-/**
- * UCUM external utilities class
- */
-class UcumLhcUtils {
- /**
- * Constructor. This loads the json prefix and unit definitions if
- * they haven't been loaded already and creates itself as a singleton object.
- *
- */
- constructor() {
- if (UnitTables.getInstance().unitsCount() === 0) {
- // Load the prefix and unit objects
- _ucumJsonDefs.ucumJsonDefs.loadJsonDefs();
- }
-
- // Get the UnitString parser that will be used with this instance
- // of the LHC Utilities
- this.uStrParser_ = UnitString.getInstance();
-
- // Get a copy of the mass dimension index.
- this.massDimIndex_ = UnitTables.getInstance().getMassDimensionIndex();
- } // end constructor
-
- /**
- * This method calls the useHTMLInMessages method on the UnitString
- * object. It should be called by web applications that use
- * these utilities.
- *
- * @param use flag indicating whether or not to use the braces message;
- * defaults to true
- */
- useHTMLInMessages(use) {
- if (use === undefined) use = true;
- this.uStrParser_.useHTMLInMessages(use);
- }
-
- /**
- * This method calls the useBraceMsgForEachString method on the UnitString
- * object. It should be called by web applications where unit
- * strings are validated individually (as opposed to validating a whole
- * file of unit strings).
- *
- * @param use flag indicating whether or not to use the braces message;
- * defaults to true
- */
- useBraceMsgForEachString(use) {
- if (use === undefined) use = true;
- this.uStrParser_.useBraceMsgForEachString(use);
- }
-
- /**
- * This method validates a unit string. It first checks to see if the
- * string passed in is a unit code that is found in the unit codes table.
- * If it is not found it parses the string to see if it resolves to a
- * valid unit string.
- *
- * If a valid unit cannot be found, the string is tested for some common
- * errors, such as missing brackets or a missing multiplication operator.
- * If found, the error is reported in the messages array that is returned.
- *
- * If a valid unit cannot be found and an error cannot be discerned, this
- * may return, if requested, a list of suggested units in the messages
- * array that is returned. Suggestions are based on matching the expression
- * with unit names and synonyms.
- *
- * @param uStr the string to be validated
- * @param suggest a boolean to indicate whether or not suggestions are
- * requested for a string that cannot be resolved to a valid unit;
- * true indicates suggestions are wanted; false indicates they are not,
- * and is the default if the parameter is not specified;
- * @param valConv a string indicating if this validation request was initiated
- * by a validation task ('validate') or a conversion task ('convert'),
- * used only for the demo code, and the default is 'Validator' if the
- * parameter is not specified;
- * @returns an object with five properties:
- * 'status' will be 'valid' (the uStr is a valid UCUM code), 'invalid'
- * (the uStr is not a valid UCUM code, and substitutions or
- * suggestions may or may not be returned, depending on what was
- * requested and found); or 'error' (an input or programming error
- * occurred);
- * 'ucumCode' the valid ucum code, which may differ from what was passed
- * in (e.g., if 'Gauss' is passed in, this will contain 'G') OR null if
- * the string was flagged as invalid or an error occurred;
- * 'msg' is an array of one or more messages, if the string is invalid or
- * an error occurred, indicating the problem, or an explanation of a
- * substitution such as the substitution of 'G' for 'Gauss', or
- * an empty array if no messages were generated;
- * 'unit' which is null if no unit is found, or a hash for a unit found:
- * 'code' is the unit's ucum code (G in the above example;
- * 'name' is the unit's name (Gauss in the above example); and
- * 'guidance' is the unit's guidance/description data; and
- * 'suggestions' if suggestions were requested and found, this is an array
- * of one or more hash objects. Each hash contains three elements:
- * 'msg' which is a message indicating what part of the uStr input
- * parameter the suggestions are for;
- * 'invalidUnit' which is the unit expression the suggestions are
- * for; and
- * 'units' which is an array of data for each suggested unit found.
- * Each array will contain the unit code, the unit name and the
- * unit guidance (if any).
- * If no suggestions were requested and found, this property is not
- * returned.
- */
- validateUnitString(uStr, suggest, valConv) {
- if (suggest === undefined) suggest = false;
- if (valConv === undefined) valConv = 'validate';
- let resp = this.getSpecifiedUnit(uStr, valConv, suggest);
- let theUnit = resp['unit'];
- let retObj = !theUnit ? {
- 'ucumCode': null
- } : {
- 'ucumCode': resp['origString'],
- 'unit': {
- 'code': theUnit.csCode_,
- 'name': theUnit.name_,
- 'guidance': theUnit.guidance_
- }
- };
- retObj.status = resp.status;
- if (resp['suggestions']) {
- retObj['suggestions'] = resp['suggestions'];
- }
- retObj['msg'] = resp['retMsg'];
- return retObj;
- } // end validateUnitString
-
- // Note that below when the value of ConversionType is mol|mass, it refers to
- // either a conversion from mol to mass or from mass to mol.
- /**
- * @typedef {
- * 'normal',
- * 'mol|mass',
- * 'eq|mass',
- * 'eq|mol',
- * 'eq|mol|mass'
- * } ConversionType
- */
-
- /**
- * Detects the type of conversion between two units.
- *
- * @param {Object} fromUnit - The unit to convert from.
- * @param {Object} toUnit - The unit to convert to.
- * @returns {ConversionType} conversionType - The type of conversion as a string.
- */
- detectConversionType(fromUnit, toUnit) {
- /** @type {ConversionType} */
- let conversionType;
- if (fromUnit.moleExp_ == toUnit.moleExp_ && fromUnit.equivalentExp_ == toUnit.equivalentExp_) {
- // Since the powers of the equivalents and mole in the units are the same in both
- // units, no conversion is going to happen between mass, mol, and eq.
- // There is the possibility that someone is trying to convert 'g' to 'g2',
- // but we will handle that as the "normal" case (and later find it invalid).
- conversionType = 'normal';
- } else if (fromUnit.equivalentExp_ == toUnit.equivalentExp_) {
- // In this case, the units have the same power of equivalents, so (because
- // it is not the first case) the units have different powers of mol and mass,
- // so this must be a conversion between mol and mass.
- conversionType = 'mol|mass';
- } else if (fromUnit.moleExp_ == toUnit.moleExp_) {
- // In this case, the units have the same power of mol, so (because
- // it is not the first case) the units have different powers of equivalents and mass,
- // so this must be a conversion between equivalents and mass.
- conversionType = 'eq|mass';
- } else if (fromUnit.dim_.getElementAt(this.massDimIndex_) == toUnit.dim_.getElementAt(this.massDimIndex_)) {
- // In this case, the units have the same power of mass, so (because
- // it is not the first case) the units have different powers of equivalents and mol,
- // so this must be a conversion between equivalents and moles.
- conversionType = 'eq|mol';
- } else {
- // In this case, the units have different powers of mass, mol, and
- // equivalents, so there is a conversion between mass, mol, and
- // equivalents.
- conversionType = 'eq|mol|mass';
- }
- return conversionType;
- } // end detectConversionType
-
- /**
- * @typedef {{
- * status: 'succeeded' | 'failed' | 'error',
- * toVal: number | null,
- * msg: string[],
- * suggestions: {
- * from: {
- * msg: string,
- * invalidUnit: string,
- * units: string[]
- * },
- * to: {
- * msg: string,
- * invalidUnit: string,
- * units: string[]
- * }
- * },
- * fromUnit: string,
- * toUnit: string
- * }} ConvertUnitResult
- */
-
- /**
- * This method converts one unit to another
- *
- * @param {string} fromUnitCode - the unit code/expression/string of the unit to be converted
- * @param {number | string} fromVal - the number of "from" units to be converted to "to" units
- * @param {string} toUnitCode - the unit code/expression/string of the unit that the from field is to be converted to
- * @param {{
- * suggest?: boolean,
- * molecularWeight?: number
- * charge?: number
- * }} options
- * - suggest: a boolean to indicate whether or not suggestions are requested for a string that cannot be resolved to a valid unit;
- * true indicates suggestions are wanted; false indicates they are not, and is the default if the parameter is not specified;
- * - molecularWeight: the molecular weight of the substance in question when a conversion is being requested from mass to moles and vice versa.
- * This is required when one of the units represents a value in moles. It is ignored if neither unit includes a measurement in moles.
- * - charge: the absolute value of the charge of the substance in question when a conversion is being requested from mass/moles to
- * equivalents and vice versa. It is required when one of the units represents a value in equivalents and the other in mass or moles.
- * It is ignored if neither unit includes an equivalent unit.
- * @returns {ConvertUnitResult}
- * - a hash with six elements:
- * - 'status' that will be: 'succeeded' if the conversion was successfully
- * calculated; 'failed' if the conversion could not be made, e.g., if
- * the units are not commensurable; or 'error' if an error occurred;
- * - 'toVal' the numeric value indicating the conversion amount, or null
- * if the conversion failed (e.g., if the units are not commensurable);
- * - 'msg' is an array message, if the string is invalid or an error occurred,
- * indicating the problem, or an explanation of a substitution such as
- * the substitution of 'G' for 'Gauss', or an empty array if no
- * messages were generated;
- * - 'suggestions' if suggestions were requested and found, this is a hash
- * that contains at most two elements:
- * - 'from' which, if the fromUnitCode input parameter or one or more of
- * its components could not be found, is an array one or more hash
- * objects. Each hash contains three elements:
- * - 'msg' which is a message indicating what unit expression the
- * suggestions are for;
- * - 'invalidUnit' which is the unit expression the suggestions
- * are for; and
- * - 'units' which is an array of data for each suggested unit found.
- * Each array will contain the unit code, the unit name and the
- * unit guidance (if any).
- * If no suggestions were found for the fromUnitCode this element
- * will not be included.
- * - 'to' which, if the "to" unit expression or one or more of its
- * components could not be found, is an array one or more hash objects. Each hash
- * contains three elements:
- * - 'msg' which is a message indicating what toUnitCode input
- * parameter the suggestions are for;
- * - 'invalidUnit' which is the unit expression the suggestions
- * are for; and
- * - 'units' which is an array of data for each suggested unit found.
- * Each array will contain the unit code, the unit name and the
- * unit guidance (if any).
- * If no suggestions were found for the toUnitCode this element
- * will not be included.
- * No 'suggestions' element will be included in the returned hash
- * object if none were found, whether or not they were requested.
- * - 'fromUnit' the unit object for the fromUnitCode passed in; returned
- * in case it's needed for additional data from the object; and
- * - 'toUnit' the unit object for the toUnitCode passed in; returned
- * in case it's needed for additional data from the object.
- */
- convertUnitTo(fromUnitCode, fromVal, toUnitCode, options = {}) {
- let {
- suggest = false,
- molecularWeight = null,
- charge = null
- } = options;
-
- /** @type {ConvertUnitResult} */
- let returnObj = {
- 'status': 'failed',
- 'toVal': null,
- 'msg': []
- };
- if (fromUnitCode) {
- fromUnitCode = fromUnitCode.trim();
- }
- if (!fromUnitCode || fromUnitCode == '') {
- returnObj['status'] = 'error';
- returnObj['msg'].push('No "from" unit expression specified.');
- }
- this._checkFromVal(fromVal, returnObj);
- if (toUnitCode) {
- toUnitCode = toUnitCode.trim();
- }
- if (!toUnitCode || toUnitCode == '') {
- returnObj['status'] = 'error';
- returnObj['msg'].push('No "to" unit expression specified.');
- }
- if (returnObj['status'] !== 'error') {
- let fromUnit = null;
- let parseResp = this.getSpecifiedUnit(fromUnitCode, 'convert', suggest);
- fromUnit = parseResp['unit'];
- if (parseResp['retMsg']) returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']);
- if (parseResp['suggestions']) {
- returnObj['suggestions'] = {};
- returnObj['suggestions']['from'] = parseResp['suggestions'];
- }
- if (!fromUnit) {
- returnObj['msg'].push(`Unable to find a unit for ${fromUnitCode}, ` + `so no conversion could be performed.`);
- }
- let toUnit = null;
- parseResp = this.getSpecifiedUnit(toUnitCode, 'convert', suggest);
- toUnit = parseResp['unit'];
- if (parseResp['retMsg']) returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']);
- if (parseResp['suggestions']) {
- if (!returnObj['suggestions']) returnObj['suggestions'] = {};
- returnObj['suggestions']['to'] = parseResp['suggestions'];
- }
- if (!toUnit) {
- returnObj['msg'].push(`Unable to find a unit for ${toUnitCode}, ` + `so no conversion could be performed.`);
- }
- if (fromUnit && toUnit) {
- const convertType = this.detectConversionType(fromUnit, toUnit);
- const msgCountBeforeConvert = returnObj['msg'].length;
- switch (convertType) {
- case 'normal':
- try {
- returnObj['toVal'] = toUnit.convertFrom(fromVal, fromUnit);
- } catch (err) {
- returnObj['msg'].push(err.message);
- }
- break;
- case 'mol|mass':
- if (!fromUnit.isMolMassCommensurable(toUnit)) {
- returnObj['msg'].push(`Sorry. ${fromUnitCode} cannot be ` + `converted to ${toUnitCode}.`);
- break;
- }
- if (!molecularWeight) {
- returnObj['msg'].push(Ucum.needMoleWeightMsg_);
- break;
- }
- returnObj['toVal'] = fromUnit.convertMolMass(fromVal, toUnit, molecularWeight);
- break;
- case 'eq|mass':
- if (!fromUnit.isEqMassCommensurable(toUnit)) {
- returnObj['msg'].push(`Sorry. ${fromUnitCode} cannot be ` + `converted to ${toUnitCode}.`);
- break;
- }
- if (!molecularWeight) {
- returnObj['msg'].push(Ucum.needEqWeightMsg_);
- }
- if (!charge) {
- returnObj['msg'].push(Ucum.needEqChargeMsg_);
- }
- if (!returnObj['msg'].length) {
- returnObj['toVal'] = fromUnit.convertEqMass(fromVal, toUnit, molecularWeight, charge);
- }
- break;
- case 'eq|mol':
- if (!fromUnit.isEqMolCommensurable(toUnit)) {
- returnObj['msg'].push(`Sorry. ${fromUnitCode} cannot be ` + `converted to ${toUnitCode}.`);
- break;
- }
- if (!charge) {
- returnObj['msg'].push(Ucum.needEqChargeMsg_);
- break;
- }
- returnObj['toVal'] = fromUnit.convertEqMol(fromVal, toUnit, charge);
- break;
- case 'eq|mol|mass':
- if (!fromUnit.isEqMolMassCommensurable(toUnit)) {
- returnObj['msg'].push(`Sorry. ${fromUnitCode} cannot be ` + `converted to ${toUnitCode}.`);
- break;
- }
- if (!molecularWeight) {
- returnObj['msg'].push(Ucum.needEqWeightMsg_);
- }
- if (!charge) {
- returnObj['msg'].push(Ucum.needEqChargeMsg_);
- }
- if (!returnObj['msg'].length) {
- returnObj['toVal'] = fromUnit.convertEqMolMass(fromVal, toUnit, molecularWeight, charge);
- }
- break;
- default:
- returnObj['msg'].push("Unknown conversion type. No conversion was attempted.");
- }
- if (returnObj['msg'].length > msgCountBeforeConvert) {
- // If one or more failure messages are pushed into returnObj['msg']
- // in the switch statement, mark the status as 'failed'.
- returnObj['status'] = 'failed';
- } else {
- // Set the return object to show success.
- returnObj['status'] = 'succeeded';
- returnObj['fromUnit'] = fromUnit;
- returnObj['toUnit'] = toUnit;
- }
- } // end if we have the from and to units
- }
- return returnObj;
- } // end convertUnitTo
-
- /**
- * Converts the given unit string into its base units, their exponents, and
- * a magnitude, and returns that data.
- * @param fromUnit the unit string to be converted to base units information
- * @param fromVal the number of "from" units to be converted
- * @returns an object with the properties:
- * 'status' indicates whether the result succeeded. The value will be one of:
- * 'succeeded': the conversion was successfully calculated (which can be
- * true even if it was already in base units);
- * 'invalid': fromUnit is not a valid UCUM code;
- * 'failed': the conversion could not be made (e.g., if it is an "arbitrary" unit);
- * 'error': if an error occurred (an input or programming error)
- * 'msg': an array of messages (possibly empty) if the string is invalid or
- * an error occurred, indicating the problem, or a suggestion of a
- * substitution such as the substitution of 'G' for 'Gauss', or
- * an empty array if no messages were generated. There can also be a
- * message that is just informational or warning.
- * 'magnitude': the new value when fromVal units of fromUnits is expressed in the base units.
- * 'fromUnitIsSpecial': whether the input unit fromUnit is a "special unit"
- * as defined in UCUM. This means there is some function applied to convert
- * between fromUnit and the base units, so the returned magnitude is likely not
- * useful as a scale factor for other conversions (i.e., it only has validity
- * and usefulness for the input values that produced it).
- * 'unitToExp': a map of base units in fromUnit to their exponent
- */
- convertToBaseUnits(fromUnit, fromVal) {
- let retObj = {};
- this._checkFromVal(fromVal, retObj);
- if (!retObj.status) {
- // could be set to 'error' by _checkFromVal
- let inputUnitLookup = this.getSpecifiedUnit(fromUnit, 'validate');
- retObj = {
- status: inputUnitLookup.status == 'valid' ? 'succeeded' : inputUnitLookup.status
- };
- let unit = inputUnitLookup.unit;
- retObj.msg = inputUnitLookup.retMsg || [];
- if (!unit) {
- if (inputUnitLookup.retMsg?.length == 0) retObj.msg.push('Could not find unit information for ' + fromUnit);
- } else if (unit.isArbitrary_) {
- retObj.msg.push('Arbitrary units cannot be converted to base units or other units.');
- retObj.status = 'failed';
- } else if (retObj.status == 'succeeded') {
- let unitToExp = {};
- let dimVec = unit.dim_?.dimVec_;
- let baseUnitString = '1';
- if (dimVec) {
- let dimVecIndexToBaseUnit = UnitTables.getInstance().dimVecIndexToBaseUnit_;
- for (let i = 0, len = dimVec.length; i < len; ++i) {
- let exp = dimVec[i];
- if (exp) {
- unitToExp[dimVecIndexToBaseUnit[i]] = exp;
- baseUnitString += '.' + dimVecIndexToBaseUnit[i] + exp;
- }
- }
- }
-
- // The unit might have a conversion function, which has to be applied; we
- // cannot just assume unit_.magnitude_ is the magnitude in base units.
- let retUnitLookup = this.getSpecifiedUnit(baseUnitString, 'validate');
- // There should not be any error in retUnitLookup, unless there is a bug.
- let retUnit = retUnitLookup.unit;
- if (retUnitLookup.status !== 'valid') {
- retObj.msg.push('Unable construct base unit string; tried ' + baseUnitString);
- retObj.status = 'error';
- } else {
- try {
- retObj.magnitude = retUnit.convertFrom(fromVal, unit);
- } catch (e) {
- retObj.msg.push(e.toString());
- retObj.status = 'error';
- }
- if (retObj.status == 'succeeded') {
- retObj.unitToExp = unitToExp;
- retObj.fromUnitIsSpecial = unit.isSpecial_;
- }
- }
- }
- }
- return retObj;
- }
-
- /**
- * Checks the given value as to whether it is suitable as a "from" value in a
- * unit conversion. If it is not, the responseObj will have its status set
- * to 'error' and a message added.
- * @param fromVal The value to check
- * @param responseObj the object that will be updated if the value is not
- * usable.
- */
- _checkFromVal(fromVal, responseObj) {
- if (fromVal === null || isNaN(fromVal) || typeof fromVal !== 'number' && !intUtils_.isNumericString(fromVal)) {
- responseObj.status = 'error';
- if (!responseObj.msg) responseObj.msg = [];
- responseObj.msg.push('No "from" value, or an invalid "from" value, ' + 'was specified.');
- }
- }
-
- /**
- * This method accepts a term and looks for units that include it as
- * a synonym - or that include the term in its name.
- *
- * @param theSyn the term to search for
- * @returns a hash with up to three elements:
- * 'status' contains the status of the request, which can be 'error',
- * 'failed' or succeeded';
- * 'msg' which contains a message for an error or if no units were found; and
- * 'units' which is an array that contains one hash for each unit found:
- * 'code' is the unit's csCode_
- * 'name' is the unit's name_
- * 'guidance' is the unit's guidance_
- *
- */
- checkSynonyms(theSyn) {
- let retObj = {};
- if (theSyn === undefined || theSyn === null) {
- retObj['status'] = 'error';
- retObj['msg'] = 'No term specified for synonym search.';
- } else {
- retObj = intUtils_.getSynonyms(theSyn);
- } // end if a search synonym was supplied
-
- return retObj;
- } // end checkSynonyms
-
- /**
- * This method parses a unit string to get (or try to get) the unit
- * represented by the string. It returns an error message if no string was specified
- * or if any errors were encountered trying to get the unit.
- *
- * @param uName the expression/string representing the unit
- * @param valConv indicates what type of request this is for - a request to
- * validate (pass in 'validate') or a request to convert (pass in 'convert')
- * @param suggest a boolean to indicate whether or not suggestions are
- * requested for a string that cannot be resolved to a valid unit;
- * true indicates suggestions are wanted; false indicates they are not,
- * and is the default if the parameter is not specified;
- * @returns a hash containing:
- * 'status' will be 'valid' (uName is a valid UCUM code), 'invalid'
- * (the uStr is not a valid UCUM code, and substitutions or
- * suggestions may or may not be returned, depending on what was
- * requested and found); or 'error' (an input or programming error
- * occurred);
- * 'unit' the unit object (or null if there were problems creating the
- * unit);
- * 'origString' the possibly updated unit string passed in;
- * 'retMsg' an array of user messages (informational, error or warning) if
- * any were generated (IF any were generated, otherwise will be an
- * empty array); and
- * 'suggestions' is an array of 1 or more hash objects. Each hash
- * contains three elements:
- * 'msg' which is a message indicating what unit expression the
- * suggestions are for;
- * 'invalidUnit' which is the unit expression the suggestions are
- * for; and
- * 'units' which is an array of data for each suggested unit found.
- * Each array will contain the unit code, the unit name and the
- * unit guidance (if any).
- * The return hash will not contain a suggestions array if a valid unit
- * was found or if suggestions were not requested and found.
- */
- getSpecifiedUnit(uName, valConv, suggest) {
- if (suggest === undefined) suggest = false;
- let retObj = {};
- retObj['retMsg'] = [];
- if (!uName) {
- retObj['retMsg'].push('No unit string specified.');
- } else {
- let utab = UnitTables.getInstance();
- uName = uName.trim();
-
- // go ahead and just try using the name as the code. This may or may not
- // work, but if it does, it cuts out a lot of parsing.
- let theUnit = utab.getUnitByCode(uName);
-
- // If we found it, set the returned unit string to what was passed in;
- // otherwise try parsing as a unit string
- if (theUnit) {
- retObj['unit'] = theUnit;
- retObj['origString'] = uName;
- } else {
- try {
- let resp = this.uStrParser_.parseString(uName, valConv, suggest);
- retObj['unit'] = resp[0];
- retObj['origString'] = resp[1];
- if (resp[2]) retObj['retMsg'] = resp[2];
- retObj['suggestions'] = resp[3];
- } catch (err) {
- console.log(`Unit requested for unit string ${uName}.` + 'request unsuccessful; error thrown = ' + err.message);
- retObj['retMsg'].unshift(`${uName} is not a valid unit. ` + `${err.message}`);
- }
- } // end if the unit was not found as a unit name
- } // end if a unit expression was specified
-
- // Set the status field
- if (!retObj.unit) {
- // No unit was found; check whether origString has a value
- retObj.status = !retObj.origString ? 'error' : 'invalid';
- } else {
- // Check whether substitutions were made to the unit string in order to
- // find the unit
- retObj.status = retObj.origString === uName ? 'valid' : 'invalid';
- }
- return retObj;
- } // end getSpecifiedUnit
-
- /**
- * This method retrieves a list of units commensurable, i.e., that can be
- * converted from and to, a specified unit. Returns an error if the "from"
- * unit cannot be found. If necessary, you can filter the list of units by
- * specifying a list of unit categories that should be in the resulting list.
- *
- * @param {string} fromName - the name/unit string of the "from" unit
- * @param {string[] | null} [categoryList] - the list of unit categories;
- * this parameter is optional, defaults to null if not specified;
- * possible list values: 'Clinical', 'Nonclinical', 'Obsolete', 'Constant'
- * @returns an array containing two elements;
- * first element is the list of commensurable units if any were found;
- * second element is an error message if the "from" unit is not found
- */
- commensurablesList(fromName, categoryList = null) {
- let retMsg = [];
- let commUnits = null;
- let parseResp = this.getSpecifiedUnit(fromName, 'validate', false);
- let fromUnit = parseResp['unit'];
- if (parseResp['retMsg'].length > 0) retMsg = parseResp['retMsg'];
- if (!fromUnit) {
- retMsg.push(`Could not find unit ${fromName}.`);
- } else {
- let dimVec = null;
- let fromDim = fromUnit.getProperty('dim_');
- if (!fromDim) {
- retMsg.push('No commensurable units were found for ' + fromName);
- } else {
- try {
- dimVec = fromDim.getProperty('dimVec_');
- } catch (err) {
- retMsg.push(err.message);
- if (err.message === "Dimension does not have requested property(dimVec_)") dimVec = null;
- }
- if (dimVec) {
- let utab = UnitTables.getInstance();
- commUnits = utab.getUnitsByDimension(dimVec);
- if (categoryList) {
- commUnits = commUnits.filter(item => {
- return categoryList.indexOf(item.category_) !== -1;
- });
- }
- }
- } // end if the from unit has a dimension vector
- } // end if we found a "from" unit
- return [commUnits, retMsg];
- } // end commensurablesList
-} // end UcumLhcUtils class
-
-/**
- * This function exists ONLY until the original UcumLhcUtils constructor
- * is called for the first time. It's defined here in case getInstance
- * is called before the constructor. This calls the constructor.
- *
- * The constructor redefines the getInstance function to return the
- * singleton UcumLhcUtils object. This is based on the UnitTables singleton
- * implementation; see more detail in the UnitTables constructor description.
- *
- * NO LONGER TRUE - not implemented as a singleton. This method retained to
- * avoid problems with calls to it that exist throughout the code.
- *
- * @return the (formerly singleton) UcumLhcUtils object.
- */
-exports.UcumLhcUtils = UcumLhcUtils;
-UcumLhcUtils.getInstance = function () {
- return new UcumLhcUtils();
-};
-
-
-},{"./config.js":62,"./ucumInternalUtils.js":68,"./ucumJsonDefs.js":69,"./unitString.js":73,"./unitTables.js":74}],71:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.UnitTables = exports.UcumLhcUtils = exports.Ucum = void 0;
-/**
- * This exports definitions for ucum classes that need references to them
- * available to the demo code. The actual code will be in the ucumPkg
- * library found in the dist directory. This file provides the hooks to
- * those classes within the library.
- */
-
-var Ucum = exports.Ucum = require("./config.js").Ucum;
-var UcumLhcUtils = exports.UcumLhcUtils = require("./ucumLhcUtils.js").UcumLhcUtils;
-var UnitTables = exports.UnitTables = require("./unitTables.js").UnitTables;
-
-
-},{"./config.js":62,"./ucumLhcUtils.js":70,"./unitTables.js":74}],72:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.Unit = void 0;
-var _ucumFunctions = _interopRequireDefault(require("./ucumFunctions.js"));
-var intUtils_ = _interopRequireWildcard(require("./ucumInternalUtils.js"));
-function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
-function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
-/**
- * This class represents one unit of measure. It includes
- * functions to cover constructor, accessor, and assignment tasks as
- * well as operators to calculate multiplication, division and raising
- * to a power.
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- *
- */
-var Ucum = require('./config.js').Ucum;
-var Dimension = require('./dimension.js').Dimension;
-var UnitTables;
-var isInteger = require("is-integer");
-class Unit {
- /**
- * Constructor.
- *
- * @param attrs an optional parameter that may be:
- * a string, which is parsed by the unit parser, which creates
- * the unit from the parsed string; or
- * a hash containing all or some values for the attributes of
- * the unit, where the keys are the attribute names, without a
- * trailing underscore, e.g., name instead of name_; or
- * null, in which case an empty hash is created and used to
- * set the values forthe attributes.
- * If a hash (empty or not) is used, attributes for which no value
- * is specified are assigned a default value.
- *
- */
- constructor(attrs = {}) {
- // Process the attrs hash passed in, which may be empty.
- // Create and assign values (from the attrs hash or defaults) to all
- // attributes. From Class Declarations in Understanding ECMAScript,
- // https://leanpub.com/understandinges6/read/#leanpub-auto-class-declarations,
- // "Own properties, properties that occur on the instance rather than the
- // prototype, can only be created inside of a class constructor or method.
- // It's recommended to create all possible own properties inside of the
- // constructor function so there's a single place that's responsible for
- // all of them."
-
- /*
- * Flag indicating whether or not this is a base unit
- */
- this.isBase_ = attrs['isBase_'] || false;
-
- /*
- * The unit name, e.g., meter
- */
- this.name_ = attrs['name_'] || '';
-
- /*
- * The unit's case-sensitive code, e.g., m
- */
- this.csCode_ = attrs['csCode_'] || '';
-
- /*
- * The unit's case-insensitive code, e.g., M
- */
- this.ciCode_ = attrs['ciCode_'] || '';
-
- /*
- * The unit's property, e.g., length
- */
- this.property_ = attrs['property_'] || '';
-
- /*
- * The magnitude of the unit, e.g., 3600/3937 for a yard,
- * where a yard - 3600/3973 * m(eter). The Dimension
- * property specifies the meter - which is the unit on which
- * a yard is based, and this magnitude specifies how to figure
- * this unit based on the base unit.
- */
- this.magnitude_ = attrs['magnitude_'] || 1;
-
- /*
- * The Dimension object of the unit
- */
- if (attrs['dim_'] === undefined || attrs['dim_'] === null) {
- this.dim_ = new Dimension();
- }
- // When the unit data stored in json format is reloaded, the dimension data
- // is recognized as a a hash, not as a Dimension object.
- else if (attrs['dim_']['dimVec_'] !== undefined) {
- this.dim_ = new Dimension(attrs['dim_']['dimVec_']);
- } else if (attrs['dim_'] instanceof Dimension) {
- this.dim_ = attrs['dim_'];
- } else if (attrs['dim_'] instanceof Array || isInteger(attrs['dim_'])) {
- this.dim_ = new Dimension(attrs['dim_']);
- } else {
- this.dim_ = new Dimension();
- }
- /*
- * The print symbol of the unit, e.g., m
- */
- this.printSymbol_ = attrs['printSymbol_'] || null;
-
- /*
- * The class of the unit, where given, e.g., dimless
- */
- this.class_ = attrs['class_'] || null;
-
- /*
- * A flag indicating whether or not the unit is metric
- */
- this.isMetric_ = attrs['isMetric_'] || false;
-
- /*
- * The "variable" - which I think is used only for base units
- * The symbol for the variable as used in equations, e.g., s for distance
- */
- this.variable_ = attrs['variable_'] || null; // comes from 'dim' in XML
-
- /*
- * The conversion function
- */
- this.cnv_ = attrs['cnv_'] || null;
-
- /*
- * The conversion prefix
- */
- this.cnvPfx_ = attrs['cnvPfx_'] || 1;
-
- /*
- * Flag indicating whether or not this is a "special" unit, i.e., is
- * constructed using a function specific to the measurement, e.g.,
- * fahrenheit and celsius
- */
- this.isSpecial_ = attrs['isSpecial_'] || false;
-
- /*
- * Flag indicating whether or not this is an arbitrary unit
- */
- this.isArbitrary_ = attrs['isArbitrary_'] || false;
-
- /*
- * Integer indicating what level of exponent applies to a mole-based portion
- * of the unit. So, for the unit "mol", this will be 1. For "mol2" this
- * will be 2. For "1/mol" this will be -1. Any unit that does not include
- * a mole will have a 0 in this field. This is used to determine
- * commensurability for mole<->mass conversions.
- */
- this.moleExp_ = attrs['moleExp_'] || 0;
-
- /**
- * Flag indicating whether or not this is a equivalent mole unit
- */
- this.equivalentExp_ = attrs['equivalentExp_'] || 0;
-
- /*
- * Added when added LOINC list of units
- * synonyms are used by the autocompleter to enhance lookup capabilities
- * while source says where the unit first shows up. Current sources are
- * UCUM - which are units from the https://ucum.org/ucum specification and LOINC -
- * which are units from the LOINC data.
- */
- this.synonyms_ = attrs['synonyms_'] || null;
- this.source_ = attrs['source_'] || null;
- this.loincProperty_ = attrs['loincProperty_'] || null;
- this.category_ = attrs['category_'] || null;
- this.guidance_ = attrs['guidance_'] || null;
-
- /*
- * Used to compute dimension; storing for now until I complete
- * unit definition parsing
- */
- /*
- * Case sensitive (cs) and case insensitive (ci) base unit strings,
- * includes exponent and prefix if applicable - specified in
- * nnn -- the unit part --
- * in the ucum-essence.xml file, and may be specified by a user
- * when requesting conversion or validation of a unit string. The
- * magnitude (base factor) is used with this to determine the new unit.
- * For example, a Newton (unit code N) is created from the string
- * kg.m/s2, and the value of 1 (base factor defined below). An hour
- * (unit code h) is created from the unit min (minute) with a value
- * of 60.
- */
- this.csUnitString_ = attrs['csUnitString_'] || null;
- this.ciUnitString_ = attrs['ciUnitString_'] || null;
-
- /*
- * String and numeric versions of factor applied to unit specified in
- * nnn -- the value part
- */
- this.baseFactorStr_ = attrs['baseFactorStr_'] || null;
- this.baseFactor_ = attrs['baseFactor_'] || null;
-
- /*
- * Flag used to indicate units where the definition process failed
- * when parsing units from the official units definitions file
- * (currently using the ucum-essence.xml file). We keep these
- * so that we can use them to at least validate them as valid
- * units, but we don't try to convert them. This is temporary
- * and only to account for instances where the code does not
- * take into account various special cases in the xml file.
- *
- * This is NOT used when trying to validate a unit string
- * submitted during a conversion or validation attempt.
- */
- this.defError_ = attrs['defError_'] || false;
- } // end constructor
-
- /**
- * Assign the unity (= dimensionless unit 1) to this unit.
- *
- * @return this unit
- */
- assignUnity() {
- this.name_ = "";
- this.magnitude_ = 1;
- if (!this.dim_) this.dim_ = new Dimension();
- this.dim_.assignZero();
- this.cnv_ = null;
- this.cnvPfx_ = 1;
- return this;
- } // end assignUnity
-
- /**
- * This assigns one or more values, as provided in the hash passed in,
- * to this unit.
- *
- * @param vals hash of values to be assigned to the attributes
- * specified by the key(s), which should be the attribute
- * name without the trailing underscore, e.g., name instead
- * of name_.
- * @return nothing
- */
- assignVals(vals) {
- for (let key in vals) {
- let uKey = key.charAt(key.length - 1) !== '_' ? key + '_' : key;
- if (this.hasOwnProperty(uKey)) this[uKey] = vals[key];else throw new Error(`Parameter error; ${key} is not a property of a Unit`);
- }
- } // end assignVals
-
- /**
- * This creates a clone of this unit.
- *
- * @return the clone
- */
- clone() {
- let retUnit = new Unit();
- Object.getOwnPropertyNames(this).forEach(val => {
- if (val === 'dim_') {
- if (this['dim_']) retUnit['dim_'] = this['dim_'].clone();else retUnit['dim_'] = null;
- } else retUnit[val] = this[val];
- });
- return retUnit;
- } // end clone
-
- /**
- * This assigns all properties of a unit passed to it to this unit.
- *
- * @param unit2 the unit whose properties are to be assigned to this one.
- * @return nothing; this unit is updated
- */
- assign(unit2) {
- Object.getOwnPropertyNames(unit2).forEach(val => {
- if (val === 'dim_') {
- if (unit2['dim_']) this['dim_'] = unit2['dim_'].clone();else this['dim_'] = null;
- } else {
- this[val] = unit2[val];
- }
- });
- } // end assign
-
- /**
- * This determines whether or not object properties of the unit
- * passed in are equal to the corresponding properties in this unit.
- * The following properties are the only ones checked:
- * magnitude_, dim_, cnv_ and cnvPfx_
- *
- * @param unit2 the unit whose properties are to be checked.
- * @return boolean indicating whether or not they match
- */
- equals(unit2) {
- return this.magnitude_ === unit2.magnitude_ && this.cnv_ === unit2.cnv_ && this.cnvPfx_ === unit2.cnvPfx_ && (this.dim_ === null && unit2.dim_ === null || this.dim_.equals(unit2.dim_));
- } // end equals
-
- /**
- * This method compares every attribute of two objects to determine
- * if they all match.
- *
- * @param unit2 the unit that is to be compared to this unit
- * @return boolean indicating whether or not every attribute matches
- */
- fullEquals(unit2) {
- let thisAttr = Object.keys(this).sort();
- let u2Attr = Object.keys(unit2).sort();
- let keyLen = thisAttr.length;
- let match = keyLen === u2Attr.length;
-
- // check each attribute. Dimension objects have to checked using
- // the equals function of the Dimension class.
- for (let k = 0; k < keyLen && match; k++) {
- if (thisAttr[k] === u2Attr[k]) {
- if (thisAttr[k] === 'dim_') match = this.dim_.equals(unit2.dim_);else match = this[thisAttr[k]] === unit2[thisAttr[k]];
- } else match = false;
- } // end do for each key and attribute
- return match;
- } // end of fullEquals
-
- /**
- * This returns the value of the property named by the parameter
- * passed in.
- *
- * @param propertyName name of the property to be returned, with
- * or without the trailing underscore.
- * @return the requested property, if found for this unit
- * @throws an error if the property is not found for this unit
- */
- getProperty(propertyName) {
- let uProp = propertyName.charAt(propertyName.length - 1) === '_' ? propertyName : propertyName + '_';
- return this[uProp];
- } // end getProperty
-
- /**
- * Takes a measurement consisting of a number of units and a unit and returns
- * the equivalent number of this unit. So, 15 mL would translate
- * to 1 tablespoon if this object is a tablespoon.
- *
- * Note that the number returned may not be what is normally expected.
- * For example, converting 10 Celsius units to Fahrenheit would "normally"
- * return a value of 50. But in this case you'll get back something like
- * 49.99999999999994.
- *
- * If either unit is an arbitrary unit an exception is raised.
- *
- * @param num the magnitude for the unit to be translated (e.g. 15 for 15 mL)
- * @param fromUnit the unit to be translated to one of this type (e.g. a mL unit)
- *
- * @return the number of converted units (e.g. 1 for 1 tablespoon)
- * @throws an error if the dimension of the fromUnit differs from this unit's
- * dimension
- */
- convertFrom(num, fromUnit) {
- let newNum = 0.0;
- if (this.isArbitrary_) throw new Error(`Attempt to convert to arbitrary unit "${this.csCode_}"`);
- if (fromUnit.isArbitrary_) throw new Error(`Attempt to convert arbitrary unit "${fromUnit.csCode_}"`);
-
- // reject request if both units have dimensions that are not equal
- if (fromUnit.dim_ && this.dim_ && !fromUnit.dim_.equals(this.dim_)) {
- // check first to see if a mole<->mass conversion is appropriate
- if (this.isMolMassCommensurable(fromUnit)) {
- throw new Error(Ucum.needMoleWeightMsg_);
- } else {
- throw new Error(`Sorry. ${fromUnit.csCode_} cannot be converted ` + `to ${this.csCode_}.`);
- }
- }
- // reject request if there is a "from" dimension but no "to" dimension
- if (fromUnit.dim_ && (!this.dim_ || this.dim_.isNull())) {
- throw new Error(`Sorry. ${fromUnit.csCode_} cannot be converted ` + `to ${this.csCode_}.`);
- }
-
- // reject request if there is a "to" dimension but no "from" dimension
- if (this.dim_ && (!fromUnit.dim_ || fromUnit.dim_.isNull())) {
- throw new Error(`Sorry. ${fromUnit.csCode_} cannot be converted ` + `to ${this.csCode_}.`);
- }
- let fromCnv = fromUnit.cnv_;
- let fromMag = fromUnit.magnitude_;
- let x;
- if (fromCnv != null) {
- // turn num * fromUnit.magnitude into its ratio scale equivalent,
- // e.g., convert Celsius to Kelvin
- let fromFunc = _ucumFunctions.default.forName(fromCnv);
- x = fromFunc.cnvFrom(num * fromUnit.cnvPfx_) * fromMag;
- //x = fromFunc.cnvFrom(num * fromMag) * fromUnit.cnvPfx_;
- } else {
- x = num * fromMag;
- }
- if (this.cnv_ != null) {
- // turn mag * origUnit on ratio scale into a non-ratio unit,
- // e.g. convert Kelvin to Fahrenheit
- let toFunc = _ucumFunctions.default.forName(this.cnv_);
- newNum = toFunc.cnvTo(x / this.magnitude_) / this.cnvPfx_;
- } else {
- newNum = x / this.magnitude_;
- }
- return newNum;
- } // end convertFrom
-
- /**
- * Takes a number and a target unit and returns the number for a measurement
- * of this unit that corresponds to the number of the target unit passed in.
- * So, 1 tablespoon (where this unit represents a tablespoon) would translate
- * to 15 mL.
- *
- * See the note on convertFrom about return values.
- *
- * @param mag the magnitude for this unit (e.g. 1 for 1 tablespoon)
- * @param toUnit the unit to which this unit is to be translated
- * (e.g. an mL unit)
- *
- * @return the converted number value (e.g. 15 mL)
- * @throws an error if the dimension of the toUnit differs from this unit's
- * dimension
- */
- convertTo(num, toUnit) {
- return toUnit.convertFrom(num, this);
- } // end convertTo
-
- /**
- * Takes a given number of this unit returns the number of this unit
- * if it is converted into a coherent unit. Does not change this unit.
- *
- * If this is a coherent unit already, just gives back the number
- * passed in.
- *
- * @param num the number for the coherent version of this unit
- * @return the number for the coherent version of this unit
- */
- convertCoherent(num) {
- // convert mag' * u' into canonical number * u on ratio scale
- if (this.cnv_ !== null) num = this.cnv_.f_from(num / this.cnvPfx_) * this.magnitude_;
- return num;
- } // end convertCoherent
-
- /**
- * Mutates this unit into a coherent unit and converts a given number of
- * units to the appropriate value for this unit as a coherent unit
- *
- * @param num the number for this unit before conversion
- * @return the number of this unit after conversion
- * @throws an error if the dimensions differ
- */
- mutateCoherent(num) {
- // convert mu' * u' into canonical mu * u on ratio scale
- num = this.convertCoherent(num);
-
- // mutate to coherent unit
- this.magnitude_ = 1;
- this.cnv_ = null;
- this.cnvPfx_ = 1;
- this.name_ = "";
-
- // build a name as a term of coherent base units
- // This is probably ALL WRONG and a HORRIBLE MISTAKE
- // but until we figure out what the heck the name being
- // built here really is, it will have to stay.
- for (let i = 0, max = Dimension.getMax(); i < max; i++) {
- let elem = this.dim_.getElementAt(i);
- let tabs = this._getUnitTables();
- let uA = tabs.getUnitsByDimension(new Dimension(i));
- if (uA == null) throw new Error(`Can't find base unit for dimension ${i}`);
- this.name_ = uA.name + elem;
- }
- return num;
- } // end mutateCoherent
-
- /**
- * This function converts between mol and mass (in either direction)
- * using the molecular weight of the substance. It assumes that the
- * isMolMassCommensurable" function has been called to check that the units are
- * commensurable.
- *
- * @param amt the quantity of this unit to be converted
- * @param toUnit the target/to unit for which the converted # is wanted
- * @param molecularWeight the molecular weight of the substance for which the
- * conversion is being made
- * @return the equivalent amount in toUnit
- */
- convertMolMass(amt, toUnit, molecularWeight) {
- // In the calculations below we are treating "molecularWeight" (measured in
- // a.m.u) as the molar weight (measured in g/mol). The values are the same,
- // though the units differ.
-
- // Determine the number of powers of mol we have to convert to mass.
- // Typically this will be just 1, or -1, but not necessarily. If it is a
- // negative number, then we are really converting mass to moles.
- const molPowersToConvert = this.moleExp_ - toUnit.moleExp_;
- // A simple mole unit has a magnitude of avogadro's number. Get that
- // number now (since not everyone agrees on what it is, and what is
- // being used in this system might change).
- let tabs = this._getUnitTables();
- let avoNum = tabs.getUnitByCode('mol').magnitude_;
- // For each molPowersToConvert, we need to multiply the mol unit by the
- // molar weight (g/mol) and divide by avoNum (1/mol) to get a weight per
- // molecule. (Note that the magnitude_ of each unit will contain factors of
- // avoNum, of which we are thus getting rid of some).
- let moleUnitFactor = Math.pow(molecularWeight / avoNum, molPowersToConvert);
- // The new value is proportional to this.magnitude_, amt, and
- // moleUnitFactor, and inversely proportional to toUnit_.magnitude.
- return this.magnitude_ / toUnit.magnitude_ * moleUnitFactor * amt;
- } // end convertMolMass
-
- /**
- * This function converts between equivalants and mass (in either direction)
- * using the charge of the substance. It assumes that the
- * isEqMassCommensurable" function has been called to check that the units are
- * commensurable.
- *
- * @param {number} amt - The amount of this unit to be converted.
- * @param {object} toUnit - The target/to unit for which the converted number is wanted.
- * @param {number} molecularWeight - The molecular weight of the substance for which the conversion is being made.
- * @param {number} charge - The absolute value of the charge of the substance for which the conversion is being made.
- * @returns {number} - The amount in the specified toUnit.
- */
- convertEqMass(amt, toUnit, molecularWeight, charge) {
- // Determine the number of powers of mass we have to convert to equivalents.
- // Typically this will be just 1, or -1, but not necessarily. If it is a
- // negative number, then we are converting in the opposite direciton.
- // Because the units are presumed commensurable, we can use the
- // equivalentExp_ instead of the mass dimension.
- const massPowersToConvert = toUnit.equivalentExp_ - this.equivalentExp_;
- // Calculate equivalent mass by dividing molecular weight by charge
- let equivalentMass = molecularWeight / charge;
- // Get Avogadro's number from the unit tables
- let avogadroNumber = this._getUnitTables().getUnitByCode('mol').magnitude_;
- // Calculate equivalents by dividing mass by equivalent mass, for each
- // power to be converted.
- let equivalents = this.magnitude_ * amt / Math.pow(equivalentMass, massPowersToConvert);
- // Calculate mole factor by dividing the magnitude of the equivalent unit by
- // Avogadro's number. toUnit may have a prefix (e.g. meq) and we need to adjust for that, for
- // each massPowersToConvert.
- let moleFactor = toUnit.magnitude_ / Math.pow(avogadroNumber, massPowersToConvert);
- // Adjust equivalents by dividing by the mole factor
- let adjustedEquivalents = equivalents / moleFactor;
- // Return the adjusted equivalents
- return adjustedEquivalents;
- } // end convertMassToEq
-
- /**
- * Converts a unit with eq/mol/mass to another unit with eq/mol/mass. It
- * assumes the units an commensurable, which can be checked via
- * isEqMolMassCommensurable. It also assumes that the powers of eq/mol/mass
- * are different between the two units; otherwise it would be more efficient
- * to call one of the other convert... functions.
- *
- * @param {number} amt - The amount of this unit to be converted.
- * @param {object} toUnit - The target/to unit for which the converted number is wanted.
- * @param {number} molecularWeight - The molecular weight of the substance for which the conversion is being made.
- * @param {number} charge - The absolute value of the charge of the substance for which the conversion is being made.
- * @returns {number} - The equivalent amount in the specified equivalent unit.
- */
- convertEqMolMass(amt, toUnit, molecularWeight, charge) {
- // Handle the equivalent differences. It important for the following
- // calculations (for consistency) that we consider the difference in
- // equivalent powers and not mol powers, so we are not calling
- // convertEqToMol, in case its implementation changes.
- // See convertEqToMol for details. One difference is that we do not scale
- // by magnitude_ until the end.
- const eqPowersToConvert = this.equivalentExp_ - toUnit.equivalentExp_;
- const molAmt = amt / Math.pow(charge, eqPowersToConvert);
- // Now for the mol/mass converstion part, we consider only the mass power
- // differences, and not the mol power differences (which were partially
- // handled in the eq/mol step above).
- // Again, see convertMolToMass for details on the calculations.
- const tabs = this._getUnitTables();
- const d = tabs.getMassDimensionIndex();
- const massPowersToConvert = this.dim_.getElementAt(d) - toUnit.dim_.getElementAt(d);
- const molPowersToConvert = -massPowersToConvert; // so the formulas follow convertMolToMass
- const avoNum = tabs.getUnitByCode('mol').magnitude_;
- let moleUnitFactor = Math.pow(molecularWeight / avoNum, molPowersToConvert);
- return this.magnitude_ / toUnit.magnitude_ * moleUnitFactor * molAmt;
- }
-
- /**
- * Checks if the given unit is an equivalent unit.
- *
- * Note: equivalent units are also be molar units, so a unit can return true for
- * both isEquivalentUnit and isMolarUnit.
- *
- * @returns {boolean} - Returns true if the unit is an equivalent unit, false otherwise.
- */
- isEquivalentUnit() {
- return this.equivalentExp_ !== 0;
- } // end isEquivalentUnit
-
- /**
- * Checks if the given unit is a molar unit.
- *
- * @returns {boolean} - Returns true if the unit is a molar unit, false otherwise.
- */
- isMolarUnit() {
- return this.moleExp_ !== 0;
- } // end isMolarUnit
-
- /**
- * This function converts between equivalants and moles (in either direction)
- * using the charge of the substance. It assumes that the
- * isEqMolCommensurable" function has been called to check that the units are
- * commensurable.
- * As with the other "convert" functions, it assumes the appropriate
- * "is...Commensurable" function has been called.
- *
- * @param {number} amt - The amount of this unit for which the conversion is being made.
- * @param {object} toUnit - The target unit for which the converted number is wanted.
- * @param {number} charge - The absolute value of the charge of the substance for which the conversion is being made.
- * @return {number} - The amount in molToUnit.
- */
- convertEqMol(amt, toUnit, charge) {
- // Determine the number of powers of eq we have to convert to mol.
- // Typically this will be just 1, or -1, but not necessarily. If it is a
- // negative number, then we are really converting mol to eq.
- const eqPowersToConvert = this.equivalentExp_ - toUnit.equivalentExp_;
-
- // A simple mole unit has a magnitude of avogadro's number.
- // So does 'eq' (equivalent) because in ucum it is defined as 1 mol, though
- // that does not account for the charge. Therefore, we don't need to
- // account for that factor in this conversion.
-
- // The conversion from equivalents to moles is based on the principle that
- // one equivalent is equal to 1/charge moles (per eqPowersToConvert).
- // The relative magnitude is accounted for via the current unit's magnitude
- // (this.magnitude_) and the target unit's magnitude (molToUnit.magnitude_)
- // For each eqPowersToConvert, we need to divide by the charge.
- return amt * (this.magnitude_ / toUnit.magnitude_) / Math.pow(charge, eqPowersToConvert);
- } // end convertEqMol
-
- /**
- * Mutates this unit into a unit on a ratio scale and converts a specified
- * number of units to an appropriate value for this converted unit
- *
- * @param num the number of this unit before it's converted
- * @return the magnitude of this unit after it's converted
- * @throw an error if the dimensions differ
- */
- mutateRatio(num) {
- if (this.cnv_ == null) return this.mutateCoherent(num);else return num;
- } // end mutateRatio
-
- /**
- * Multiplies this unit with a scalar. Special meaning for
- * special units so that (0.1*B) is 1 dB.
- *
- * This function DOES NOT modify this unit.
- *
- * @param s the value by which this unit is to be multiplied
- * @return a copy this unit multiplied by s
- * */
- multiplyThis(s) {
- let retUnit = this.clone();
- if (retUnit.cnv_ != null) retUnit.cnvPfx_ *= s;else retUnit.magnitude_ *= s;
- let mulVal = s.toString();
- retUnit.name_ = this._concatStrs(mulVal, '*', this.name_, '[', ']');
- retUnit.csCode_ = this._concatStrs(mulVal, '.', this.csCode_, '(', ')');
- retUnit.ciCode_ = this._concatStrs(mulVal, '.', this.ciCode_, '(', ')');
- retUnit.printSymbol_ = this._concatStrs(mulVal, '.', this.printSymbol_, '(', ')');
- return retUnit;
- } // end multiplyThis
-
- /**
- * Multiplies this unit with another unit. If one of the
- * units is a non-ratio unit the other must be dimensionless or
- * else an exception is thrown.
- *
- * This function does NOT modify this unit
- * @param unit2 the unit to be multiplied with this one
- * @return this unit after it is multiplied
- * @throws an error if one of the units is not on a ratio-scale
- * and the other is not dimensionless.
- */
- multiplyThese(unit2) {
- var retUnit = this.clone();
- if (retUnit.cnv_ != null) {
- if (unit2.cnv_ == null && (!unit2.dim_ || unit2.dim_.isZero())) retUnit.cnvPfx_ *= unit2.magnitude_;else throw new Error(`Attempt to multiply non-ratio unit ${retUnit.name_} ` + 'failed.');
- } // end if this unit has a conversion function
- else if (unit2.cnv_ != null) {
- if (!retUnit.dim_ || retUnit.dim_.isZero()) {
- retUnit.cnvPfx_ = unit2.cnvPfx_ * retUnit.magnitude_;
- retUnit.magnitude_ = unit2.magnitude_;
- retUnit.cnv_ = unit2.cnv_;
- } else throw new Error(`Attempt to multiply non-ratio unit ${unit2.name_}`);
- } // end if unit2 has a conversion function
-
- // else neither unit has a conversion function
- else {
- retUnit.magnitude_ *= unit2.magnitude_;
- } // end if unit2 does not have a conversion function
-
- // If this.dim_ isn't there, clone the dimension in unit2 - if dimVec_
- // is a dimension in unit2.dim_; else just transfer it to this dimension
- if (!retUnit.dim_ || retUnit.dim_ && !retUnit.dim_.dimVec_) {
- if (unit2.dim_) retUnit.dim_ = unit2.dim_.clone();else retUnit.dim_ = unit2.dim_;
- }
- // Else this.dim_ is there. If there is a dimension for unit2,
- // add it to this one.
- else if (unit2.dim_ && unit2.dim_ instanceof Dimension) {
- retUnit.dim_.add(unit2.dim_);
- }
-
- // Add the values of equivalentExp_ and moleExp for the two units
- retUnit.equivalentExp_ += unit2.equivalentExp_;
- retUnit.moleExp_ += unit2.moleExp_;
-
- // Concatenate the unit info (name, code, etc) for all cases
- // where the multiplication was performed (an error wasn't thrown)
- retUnit.name_ = this._concatStrs(retUnit.name_, '*', unit2.name_, '[', ']');
- retUnit.csCode_ = this._concatStrs(retUnit.csCode_, '.', unit2.csCode_, '(', ')');
- if (retUnit.ciCode_ && unit2.ciCode_) retUnit.ciCode_ = this._concatStrs(retUnit.ciCode_, '.', unit2.ciCode_, '(', ')');else if (unit2.ciCode_) retUnit.ciCode_ = unit2.ciCode_;
- retUnit.resetFieldsForDerivedUnit();
- if (retUnit.printSymbol_ && unit2.printSymbol_) retUnit.printSymbol_ = this._concatStrs(retUnit.printSymbol_, '.', unit2.printSymbol_, '(', ')');else if (unit2.printSymbol_) retUnit.printSymbol_ = unit2.printSymbol_;
-
- // A unit that has the arbitrary attribute taints any unit created from it
- // via an arithmetic operation. Taint accordingly
- // if (!retUnit.isMole_)
- // retUnit.isMole_ = unit2.isMole_ ;
- if (!retUnit.isArbitrary_) retUnit.isArbitrary_ = unit2.isArbitrary_;
-
- // Likewise for special units
- if (!retUnit.isSpecial_) retUnit.isSpecial_ = unit2.isSpecial_;
- return retUnit;
- } // end multiplyThese
-
- /**
- * Clears fields like isBase_, synonyms_, etc. when a unit has been cloned
- * from a known unit but it being used to construct a derived unit.
- */
- resetFieldsForDerivedUnit() {
- this.guidance_ = '';
- this.synonyms_ = null;
- this.isBase_ = false;
- }
-
- /**
- * Divides this unit by another unit. If this unit is not on a ratio
- * scale an exception is raised. Mutating to a ratio scale unit
- * is not possible for a unit, only for a measurement.
- *
- * This unit is NOT modified by this function.
- * @param unit2 the unit by which to divide this one
- * @return this unit after it is divided by unit2
- * @throws an error if either of the units is not on a ratio scale.
- * */
- divide(unit2) {
- var retUnit = this.clone();
- if (retUnit.cnv_ != null) throw new Error(`Attempt to divide non-ratio unit ${retUnit.name_}`);
- if (unit2.cnv_ != null) throw new Error(`Attempt to divide by non-ratio unit ${unit2.name_}`);
- if (retUnit.name_ && unit2.name_) retUnit.name_ = this._concatStrs(retUnit.name_, '/', unit2.name_, '[', ']');else if (unit2.name_) retUnit.name_ = unit2.invertString(unit2.name_);
- retUnit.csCode_ = this._concatStrs(retUnit.csCode_, '/', unit2.csCode_, '(', ')');
- if (retUnit.ciCode_ && unit2.ciCode_) retUnit.ciCode_ = this._concatStrs(retUnit.ciCode_, '/', unit2.ciCode_, '(', ')');else if (unit2.ciCode_) retUnit.ciCode_ = unit2.invertString(unit2.ciCode_);
- retUnit.resetFieldsForDerivedUnit();
- retUnit.magnitude_ /= unit2.magnitude_;
- if (retUnit.printSymbol_ && unit2.printSymbol_) retUnit.printSymbol_ = this._concatStrs(retUnit.printSymbol_, '/', unit2.printSymbol_, '(', ')');else if (unit2.printSymbol_) retUnit.printSymbol_ = unit2.invertString(unit2.printSymbol_);
-
- // Continue if unit2 has a dimension object.
- // If this object has a dimension object, subtract unit2's dim_ object from
- // this one. The sub method will take care of cases where the dimVec_ arrays
- // are missing on one or both dim_ objects.
- if (unit2.dim_) {
- if (retUnit.dim_) {
- if (retUnit.dim_.isNull()) retUnit.dim_.assignZero();
- retUnit.dim_ = retUnit.dim_.sub(unit2.dim_);
- } // end if this.dim_ exists
-
- // Else if this dim_ object is missing, clone unit2's dim_ object
- // and give the inverted clone to this unit.
- else retUnit.dim_ = unit2.dim_.clone().minus();
- } // end if unit2 has a dimension object
-
- // Update the mole exponent count by subtracting the count for unit2 from
- // the count for this unit.
- retUnit.moleExp_ -= unit2.moleExp_;
- // Also update the equivalent exponent.
- retUnit.equivalentExp_ -= unit2.equivalentExp_;
-
- // A unit that has the arbitrary attribute taints any unit created from
- // it via an arithmetic operation. Taint accordingly
- // if (!retUnit.isMole_)
- // retUnit.isMole_ = unit2.isMole_ ;
- if (!retUnit.isArbitrary_) retUnit.isArbitrary_ = unit2.isArbitrary_;
- return retUnit;
- } // end divide
-
- /**
- * This function is not actually used by the other code, except for some test
- * code, and might not be adequately tested.
- *
- * Invert this unit with respect to multiplication. If this unit is not
- * on a ratio scale an exception is thrown. Mutating to a ratio scale unit
- * is not possible for a unit, only for a measurement (the magnitude and
- * dimension).
- *
- * This unit is modified by this function.
- * @return this unit after being inverted
- * @throws and error if this unit is not on a ratio scale
- */
- invert() {
- var retUnit = this.clone();
- if (this.cnv_ != null) throw new Error(`Attempt to invert a non-ratio unit - ${this.name_}`);
- retUnit.name_ = this.invertString(this.name_);
- retUnit.magnitude_ = 1 / this.magnitude_;
- retUnit.dim_.minus();
-
- // Also update equivalentExp_ and moleExp
- retUnit.equivalentExp_ = -this.equivalentExp_;
- retUnit.moleExp_ = -this.moleExp_;
- return retUnit;
- } // end invert
-
- /**
- * Inverts a string, where the string is assumed to be a code or a name
- * of a division operation where the string is the divisor and the dividend
- * is blank.
- *
- * @param the string to be inverted
- * @return the inverted string
- */
- invertString(theString) {
- if (theString.length > 0) {
- // replace(' are intact. See LF-2830.
- let stringRep = theString.replace('/', "!").replace('.', '/').replace('= 0; u--) {
- let uChar = parseInt(un[u]);
- if (!isInteger(uChar)) {
- if (un[u] === '-' || un[u] === '+') {
- u--;
- }
- if (u < uLen - 1) {
- let exp = parseInt(un.substr(u));
- exp = Math.pow(exp, p);
- uArray[i] = un.substr(0, u) + exp.toString();
- u = -1;
- } else {
- uArray[i] += p.toString();
- u = -1;
- } // end if there are/aren't some numbers at the end
- u = -1;
- } // end if this character is not a number
- } // end searching backwards for start of exponent
- } // end if this element is not a number
- } // end if the current element is not an operator
- } // end do for each element of the units array
-
- // reassemble the updated units array to a string
- retUnit.csCode_ = uArray.join('');
- retUnit.magnitude_ = Math.pow(this.magnitude_, p);
- if (retUnit.dim_) {
- retUnit.dim_.mul(p);
- }
-
- // Also update equivalentExp_ and moleExp
- retUnit.equivalentExp_ *= p;
- retUnit.moleExp_ *= p;
- return retUnit;
- } // end power
-
- /*
- * This function tests this unit against the unit passed in to see if the
- * two are mole to mass commensurable. It assumes that one of the units
- * is a mole-based unit and the other is a mass-based unit. It also assumes
- * that the mole-based unit has a single mole unit in the numerator and that
- * the mass-based unit has a single mass unit in the numerator. It does NOT
- * check to validate those assumptions.
- *
- * The check is made by setting the dimension vector element corresponding
- * to the base mass unit (gram) in the mole unit, and then comparing the
- * two dimension vectors. If they match, the units are commensurable.
- * Otherwise they are not.
- *
- * @param unit2 the unit to be compared to this one
- * @returns boolean indicating commensurability
- */
- isMolMassCommensurable(unit2) {
- let tabs = this._getUnitTables();
- let d = tabs.getMassDimensionIndex();
- // Add the moleExp_ values to the mass values in the dimension vectors
- // of each unit, and then compare them.
- const unit1Dim = this.dim_.clone();
- unit1Dim.setElementAt(d, unit1Dim.getElementAt(d) + this.moleExp_);
- const unit2Dim = unit2.dim_.clone();
- unit2Dim.setElementAt(d, unit2Dim.getElementAt(d) + unit2.moleExp_);
- return unit1Dim.equals(unit2Dim);
- }
-
- /**
- * This function tests this unit against the unit passed in to see if the
- * two are eq to mass commensurable. It assumes that one of the units
- * is a eq-based unit and the other is a mass-based unit. It also assumes
- * that the eq-based unit has a single eq unit in the numerator and that
- * the mass-based unit has a single mass unit in the numerator. It does NOT
- * check to validate those assumptions.
- *
- * The check is made by setting the dimension vector element corresponding
- * to the base mass unit (gram) in the eq unit, and then comparing the
- * two dimension vectors. If they match, the units are commensurable.
- * Otherwise they are not.
- *
- * @param {Unit} unit2 the unit to be compared to this one
- * @returns {boolean} boolean indicating commensurability
- */
- isEqMassCommensurable(unit2) {
- let tabs = this._getUnitTables();
- let d = tabs.getMassDimensionIndex();
- // Add the equivalentExp_ values to the mass values in the dimension vectors
- // of each unit, and then compare them.
- const unit1Dim = this.dim_.clone();
- unit1Dim.setElementAt(d, unit1Dim.getElementAt(d) + this.equivalentExp_);
- const unit2Dim = unit2.dim_.clone();
- unit2Dim.setElementAt(d, unit2Dim.getElementAt(d) + unit2.equivalentExp_);
- return unit1Dim.equals(unit2Dim);
- }
-
- /**
- * This function tests this unit against the unit passed in to see if the
- * two are eq to mass commensurable-- that the equivalents could be converted
- * to the mass or vice-versa, in a way that makes the units commensurable.
- *
- * The check is made by adding the mole dimension to the equivalent dimension
- * and comparing that result for the two units, along with the units'
- * dimension vectors. If they match, the units are
- * commensurable. Otherwise they are not.
- *
- * @param {Unit} unit2 the unit to be compared to this one
- * @returns {boolean} boolean indicating commensurability
- */
- isEqMolCommensurable(unit2) {
- const unit1Sum = this.equivalentExp_ + this.moleExp_;
- const unit2Sum = unit2.equivalentExp_ + unit2.moleExp_;
- return unit1Sum == unit2Sum && this.dim_.equals(unit2.dim_);
- }
-
- /**
- * This function tests this unit against the unit passed in to see if the
- * two are commensurable if eq, mol, and mass units are converted in some
- * direction.
- *
- * The check is made by adding the eq, mol, and mass dimensions
- * and comparing that result for the two units, along with the units'
- * dimension vectors. If they match, the units are
- * commensurable. Otherwise they are not.
- *
- * @param {Unit} unit2 the unit to be compared to this one
- * @returns {boolean} boolean indicating commensurability
- */
- isEqMolMassCommensurable(unit2) {
- const d = this._getUnitTables().getMassDimensionIndex();
- const unit1Dim = this.dim_.clone();
- unit1Dim.setElementAt(d, unit1Dim.getElementAt(d) + this.equivalentExp_ + this.moleExp_);
- const unit2Dim = unit2.dim_.clone();
- unit2Dim.setElementAt(d, unit2Dim.getElementAt(d) + unit2.equivalentExp_ + unit2.moleExp_);
- return unit1Dim.equals(unit2Dim);
- }
-
- /**
- * This returns the UnitTables singleton object. Including the require
- * statement included here causes a circular dependency condition that
- * resulted in the UnitTables object not being defined for the Unit object.
- * sigh. Thanks, Paul, for figuring this out.
- *
- * @private
- */
- _getUnitTables() {
- if (!UnitTables) UnitTables = require('./unitTables.js').UnitTables;
- return UnitTables.getInstance();
- }
-} // end Unit class
-exports.Unit = Unit;
-
-
-},{"./config.js":62,"./dimension.js":63,"./ucumFunctions.js":67,"./ucumInternalUtils.js":68,"./unitTables.js":74,"is-integer":77}],73:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.UnitString = void 0;
-var intUtils_ = _interopRequireWildcard(require("./ucumInternalUtils.js"));
-function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
-function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
-function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
-function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
-/**
- * This class handles the parsing of a unit string into a unit object
- */
-
-var Ucum = require('./config.js').Ucum;
-var Unit = require('./unit.js').Unit;
-var UnitTables = require('./unitTables.js').UnitTables;
-var PrefixTables = require('./prefixTables.js').PrefixTables;
-class UnitString {
- /**
- * Constructor
- */
- constructor() {
- // Get instances of the unit and prefix tables and the utilities
- this.utabs_ = UnitTables.getInstance();
- this.pfxTabs_ = PrefixTables.getInstance();
-
- // Set emphasis characters to defaults. These are used to emphasize
- // certain characters or strings in user messages. They can be reset in
- // the useHTMLInMessages method.
- this.openEmph_ = Ucum.openEmph_;
- this.closeEmph_ = Ucum.closeEmph_;
-
- // Set the braces message to blank. This message is displayed for each
- // validation request on the web page, but is included separately as
- // a note on the validation spreadsheet. The useBraceMsgForEachString
- // method should be used to set the message to be displayed for each
- // unit string.
- this.bracesMsg_ = '';
-
- // Set the flags used, with indices, as place holders in unit strings
- // for parenthetical strings and strings within braces.
- this.parensFlag_ = "parens_placeholder"; // in lieu of Jehoshaphat
- this.pFlagLen_ = this.parensFlag_.length;
- this.braceFlag_ = "braces_placeholder"; // in lieu of Nebuchadnezzar
- this.bFlagLen_ = this.braceFlag_.length;
-
- // Initialize the message start/end strings, which will be set when
- // parseString is called.
- this.vcMsgStart_ = null;
- this.vcMsgEnd_ = null;
-
- // Arrays used by multiple methods within this class to hold persistent
- // data. Just gets too bulky to pass these guys around.
-
- // Messages to be returned to the calling function
- this.retMsg_ = [];
-
- // Units for parenthetical unit strings
- this.parensUnits_ = [];
-
- // annotation text for annotations found in unit strings
- this.annotations_ = [];
-
- // suggestions for unit strings that for which no unit was found
- this.suggestions = [];
- } // end constructor
-
- // The start of an error message about an invalid annotation character.
-
- // A regular expression for validating annotation strings.
-
- /**
- * Sets the emphasis strings to the HTML used in the webpage display - or
- * blanks them out, depending on the use parameter.
- *
- * @param use flag indicating whether or not to use the html message format;
- * defaults to true
- */
- useHTMLInMessages(use) {
- if (use === undefined || use) {
- this.openEmph_ = Ucum.openEmphHTML_;
- this.closeEmph_ = Ucum.closeEmphHTML_;
- } else {
- this.openEmph_ = Ucum.openEmph_;
- this.closeEmph_ = Ucum.closeEmph_;
- }
- } // end useHTMLInMessages
-
- /**
- * Sets the braces message to be displayed for each unit string validation
- * requested, as appropriate.
- *
- * @param use flag indicating whether or not to use the braces message;
- * defaults to true
- */
- useBraceMsgForEachString(use) {
- if (use === undefined || use) this.bracesMsg_ = Ucum.bracesMsg_;else this.bracesMsg_ = '';
- }
-
- /**
- * Parses a unit string, returns a unit, a possibly updated version of
- * the string passed in, and messages and suggestions where appropriate.
- *
- * The string returned may be updated if the input string contained unit
- * names, e.g., "pound". The unit code ([lb_av] for pound) is placed in
- * the string returned, a the returned messages array includes a note
- * explaining the substitution.
- *
- * @param uStr the string defining the unit
- * @param valConv indicates what type of request this is for - a request to
- * validate (pass in 'validate') or a request to convert (pass in 'convert');
- * optional, defaults to 'validate'
- * @param suggest a boolean to indicate whether or not suggestions are
- * requested for a string that cannot be resolved to a valid unit;
- * true indicates suggestions are wanted; false indicates they are not,
- * and is the default if the parameter is not specified;
- * @returns an array containing:
- * the unit object or null if a unit could not be created. In cases where
- * a fix was found for a problem string, .e.g., 2.mg for 2mg, a unit will
- * be returned but an error message will also be returned, describing
- * the substitution;
- * the possibly updated unit string passed in;
- * an array of any user messages (informational, error or warning)
- * generated (or an empty array); and
- * a suggestions array of hash objects (1 or more). Each hash contains
- * three elements:
- * 'msg' which is a message indicating what unit expression the
- * suggestions are for;
- * 'invalidUnit' which is the unit expression the suggestions are
- * for; and
- * 'units' which is an array of data for each suggested unit found.
- * Each array will contain the unit code, the unit name and the
- * unit guidance (if any).
- * The return array will not contain a suggestions array if a valid unit
- * was found or if suggestions were not requested.
- * @throws an error if nothing was specified.
- */
- parseString(uStr, valConv, suggest) {
- uStr = uStr.trim();
- // Make sure we have something to work with
- if (uStr === '' || uStr === null) {
- throw new Error('Please specify a unit expression to be validated.');
- }
- if (valConv === 'validate') {
- this.vcMsgStart_ = Ucum.valMsgStart_;
- this.vcMsgEnd_ = Ucum.valMsgEnd_;
- } else {
- this.vcMsgStart_ = Ucum.cnvMsgStart_;
- this.vcMsgEnd_ = Ucum.cnvMsgEnd_;
- }
- if (suggest === undefined || suggest === false) {
- this.suggestions_ = null;
- } else {
- this.suggestions_ = [];
- }
- this.retMsg_ = [];
- this.parensUnits_ = [];
- this.annotations_ = [];
- let origString = uStr;
- let retObj = [];
-
- // Extract any annotations, i.e., text enclosed in braces ({}) from the
- // string before further processing. Store each one in this.annotations_
- // array and put a placeholder in the string for the annotation. Do
- // this before other processing in case an annotation contains characters
- // that will be interpreted as parenthetical markers or operators in
- // subsequent processing.
-
- uStr = this._getAnnotations(uStr);
- if (this.retMsg_.length > 0) {
- retObj[0] = null;
- retObj[1] = null;
- } else {
- // Flag used to block further processing on an unrecoverable error
- let endProcessing = this.retMsg_.length > 0;
-
- // First check for one of the "special" units. If it's one of those, put
- // in a substitution phrase for it to avoid having it separated on its
- // embedded operator. This will only happen, by the way, if it is
- // preceded by a prefix or followed by an operator and another unit.
- let sUnit = null;
- for (sUnit in Ucum.specUnits_) {
- while (uStr.indexOf(sUnit) !== -1) uStr = uStr.replace(sUnit, Ucum.specUnits_[sUnit]);
- }
-
- // Check for spaces and throw an error if any are found. The spec
- // explicitly forbids spaces except in annotations, which is why any
- // annotations are extracted before this check is made.
- if (uStr.indexOf(' ') > -1) {
- throw new Error('Blank spaces are not allowed in unit expressions.');
- } // end if blanks were found in the string
-
- // assign the array returned to retObj. It will contain 2 elements:
- // the unit returned in position 0; and the origString (possibly
- // modified) in position 1. The origString in position 1 will not
- // be changed by subsequent processing.
- retObj = this._parseTheString(uStr, origString);
- let finalUnit = retObj[0];
-
- // Do a final check to make sure that finalUnit is a unit and not
- // just a number. Something like "8/{HCP}" will return a "unit" of 8
- // - which is not a unit. Hm - evidently it is. So just create a unit
- // object for it.
- if (intUtils_.isIntegerUnit(finalUnit) || typeof finalUnit === 'number') {
- finalUnit = new Unit({
- 'csCode_': origString,
- 'ciCode_': origString,
- 'magnitude_': finalUnit,
- 'name_': origString
- });
- retObj[0] = finalUnit;
- } // end final check
- } // end if no annotation errors were found
-
- retObj[2] = this.retMsg_;
- if (this.suggestions_ && this.suggestions_.length > 0) retObj[3] = this.suggestions_;
- return retObj;
- } // end parseString
-
- /**
- * Parses a unit string, returns a unit, a possibly updated version of
- * the string passed in, and messages where appropriate. This should
- * only be called from within this class (or by test code).
- *
- * The string returned may be updated if the input string contained unit
- * names, e.g., "pound". The unit code ([lb_av] for pound) is placed in
- * the string returned, a the returned messages array includes a note
- * explaining the substitution.
- *
- * @param uStr the string defining the unit
- * @param origString the original unit string passed in
- *
- * @returns
- * an array containing:
- * the unit object (or null if there were problems creating the unit); and
- * the possibly updated unit string passed in.
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- * the this.parensUnits_ array is referenced and possibly populated by
- * methods called within this one
- * the this.annotations_ array is referenced by methods called within
- * this one
- * the this.suggestions_ array may be populated by methods called within
- * this one
- */
- _parseTheString(uStr, origString) {
- // Unit to be returned
- let finalUnit = null;
-
- // Flag used to block further processing on an unrecoverable error
- let endProcessing = this.retMsg_.length > 0;
-
- // Call _processParens to search for and process any/all parenthetical
- // strings in uStr. Units created for parenthetical strings will be
- // stored in the this.parensUnits_ array.
- let parensResp = this._processParens(uStr, origString);
- endProcessing = parensResp[2];
-
- // The array used to hold the units and their operators.
- let uArray = [];
-
- // Continue if we didn't hit a problem
- if (!endProcessing) {
- uStr = parensResp[0];
- origString = parensResp[1];
-
- // Call _makeUnitsArray to convert the string to an array of unit
- // descriptors with operators.
- let mkUArray = this._makeUnitsArray(uStr, origString);
- endProcessing = mkUArray[2];
- if (!endProcessing) {
- uArray = mkUArray[0];
- origString = mkUArray[1];
- // Create a unit object out of each un element
- let uLen = uArray.length;
- for (let u1 = 0; u1 < uLen; u1++) {
- //for (let u1 = 0; u1 < uLen && !endProcessing; u1++) {
- let curCode = uArray[u1]['un'];
-
- // Determine the type of the "un" attribute of the current array element
-
- // Check to see if it's a number. If so write the number version of
- // the number back to the "un" attribute and move on
- if (intUtils_.isIntegerUnit(curCode)) {
- uArray[u1]['un'] = Number(curCode);
- } else {
- // The current unit array element is a string. Check now to see
- // if it is or contains a parenthesized unit from this.parensUnits_.
- // If so, call _getParens to process the string and get the unit.
-
- if (curCode.indexOf(this.parensFlag_) >= 0) {
- let parenUnit = this._getParensUnit(curCode, origString);
- // if we couldn't process the string, set the end flag and bypass
- // further processing.
- if (!endProcessing) endProcessing = parenUnit[1];
-
- // If we're good, put the unit in the uArray and replace the
- // curCode, which contains the parentheses placeholders, etc.,
- // with the unit's code - including any substitutions.
- if (!endProcessing) {
- uArray[u1]['un'] = parenUnit[0];
- }
- } // end if the curCode contains a parenthesized unit
-
- // Else it's not a parenthetical unit and not a number. Call
- // _makeUnit to create a unit for it.
- else {
- let uRet = this._makeUnit(curCode, origString);
- // If we didn't get a unit, set the endProcessing flag.
- if (uRet[0] === null) {
- endProcessing = true;
- } else {
- uArray[u1]['un'] = uRet[0];
- origString = uRet[1];
- }
- } // end if the curCode is not a parenthetical expression
- } // end if the "un" array is a not a number
- } // end do for each element in the units array
- } // end if _makeUnitsArray did not return an error
- } // end if _processParens did not find an error that causes a stop
-
- // If we're still good, continue
- if (!endProcessing) {
- // Process the units (and numbers) to create one final unit object
- if ((uArray[0] === null || uArray[0] === ' ' || uArray[0]['un'] === undefined || uArray[0]['un'] === null) && this.retMsg_.length === 0) {
- // not sure what this might be, but this is a safeguard
- this.retMsg_.push(`Unit string (${origString}) did not contain ` + `anything that could be used to create a unit, or else something ` + `that is not handled yet by this package. Sorry`);
- endProcessing = true;
- }
- }
- if (!endProcessing) {
- finalUnit = this._performUnitArithmetic(uArray, origString);
- }
- return [finalUnit, origString];
- } // end _parseTheString
-
- /**
- * Extracts all annotations from a unit string, replacing them with
- * placeholders for later evaluation. The annotations are stored in the
- * this.annotations_ array. This should only be called from within this
- * class (or by test code).
- *
- * @param uString the unit string being parsed
- * @returns the string after the annotations are replaced with placeholders
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- * the this.annotations_ array is populated by this method
- */
- _getAnnotations(uString) {
- let openBrace = uString.indexOf('{');
- while (openBrace >= 0) {
- let closeBrace = uString.indexOf('}');
- if (closeBrace < 0) {
- this.retMsg_.push('Missing closing brace for annotation starting at ' + this.openEmph_ + uString.substr(openBrace) + this.closeEmph_);
- openBrace = -1;
- } else {
- let braceStr = uString.substring(openBrace, closeBrace + 1);
- // Check for valid characters in the annotation.
- if (!UnitString.VALID_ANNOTATION_REGEX.test(braceStr)) {
- this.retMsg_.push(UnitString.INVALID_ANNOTATION_CHAR_MSG + this.openEmph_ + braceStr + this.closeEmph_);
- openBrace = -1; // end search for annotations
- } else {
- let aIdx = this.annotations_.length.toString();
- uString = uString.replace(braceStr, this.braceFlag_ + aIdx + this.braceFlag_);
- this.annotations_.push(braceStr);
- openBrace = uString.indexOf('{');
- }
- }
- } // end do while we have an opening brace
-
- // check for a stray/unmatched closing brace
- if (this.retMsg_.length == 0) {
- // if there were no other errors above
- let closeBrace = uString.indexOf('}');
- if (closeBrace >= 0) this.retMsg_.push('Missing opening brace for closing brace found at ' + this.openEmph_ + uString.substring(0, closeBrace + 1) + this.closeEmph_);
- }
- return uString;
- } // end _getAnnotations
-
- /**
- * Finds and processes any/all parenthesized unit strings. This should only
- * be called from within this class (or by test code).
- *
- * Nested parenthesized strings are processed from the inside out. The
- * parseString function is called from within this one for each parenthesized
- * unit string, and the resulting unit object is stored in this.parensUnits_,
- * to be processed after all strings are translated to units.
- *
- * A placeholder is placed in the unit string returned to indicate that the
- * unit object should be obtained from the this.parensUnits_ array. The
- * placeholder consists of the parenthesis flag (this.parensFlag_) followed
- * by the index of the unit in this.parensUnits_ followed by this.parensFlag_.
- *
- * @param uString the unit string being parsed, where this will be the full
- * string the first time this is called and parenthesized strings on any
- * subsequent calls
- * @param origString the original string first passed in to parseString
- * @returns
- * an array containing:
- * the string after the parentheses are replaced;
- * the original string; and
- * a boolean flag indicating whether or not an error occurred that
- * should stop processing.
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- * this this.parensUnits_ array will be populated with units found for
- * parenthetical unit strings
- */
- _processParens(uString, origString) {
- // Unit strings array and index
- let uStrArray = [];
- let uStrAryPos = 0;
- let stopProcessing = false;
- let pu = this.parensUnits_.length;
-
- // Count of characters trimmed off the beginning of the unit string (uString)
- // as units are removed from it; used for error messages to provide
- // context.
- let trimmedCt = 0;
-
- // Break the unit string into pieces that consist of text outside of
- // parenthetical strings and placeholders for the parenthetical units.
- // This method is called recursively for parenthetical strings and the units
- // returned are stored in the this.parensUnits_ array.
- while (uString !== "" && !stopProcessing) {
- let openCt = 0;
- let closeCt = 0;
- let openPos = uString.indexOf('(');
-
- // If an opening parenthesis was not found, check for an unmatched
- // close parenthesis. If one was found report the error and end
- // processing.
- if (openPos < 0) {
- let closePos = uString.indexOf(')');
- if (closePos >= 0) {
- let theMsg = `Missing open parenthesis for close ` + `parenthesis at ${uString.substring(0, closePos + trimmedCt)}` + `${this.openEmph_}${uString.substr(closePos, 1)}${this.closeEmph_}`;
- if (closePos < uString.length - 1) {
- theMsg += `${uString.substr(closePos + 1)}`;
- }
- this.retMsg_.push(theMsg);
- uStrArray[uStrAryPos] = uString;
- stopProcessing = true;
- } // end if a close parenthesis was found
-
- // If no parentheses were found in the current unit string, transfer
- // it to the units array and blank out the string, which will end
- // the search for parenthetical units.
- else {
- uStrArray[uStrAryPos] = uString;
- uString = "";
- } // end if no close parenthesis was found
- } // end if no open parenthesis was found
-
- // Otherwise an open parenthesis was found. Process the string that
- // includes the parenthetical group
- else {
- openCt += 1;
- // Write the text before the parentheses (if any) to the unit strings array
- let uLen = uString.length;
- if (openPos > 0) {
- uStrArray[uStrAryPos++] = uString.substr(0, openPos);
- }
-
- // Find the matching closePos, i.e., the one that closes the
- // parenthetical group that this one opens. Look also for
- // another open parenthesis, in case this includes nested parenthetical
- // strings. This continues until it finds the same number of close
- // parentheses as open parentheses, or runs out of string to check.
- // In the case of nested parentheses this will identify the outer set
- // of parentheses.
- let closePos = 0;
- let c = openPos + 1;
- for (; c < uLen && openCt != closeCt; c++) {
- if (uString[c] === '(') openCt += 1;else if (uString[c] === ')') closeCt += 1;
- }
-
- // Put a placeholder for the group in the unit strings array and recursively
- // call this method for the parenthetical group. Put the unit returned
- // in this.parensUnits_. Set the unit string to whatever follows
- // the position of the closing parenthesis for this group, to be
- // processed by the next iteration of this loop. If there's nothing
- // left uString is set to "".
- if (openCt === closeCt) {
- closePos = c;
- uStrArray[uStrAryPos++] = this.parensFlag_ + pu.toString() + this.parensFlag_;
- let parseResp = this._parseTheString(uString.substring(openPos + 1, closePos - 1), origString);
- if (parseResp[0] === null) stopProcessing = true;else if (uString[openPos + 1] === '/') {
- // If the term inside the parenthesis starts with '/', fail the validation. See LF-2854.
- this.retMsg_.push("Unary operator '/' is only allowed at the beginning of the main term, not inside a parenthesis.");
- stopProcessing = true;
- } else {
- origString = parseResp[1];
- this.parensUnits_[pu++] = parseResp[0];
- uString = uString.substr(closePos);
- trimmedCt = closePos;
- }
- } // end if the number of open and close parentheses matched
-
- // If the number of open and close parentheses doesn't match, indicate
- // an error.
- else {
- uStrArray.push(origString.substr(openPos));
- this.retMsg_.push(`Missing close parenthesis for open parenthesis at ` + `${origString.substring(0, openPos + trimmedCt)}` + `${this.openEmph_}${origString.substr(openPos, 1)}` + `${this.closeEmph_}${origString.substr(openPos + 1)}`);
- stopProcessing = true;
- }
- } // end if an open parenthesis was found
- } // end do while the input string is not empty
- if (stopProcessing) this.parensUnits_ = [];
- return [uStrArray.join(''), origString, stopProcessing];
- } // end _processParens
-
- /**
- * Breaks the unit string into an array of unit descriptors and operators.
- * If a unit descriptor consists of a number preceding a unit code, with
- * no multiplication operator, e.g., 2mg instead of 2.mg, it is handled
- * as if it were a parenthetical expression.
- *
- * This should only be called from within this class (or by test code).
- *
- * @param uStr the unit string being parsed
- * @param origString the original string passed to parseString
- * @returns
- * an array containing:
- * the array representing the unit string;
- * the original string passed in, possibly updated with corrections; and
- * and a flag indicating whether or not processing can continue.
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- */
- _makeUnitsArray(uStr, origString) {
- // Separate the string into pieces based on delimiters / (division) and .
- // (multiplication). The idea is to get an array of units on which we
- // can then perform any operations (prefixes, multiplication, division).
-
- let uArray1 = uStr.match(/([./]|[^./]+)/g);
- let endProcessing = false;
- let uArray = [];
- let startNumCheck = /(^[0-9]+)(\[?[a-zA-Z\_0-9a-zA-Z\_]+\]?$)/;
-
- // If the first element in the array is the division operator (/), the
- // string started with '/'. Add a first element containing 1 to the
- // array, which will cause the correct computation to be performed (inversion).
- if (uArray1[0] === "/") {
- uArray1.unshift("1");
- }
- // If the first element in the array is the multiplication operator (.)
- // return an error.
- else if (uArray1[0] === '.') {
- this.retMsg_.push(`${origString} is not a valid UCUM code. ` + `The multiplication operator at the beginning of the expression is ` + `not valid. A multiplication operator must appear only between ` + `two codes.`);
- endProcessing = true;
- }
- if (!endProcessing) {
- // Check to see if there is a number preceding a unit code, e.g., 2mg
- // If so, update the first element to remove the number (2mg -> mg) and
- // add two elements to the beginning of the array - the number and the
- // multiplication operator.
-
- if (!intUtils_.isNumericString(uArray1[0])) {
- let numRes = uArray1[0].match(startNumCheck);
- if (numRes && numRes.length === 3 && numRes[1] !== '' && numRes[2] !== '' && numRes[2].indexOf(this.braceFlag_) !== 0) {
- let dispVal = numRes[2];
- if (!endProcessing && numRes[2].indexOf(this.parensFlag_) !== -1) {
- let parensback = this._getParensUnit(numRes[2], origString);
- numRes[2] = parensback[0]['csCode_'];
- dispVal = `(${numRes[2]})`;
- endProcessing = parensback[1];
- }
- if (!endProcessing) {
- this.retMsg_.push(`${numRes[1]}${dispVal} is not a valid UCUM code.` + ` ${this.vcMsgStart_}${numRes[1]}.${dispVal}${this.vcMsgEnd_}`);
- origString = origString.replace(`${numRes[1]}${dispVal}`, `${numRes[1]}.${dispVal}`);
- uArray1[0] = numRes[2];
- uArray1.unshift(numRes[1], '.');
- }
- }
- } // end if the first element is not a number (only)
-
- // Create an array of unit/operator objects. The unit is, for now, the
- // string containing the unit code (e.g., Hz for hertz) including
- // a possible prefix and exponent. The operator is the operator to be
- // applied to that unit and the one preceding it. So, a.b would give
- // us two objects. The first will have a unit of a, and a blank operator
- // (because it's the first unit). The second would have a unit of b
- // and the multiplication operator (.).
- if (!endProcessing) {
- let u1 = uArray1.length;
- uArray = [{
- op: "",
- un: uArray1[0]
- }];
- for (let n = 1; n < u1; n++) {
- // check to make sure that we don't have two operators together, e.g.,
- // mg./K. If so, let the user know the problem.
- let theOp = uArray1[n++];
- // oh wait - check to make sure something is even there, that the
- // user didn't end the expression with an operator.
- if (!uArray1[n]) {
- this.retMsg_.push(`${origString} is not a valid UCUM code. ` + `It is terminated with the operator ${this.openEmph_}` + `${theOp}${this.closeEmph_}.`);
- n = u1;
- endProcessing = true;
- } else if (Ucum.validOps_.indexOf(uArray1[n]) !== -1) {
- this.retMsg_.push(`${origString} is not a valid UCUM code. ` + `A unit code is missing between${this.openEmph_}` + `${theOp}${this.closeEmph_}and${this.openEmph_}` + `${uArray1[n]}${this.closeEmph_}in${this.openEmph_}` + `${theOp}${uArray1[n]}${this.closeEmph_}.`);
- n = u1;
- endProcessing = true;
- } else {
- // Check to see if a number precedes a unit code.
- // If so, send the element to _processParens, inserting the multiplication
- // operator where it belongs. Treating it as parenthetical keeps it from
- // being interpreted incorrectly because of operator parentheses. For
- // example, if the whole string is mg/2kJ we don't want to rewrite it as
- // mg/2.kJ - because mg/2 would be performed, followed by .kJ. Instead,
- // handling 2kJ as a parenthesized unit will make sure mg is divided by
- // 2.kJ.
- if (!intUtils_.isNumericString(uArray1[n])) {
- let numRes2 = uArray1[n].match(startNumCheck);
- if (numRes2 && numRes2.length === 3 && numRes2[1] !== '' && numRes2[2] !== '' && numRes2[2].indexOf(this.braceFlag_) !== 0) {
- let invalidString = numRes2[0];
- if (!endProcessing && numRes2[2].indexOf(this.parensFlag_) !== -1) {
- let parensback = this._getParensUnit(numRes2[2], origString);
- numRes2[2] = parensback[0]['csCode_'];
- invalidString = `(${numRes2[2]})`;
- endProcessing = parensback[1];
- if (!endProcessing) {
- this.retMsg_.push(`${numRes2[1]}${invalidString} is not a ` + `valid UCUM code. ${this.vcMsgStart_}${numRes2[1]}.${invalidString}` + `${this.vcMsgEnd_}`);
- let parensString = `(${numRes2[1]}.${invalidString})`;
- origString = origString.replace(`${numRes2[1]}${invalidString}`, parensString);
- let nextParens = this._processParens(parensString, origString);
- endProcessing = nextParens[2];
- if (!endProcessing) {
- uArray.push({
- op: theOp,
- un: nextParens[0]
- });
- }
- //uArray.push({op: '.', un: numRes2[2]});
- }
- } // end if the string represents a parenthesized unit
- else {
- let parensStr = '(' + numRes2[1] + '.' + numRes2[2] + ')';
- let parensResp = this._processParens(parensStr, origString);
- // if a "stop processing" flag was returned, set the n index to end
- // the loop and set the endProcessing flag
- if (parensResp[2]) {
- n = u1;
- endProcessing = true;
- } else {
- this.retMsg_.push(`${numRes2[0]} is not a ` + `valid UCUM code. ${this.vcMsgStart_}${numRes2[1]}.${numRes2[2]}` + `${this.vcMsgEnd_}`);
- origString = origString.replace(numRes2[0], parensStr);
- uArray.push({
- op: theOp,
- un: parensResp[0]
- });
- } // end if no error on the processParens call
- } // end if the string does not represent a parenthesized unit
- } // end if the string is a number followed by a string
- else {
- uArray.push({
- op: theOp,
- un: uArray1[n]
- });
- }
- } else {
- uArray.push({
- op: theOp,
- un: uArray1[n]
- });
- }
- } // end if there isn't a missing operator or unit code
- } // end do for each element in uArray1
- } // end if a processing error didn't occur in getParensUnit
- } // end if the string did not begin with a '.' with no following digit
- return [uArray, origString, endProcessing];
- } // end _makeUnitsArray
-
- /**
- * Takes a unit string containing parentheses flags and returns the unit they
- * represent. Any text found before and/or after the parenthetical
- * expression is checked to see if we can tell what the user meant and
- * let them know what it should have been. For example, 2(mg), which
- * would resolve to 2mg, should be 2.mg.
- *
- * This should only be called from within this class (or by test code).
- *
- * @param pStr the string being parsed
- * @param origString the original unit string passed in; passed through
- * to _getAnnonText if annotation flags are found in any text preceding
- * or following the parenthetical unit
- * @returns
- * an array containing
- * the unit object; and
- * a flag indicating whether or not processing should be ended.
- * True indicates that the string was invalid and no corrections
- * (substitutions or suggestions) could be found;
- * False indicates that it was either valid or substitutions/suggestions
- * were made.
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- * this this.parensUnits_ array contains the units that are acquired by
- * this method
- * @throws an error if an invalid parensUnit index was found. This is
- * a processing error.
- */
- _getParensUnit(pStr, origString) {
- let endProcessing = false;
- let retAry = [];
- let retUnit = null;
- let befAnnoText = null;
- let aftAnnoText = null;
-
- // Get the location of the flags. We're assuming there are only two
- // because _processParens takes care of nesting. By the time we get
- // here we should not be looking a nested parens. Also get any text
- // before and after the parentheses. Once we get the unit we update
- // the input string with the unit's csCode_, which will wipe out any
- // before and after text
- let psIdx = pStr.indexOf(this.parensFlag_);
- let befText = null;
- if (psIdx > 0) {
- befText = pStr.substring(0, psIdx);
- }
- let peIdx = pStr.lastIndexOf(this.parensFlag_);
- let aftText = null;
- if (peIdx + this.pFlagLen_ < pStr.length) {
- aftText = pStr.substr(peIdx + this.pFlagLen_);
- }
-
- // Get the text between the flags
- let pNumText = pStr.substring(psIdx + this.pFlagLen_, peIdx);
-
- // Make sure the index is a number, and if it is, get the unit from the
- // this.parensUnits_ array
- if (intUtils_.isNumericString(pNumText)) {
- retUnit = this.parensUnits_[Number(pNumText)];
- if (!intUtils_.isIntegerUnit(retUnit)) {
- pStr = retUnit.csCode_;
- } else {
- pStr = retUnit;
- }
- }
- // If it's not a number, it's a programming error. Throw a fit.
- else {
- throw new Error(`Processing error - invalid parens number ${pNumText} ` + `found in ${pStr}.`);
- }
-
- // If there's something in front of the starting parentheses flag, check to
- // see if it's a number or an annotation.
- if (befText) {
- // If it's a number, assume that multiplication was assumed
- if (intUtils_.isNumericString(befText)) {
- let nMag = retUnit.getProperty('magnitude_');
- nMag *= Number(befText);
- retUnit.assignVals({
- 'magnitude_': nMag
- });
- pStr = `${befText}.${pStr}`;
- this.retMsg_.push(`${befText}${pStr} is not a valid UCUM code.\n` + this.vcMsgStart_ + pStr + this.vcMsgEnd_);
- } else {
- if (befText.indexOf(this.braceFlag_) >= 0) {
- let annoRet = this._getAnnoText(befText, origString);
- // if we found not only an annotation, but text before or after
- // the annotation (remembering that this is all before the
- // parentheses) throw an error - because we don't know what
- // to do with it. Could it be missing an operator?
- if (annoRet[1] || annoRet[2]) {
- throw new Error(`Text found before the parentheses (` + `${befText}) included an annotation along with other text ` + `for parenthetical unit ${retUnit.csCode_}`);
- }
- // Otherwise put the annotation after the unit string and note
- // the misplacement.
- pStr += annoRet[0];
- this.retMsg_.push(`The annotation ${annoRet[0]} before the unit ` + `code is invalid.\n` + this.vcMsgStart_ + pStr + this.vcMsgEnd_);
- }
- // else the text before the parentheses is neither a number nor
- // an annotation. Record an error.
- else {
- this.retMsg_.push(`${befText} preceding the unit code ${pStr} ` + `is invalid. Unable to make a substitution.`);
- endProcessing = true;
- } // end if a brace was found
- } // end if text preceding the parentheses was not a number
- } // end if there was text before the parentheses
-
- // Process any text after the parentheses
- if (aftText) {
- // if it's an annotation, get it and add it to the pStr
- if (aftText.indexOf(this.braceFlag_) >= 0) {
- let annoRet = this._getAnnoText(aftText, origString);
- // if we found not only an annotation, but text before or after
- // the annotation (remembering that this is all after the
- // parentheses) throw an error - because we don't know what
- // to do with it. Could it be missing an operator?
- if (annoRet[1] || annoRet[2]) {
- throw new Error(`Text found after the parentheses (` + `${aftText}) included an annotation along with other text ` + `for parenthetical unit ${retUnit.csCode_}`);
- }
- // Otherwise put the annotation after the unit string - no message
- // needed.
- pStr += annoRet[0];
- }
- // Otherwise check to see if it's an exponent. If so, warn the
- // user that it's not valid - but try it anyway
- else {
- if (intUtils_.isNumericString(aftText)) {
- retUnit = null;
- let msg = `An exponent (${aftText}) following a parenthesis ` + `is invalid as of revision 1.9 of the UCUM Specification.`;
- // Add the suggestion only if the string in the parenthesis don't end with a number.
- if (!pStr.match(/\d$/)) {
- pStr += aftText;
- msg += '\n ' + this.vcMsgStart_ + pStr + this.vcMsgEnd_;
- }
- this.retMsg_.push(msg);
- endProcessing = true;
- }
- // else the text after the parentheses is neither a number nor
- // an annotation. Record an error.
- else {
- this.retMsg_.push(`Text ${aftText} following the unit code ${pStr} ` + `is invalid. Unable to make a substitution.`);
- endProcessing = true;
- } // end if text following the parentheses not an exponent
- } // end if text following the parentheses is not an annotation
- } // end if there is text following the parentheses
- if (!endProcessing) {
- if (!retUnit) {
- retUnit = new Unit({
- 'csCode_': pStr,
- 'magnitude_': 1,
- 'name_': pStr
- });
- } else if (intUtils_.isIntegerUnit(retUnit)) {
- retUnit = new Unit({
- 'csCode_': retUnit,
- 'magnitude_': retUnit,
- 'name_': retUnit
- });
- } else {
- retUnit.csCode_ = pStr;
- }
- }
- return [retUnit, endProcessing];
- } // end _getParensUnit
-
- /**
- * Takes a unit string containing annotation flags and returns the
- * annotation they represent. This also returns any text found before
- * the annotation and any found after the annotation.
- *
- * This should only be called from within this class (or by test code).
- * NEEDS FIX in next branch to handle string with multiple annotations.
- *
- * @param pStr the string being parsed
- * @param origString the original string being parsed; used in error msg
- * thrown for an invalid index to the annotations array
- * @returns
- * an array containing
- * the annotation for the pStr;
- * any text found before the annotation; and
- * any text found after the annotation.
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- * the this.annotations_ array is used as the source for the annotations text
- * @throws an error if for a processing error - an invalid annotation index.
- */
- _getAnnoText(pStr, origString) {
- // if the starting braces flag is not at index 0, get the starting
- // text and the adjust the pStr to omit it.
- let asIdx = pStr.indexOf(this.braceFlag_);
- let startText = asIdx > 0 ? pStr.substring(0, asIdx) : null;
- if (asIdx !== 0) {
- pStr = pStr.substr(asIdx);
- }
-
- // Get the location of the end flag and, if text follows it, get the text
- let aeIdx = pStr.indexOf(this.braceFlag_, 1);
- let endText = aeIdx + this.bFlagLen_ < pStr.length ? pStr.substr(aeIdx + this.bFlagLen_) : null;
-
- // Get the index of the annotation in this.annotations_.
- // Check it to make sure it's valid, and if not, throw an error
- let idx = pStr.substring(this.bFlagLen_, aeIdx);
- let idxNum = Number(idx);
- if (!intUtils_.isNumericString(idx) || idxNum >= this.annotations_.length) {
- throw new Error(`Processing Error - invalid annotation index ${idx} found ` + `in ${pStr} that was created from ${origString}`);
- }
-
- // Replace the flags and annotation index with the annotation expression
- pStr = this.annotations_[idxNum];
- return [pStr, startText, endText];
- } // end _getAnnoText
-
- /**
- * Takes a unit string and looks for suggested units. This should be
- * called for unit strings that cannot be resolved to unit codes. The
- * string is searched for in the synonyms table found in the UnitTables
- * class. That table includes all synonyms and unit names for the units
- * in the unit data table.
- *
- * @param pStr the string being parsed
- * @returns an object that contains an element named 'status', whose
- * value indicates the status of the request:
- * 'succeeded' indicates that synonyms were found;
- * 'failed' indicates that no synonyms were found; or
- * 'error' which indicates that an error occurred
- *
- * the this.retMsg_ array will be updated with a message indicating whether
- * or not synonyms/suggestions were found
- * the this.suggestions_ array will be updated with a hash (added to the
- * array if it already contains others) that contains three elements:
- * 'msg' which is a message indicating what unit expression the
- * suggestions are for;
- * 'invalidUnit' which is the unit expression the suggestions are for; and
- * 'units' which is an array of data for each suggested unit found.
- * Each array will contain the unit code, the unit name and the
- * unit guidance (if any).
- */
- _getSuggestions(pStr) {
- let retObj = intUtils_.getSynonyms(pStr);
- if (retObj['status'] === 'succeeded') {
- let suggSet = {};
- suggSet['msg'] = `${pStr} is not a valid UCUM code. We found possible ` + `units that might be what was meant:`;
- suggSet['invalidUnit'] = pStr;
- let synLen = retObj['units'].length;
- suggSet['units'] = [];
- for (let s = 0; s < synLen; s++) {
- let unit = retObj['units'][s];
- let unitArray = [unit['code'], unit['name'], unit['guidance']];
- suggSet['units'].push(unitArray);
- }
- this.suggestions_.push(suggSet);
- } else {
- this.retMsg_.push(`${pStr} is not a valid UCUM code. No alternatives ` + `were found.`);
- }
- return retObj['status'];
- } // end getSuggestions
-
- /**
- * Creates a unit object from a string defining one unit. The string
- * should consist of a unit code for a unit already defined (base or
- * otherwise). It may include a prefix and an exponent, e.g., cm2
- * (centimeter squared). This should only be called from within this
- * class (or by test code).
- *
- * @params uCode the string defining the unit
- * @param origString the original string to be parsed; used to provide
- * context for messages
- * @returns
- * an array containing:
- * a unit object, or null if there were problems creating the unit; and
- * the origString passed in, which may be updated if a unit name was
- * translated to a unit code.
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- * the this.suggestions_ array will be populated if no unit (with or without
- * substitutions) could be found and suggestions were requested
- */
- _makeUnit(uCode, origString) {
- // First try the code just as is, without looking for annotations,
- // prefixes, exponents, or elephants.
- let retUnit = this.utabs_.getUnitByCode(uCode);
- if (retUnit) {
- retUnit = retUnit.clone();
- }
-
- // If we found it, we're done. No need to parse for those elephants (or
- // other stuff).
- else if (uCode.indexOf(this.braceFlag_) >= 0) {
- let getAnnoRet = this._getUnitWithAnnotation(uCode, origString);
- retUnit = getAnnoRet[0];
- if (retUnit) {
- origString = getAnnoRet[1];
- }
- // If a unit is not found, retUnit will be returned null and
- // the this.retMsg_ array will contain a message describing the problem.
- // If a unit is found, of course, all is good. So ... nothing left
- // to see here, move along.
- } // end if the uCode includes an annotation
- else {
- // So we didn't find a unit for the full uCode or for one with
- // annotations. Try looking for a unit that uses a carat (^)
- // instead of an asterisk (*)
-
- if (uCode.indexOf('^') > -1) {
- let tryCode = uCode.replace('^', '*');
- retUnit = this.utabs_.getUnitByCode(tryCode);
- if (retUnit) {
- retUnit = retUnit.clone();
- retUnit.csCode_ = retUnit.csCode_.replace('*', '^');
- retUnit.ciCode_ = retUnit.ciCode_.replace('*', '^');
- }
- }
- // If we still don't have a unit, try assuming a modifier (prefix and/or
- // exponent) and look for a unit without the modifier
- if (!retUnit) {
- // Well, first see if it's one of the special units. If so,
- // replace the placeholder text with the actual unit string, keeping
- // whatever text (probably a prefix) goes with the unit string.
- let sUnit = null;
- for (sUnit in Ucum.specUnits_) {
- if (uCode.indexOf(Ucum.specUnits_[sUnit]) !== -1) uCode = uCode.replace(Ucum.specUnits_[sUnit], sUnit);
- }
- retUnit = this.utabs_.getUnitByCode(uCode);
- if (retUnit) retUnit = retUnit.clone();
- }
- if (!retUnit) {
- let origCode = uCode;
- let origUnit = null;
- let exp = null;
- let pfxCode = null;
- let pfxObj = null;
- let pfxVal = null;
-
- // Look first for an exponent. If we got one, separate it out and
- // try to get the unit again
- let codeAndExp = this._isCodeWithExponent(uCode);
- let isIntegerUnitWithExp = false;
- if (codeAndExp) {
- uCode = codeAndExp[0];
- exp = codeAndExp[1];
- isIntegerUnitWithExp = intUtils_.isIntegerUnit(uCode);
- origUnit = isIntegerUnitWithExp ? new Unit({
- 'csCode_': uCode,
- 'ciCode_': uCode,
- 'magnitude_': Number(uCode),
- 'name_': uCode
- }) : this.utabs_.getUnitByCode(uCode);
- }
-
- // If an exponent is found but it's not a valid number, e.g. "2-1",
- // mark the unit invalid. Otherwise, the "-1" part will be ignored
- // because parseInt("2-1") results in 2. See LF-2870.
- if (exp && isNaN(exp)) {
- retUnit = null;
- this.retMsg_.push(`${origCode} is not a valid UCUM code.`);
- } else {
- // If we still don't have a unit, separate out the prefix, if any,
- // and try without it.
- if (!origUnit && uCode.length > 1) {
- // Try for a single character prefix first, then for a two-digit prefix
- pfxCode = '';
- do {
- pfxCode += uCode.charAt(0);
- uCode = uCode.substr(1);
- pfxObj = this.pfxTabs_.getPrefixByCode(pfxCode);
- if (pfxObj) {
- pfxVal = pfxObj.getValue();
- // try again for the unit
- origUnit = this.utabs_.getUnitByCode(uCode);
- }
- } while (!origUnit && pfxCode.length < 2 && uCode.length > 1);
-
- // Reject the unit we found if it might have another prefix. (??)
- // Such things are in our tables through the LOINC source_
- // (ucum.csv) which has guidance and synonyms. I think it should be
- // safe to exclude anything whose source is LOINC from having a
- // prefix.
- if (origUnit && origUnit.source_ == 'LOINC') origUnit = null;
- } // end if we didn't get a unit after removing an exponent
-
- // If we still haven't found anything, we're done looking.
- // (We tried with the full unit string, with the unit string
- // without the exponent, the unit string without a prefix,
- // common errors, etc. That's all we can try).
- if (!origUnit) {
- let bracketRet = this._getUnitAfterAddingBrackets(origCode, origString);
- retUnit = bracketRet[0];
- origString = bracketRet[1];
- if (!retUnit) {
- let nameRet = this._getUnitByName(origCode, origString);
- retUnit = nameRet[0];
- origString = nameRet[1];
- if (!retUnit) {
- // BUT if the user asked for suggestions, at least look for them
- if (this.suggestions_) {
- let suggestStat = this._getSuggestions(origCode);
- } else {
- this.retMsg_.push(`${origCode} is not a valid UCUM code.`);
- }
- }
- }
- } else {
- // Otherwise we found a unit object. Clone it and then apply the
- // prefix and exponent, if any, to it. And remove the guidance.
- retUnit = origUnit.clone();
- // If we are here, this is only part of the full unit string, so it is
- // not a base unit, and the synonyms will mostly likely not be correct for the full
- // string.
- retUnit.resetFieldsForDerivedUnit();
- let theDim = retUnit.getProperty('dim_');
- let theMag = retUnit.getProperty('magnitude_');
- let theName = retUnit.getProperty('name_');
- let theCiCode = retUnit.getProperty('ciCode_');
- let thePrintSymbol = retUnit.getProperty('printSymbol_');
- // If there is an exponent for the unit, apply it to the dimension
- // and magnitude now
- if (exp) {
- // Special units cannot be raised to a power
- if (retUnit.isSpecial_) {
- this.retMsg_.push(`Special units like ${retUnit.name_} cannot be raised to a power.`);
- retUnit = null;
- } else {
- exp = parseInt(exp);
- if (theDim) theDim = theDim.mul(exp);
- retUnit.equivalentExp_ *= exp;
- retUnit.moleExp_ *= exp;
- theMag = Math.pow(theMag, exp);
- retUnit.assignVals({
- 'magnitude_': theMag
- });
-
- // If there is also a prefix, apply the exponent to the prefix.
- if (pfxObj) {
- // We don't need to consider pfxObj.getExp(), because when
- // present that is reflected in the pfxVal. However, in some
- // cases one can avoid floating-point math inaccuracies by using
- // that exponent instead of relying on pfxVal. For example:
- // 1e-66 = Math.pow(10, -3*22) = Math.pow(0.001, 22) = 1.0000000000000005e-66
- // (This is the from the test case of the unit mg% raised to the 22nd power (mg%22).)
- // This does not help in all cases, but it does help the above
- // test case (which is in our web API service test code).
- let pfxExp = pfxObj.getExp();
- if (pfxExp) {
- // This is relying on the fact that pfxExp is null when
- // the prefix base is not 10.
- pfxVal = Math.pow(10, exp * pfxExp);
- } else {
- pfxVal = Math.pow(pfxVal, exp);
- }
- }
- } // end else - prefix and exponent handling for non-special units
- } // end if there's an exponent
-
- if (retUnit) {
- // Now apply the prefix, if there is one, to the conversion
- // prefix or the magnitude
- if (pfxObj) {
- if (retUnit.cnv_) {
- retUnit.assignVals({
- 'cnvPfx_': pfxVal
- });
- } else {
- theMag *= pfxVal;
- retUnit.assignVals({
- 'magnitude_': theMag
- });
- }
- }
- // if we have a prefix and/or an exponent, add them to the unit
- // attributes - name, csCode, ciCode and print symbol
- let theCode = retUnit.csCode_;
- if (pfxObj) {
- theName = pfxObj.getName() + theName;
- theCode = pfxCode + theCode;
- theCiCode = pfxObj.getCiCode() + theCiCode;
- thePrintSymbol = pfxObj.getPrintSymbol() + thePrintSymbol;
- retUnit.assignVals({
- 'name_': theName,
- 'csCode_': theCode,
- 'ciCode_': theCiCode,
- 'printSymbol_': thePrintSymbol
- });
- }
- if (exp) {
- let expStr = exp.toString();
- const intergerUnitExpSign = isIntegerUnitWithExp && exp > 0 ? '+' : '';
- retUnit.assignVals({
- 'name_': theName + '' + expStr + '',
- 'csCode_': theCode + intergerUnitExpSign + expStr,
- 'ciCode_': theCiCode + intergerUnitExpSign + expStr,
- 'printSymbol_': thePrintSymbol + '' + expStr + ''
- });
- }
- }
- } // end if an original unit was found (without prefix and/or exponent)
- } // end if an invalid exponent wasn't found
- } // end if we didn't get a unit for the full unit code (w/out modifiers)
- } // end if we didn't find the unit on the first try, before parsing
- return [retUnit, origString];
- } // end _makeUnit
-
- /**
- * Checks whether an otherwise unresolved unit code matches a unit name.
- *
- * @param uCode the unit code or name to check
- * @param origString the original full string submitted to parseString
- * @returns an array containing the unit object found, or null, and origString
- */
- _getUnitByName(uCode, origString) {
- let retUnit = null;
- let retUnitAry = this.utabs_.getUnitByName(uCode);
- if (retUnitAry && retUnitAry.length > 0) {
- retUnit = retUnitAry[0].clone();
- let mString = 'The UCUM code for ' + uCode + ' is ' + retUnit.csCode_ + '.\n' + this.vcMsgStart_ + retUnit.csCode_ + this.vcMsgEnd_;
- let dupMsg = false;
- for (let r = 0; r < this.retMsg_.length && !dupMsg; r++) dupMsg = this.retMsg_[r] === mString;
- if (!dupMsg) this.retMsg_.push(mString);
- const escapedCode = uCode.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- let rStr = new RegExp('(^|[./(])(' + escapedCode + ')($|[./)\\-\\d{])');
- const updatedOrigString = origString.replace(rStr, '$1' + retUnit.csCode_ + '$3');
- if (updatedOrigString == origString) {
- // This should not happen, if the processing has been correct. However, if it does happen, we
- // still have to change origString to signal that the input unit is invalid.
- // There is a test present to make sure this message does not appear from the top-level APIs in
- // ucumLhcUtils.js.
- // Ideally, this problem would be signalled some other way, but that would be a bigger change.
- origString += ' (Unable to update the unit expression with a suggested replacement.)';
- } else {
- origString = updatedOrigString;
- }
- }
- return [retUnit, origString];
- } // end _getUnitByName
-
- /**
- * Checks whether an otherwise unresolved unit code can be found after adding
- * square brackets, e.g., degF -> [degF]. If a bracketed unit is found,
- * origString is modified to include the suggested replacement.
- *
- * @param uCode the unit code to check
- * @param origString the original full string submitted to parseString
- * @returns an array containing the unit object found, or null, and the possibly
- * modified origString
- */
- _getUnitAfterAddingBrackets(uCode, origString) {
- let retUnit = null;
- const addBrackets = '[' + uCode + ']';
- const bracketUnit = this.utabs_.getUnitByCode(addBrackets);
- if (bracketUnit) {
- retUnit = bracketUnit.clone();
- const escapedCode = uCode.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const leadingUnitBoundary = '(^|[./(])';
- const trailingUnitBoundary = '($|[./)\\-\\d{])';
- const rStr = new RegExp(leadingUnitBoundary + '(' + escapedCode + ')' + trailingUnitBoundary);
- const updatedOrigString = origString.replace(rStr, '$1' + addBrackets + '$3');
- if (updatedOrigString == origString) {
- // This should not happen, if the processing has been correct. However, if it does happen, we
- // still have to change origString to signal that the input unit is invalid.
- // There is a test present to make sure this message does not appear from the top-level APIs in
- // ucumLhcUtils.js.
- // Ideally, this problem would be signalled some other way, but that would be a bigger change.
- origString += ' (Unable to update the unit expression with a suggested replacement.)';
- } else {
- origString = updatedOrigString;
- }
- this.retMsg_.push(`${uCode} is not a valid unit expression, but ` + `${addBrackets} is.\n` + this.vcMsgStart_ + `${addBrackets} (${retUnit.name_})${this.vcMsgEnd_}`);
- }
- return [retUnit, origString];
- } // end _getUnitAfterAddingBrackets
-
- /**
- * This method handles unit creation when an annotation is included
- * in the unit string. This basically isolates and retrieves the
- * annotation and then calls _makeUnit to try to get a unit from
- * any text that precedes or follows the annotation.
- *
- * @param uCode the string defining the unit
- * @param origString the original full string submitted to parseString
- * @returns the unit object found, or null if one could not be found
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- */
- _getUnitWithAnnotation(uCode, origString) {
- let retUnit = null;
-
- // Get the annotation and anything that precedes or follows it.
- let annoRet = this._getAnnoText(uCode, origString);
- let annoText = annoRet[0];
- let befAnnoText = annoRet[1];
- let aftAnnoText = annoRet[2];
-
- // Add the warning about annotations - just once.
-
- if (this.bracesMsg_ && this.retMsg_.indexOf(this.bracesMsg_) === -1) this.retMsg_.push(this.bracesMsg_);
-
- // If there's no text before or after the annotation, it's probably
- // something that should be interpreted as a 1, e.g., {KCT'U}.
- // HOWEVER, it could also be a case where someone used braces instead
- // of brackets, e.g., {degF} instead of [degF]. Check for that before
- // we assume it should be a 1.
- let msgLen = this.retMsg_.length;
- if (!befAnnoText && !aftAnnoText) {
- let tryBrackets = '[' + annoText.substring(1, annoText.length - 1) + ']';
- let mkUnitRet = this._makeUnit(tryBrackets, origString);
-
- // Nearly anything inside braces is valid, so we don't want to change the
- // unit, but we can put the found unit in the message as a sort of
- // warning.
- if (mkUnitRet[0]) {
- retUnit = uCode;
- this.retMsg_.push(`${annoText} is a valid unit expression, but ` + `did you mean ${tryBrackets} (${mkUnitRet[0].name_})?`);
- } else {
- // remove error message generated for trybrackets
- if (this.retMsg_.length > msgLen) {
- this.retMsg_.pop();
- }
- }
-
- // This is the case where the string is only this annotation.
- // Create and return a unit object, as we do for numeric units in
- // parseString.
- retUnit = new Unit({
- 'csCode_': annoText,
- 'ciCode_': annoText,
- 'magnitude_': 1,
- 'name_': annoText
- });
- } // end if it's only an annotation
- else {
- // if there's text before and no text after, assume the text before
- // the annotation is the unit code (with an annotation following it).
- // Call _makeUnit for the text before the annotation.
- if (befAnnoText && !aftAnnoText) {
- // make sure that what's before the annoText is not a number, e.g.,
- // /100{cells}. But f it is a number, just set the return unit to
- // the number.
- if (intUtils_.isIntegerUnit(befAnnoText)) {
- retUnit = new Unit({
- 'csCode_': befAnnoText + annoText,
- 'ciCode_': befAnnoText + annoText.toUpperCase(),
- 'magnitude_': Number(befAnnoText),
- 'name_': befAnnoText + annoText
- });
- }
- // Otherwise try to find a unit
- else {
- let mkUnitRet = this._makeUnit(befAnnoText, origString);
-
- // if a unit was returned
- if (mkUnitRet[0]) {
- retUnit = mkUnitRet[0];
- retUnit.csCode_ += annoText;
- origString = mkUnitRet[1];
- }
- // Otherwise add a not found message
- else {
- this.retMsg_.push(`Unable to find a unit for ${befAnnoText} that ` + `precedes the annotation ${annoText}.`);
- }
- }
- }
- // else if there's only text after the annotation, try for a unit
- // from the after text and assume the user put the annotation in
- // the wrong place (and tell them)
- else if (!befAnnoText && aftAnnoText) {
- // Again, test for a number and if it is a number, set the return
- // unit to the number.
- if (intUtils_.isIntegerUnit(aftAnnoText)) {
- retUnit = aftAnnoText + annoText;
- this.retMsg_.push(`The annotation ${annoText} before the ``${aftAnnoText} is invalid.\n` + this.vcMsgStart_ + retUnit + this.vcMsgEnd_);
- } else {
- let mkUnitRet = this._makeUnit(aftAnnoText, origString);
- if (mkUnitRet[0]) {
- retUnit = mkUnitRet[0];
- retUnit.csCode_ += annoText;
- origString = retUnit.csCode_;
- this.retMsg_.push(`The annotation ${annoText} before the unit ` + `code is invalid.\n` + this.vcMsgStart_ + retUnit.csCode_ + this.vcMsgEnd_);
- }
- // Otherwise add a not found message
- else {
- this.retMsg_.push(`Unable to find a unit for ${befAnnoText} that ` + `follows the annotation ${annoText}.`);
- }
- }
- }
- // else it's got text before AND after the annotation. Now what?
- // For now this is an error. This may be a case of a missing
- // operator but that is not handled yet.
- else {
- this.retMsg_.push(`Unable to find a unit for ${befAnnoText}${annoText}` + `${aftAnnoText}.\nWe are not sure how to interpret text both before ` + `and after the annotation. Sorry`);
- }
- } // else if there's text before/and or after the annotation
-
- return [retUnit, origString];
- } // end _getUnitWithAnnotations
-
- /**
- * Performs unit arithmetic for the units in the units array. That array
- * contains units/numbers and the operators (division or multiplication) to
- * be performed on each unit/unit or unit/number pair in the array. This
- * should only be called from within this class (or by test code).
- *
- * @params uArray the array that contains the units, numbers and operators
- * derived from the unit string passed in to parseString
- * @param origString the original string to be parsed; used to provide
- * context for messages
- *
- * @returns a single unit object that is the result of the unit arithmetic
- *
- * the this.retMsg_ array will be updated with any user messages
- * (informational, error or warning) generated by this or called methods
- */
- _performUnitArithmetic(uArray, origString) {
- let finalUnit = uArray[0]['un'];
- if (intUtils_.isIntegerUnit(finalUnit)) {
- finalUnit = new Unit({
- 'csCode_': finalUnit,
- 'ciCode_': finalUnit,
- 'magnitude_': Number(finalUnit),
- 'name_': finalUnit
- });
- }
- let uLen = uArray.length;
- let endProcessing = false;
- // Perform the arithmetic for the units, starting with the first 2 units.
- // We only need to do the arithmetic if we have more than one unit.
- for (let u2 = 1; u2 < uLen && !endProcessing; u2++) {
- let nextUnit = uArray[u2]['un'];
- if (intUtils_.isIntegerUnit(nextUnit)) {
- nextUnit = new Unit({
- 'csCode_': nextUnit,
- 'ciCode_': nextUnit,
- 'magnitude_': Number(nextUnit),
- 'name_': nextUnit
- });
- }
- if (nextUnit === null || typeof nextUnit !== 'number' && !nextUnit.getProperty) {
- let msgString = `Unit string (${origString}) contains unrecognized ` + 'element';
- if (nextUnit) {
- msgString += ` (${this.openEmph_}${nextUnit.toString()}` + `${this.closeEmph_})`;
- }
- msgString += '; could not parse full string. Sorry';
- this.retMsg_.push(msgString);
- endProcessing = true;
- } else {
- try {
- // Is the operation division?
- let thisOp = uArray[u2]['op'];
- let isDiv = thisOp === '/';
-
- // Perform the operation. Both the finalUnit and nextUnit
- // are unit objects.
- isDiv ? finalUnit = finalUnit.divide(nextUnit) : finalUnit = finalUnit.multiplyThese(nextUnit);
- } catch (err) {
- this.retMsg_.unshift(err.message);
- endProcessing = true;
- finalUnit = null;
- }
- } // end if we have another valid unit/number to process
- } // end do for each unit after the first one
- return finalUnit;
- } // end _performUnitArithmetic
-
- /**
- * This tests a string to see if it starts with characters and ends with
- * digits. This is used to test for an exponent on a UCUM code (or what
- * we think might be a UCUM code). This is broken out to a separate
- * function so that the regular expression can be verified to provide the
- * results we expect, in case someone changes it. (Per Paul Lynch)
- * See "Test _isCodeWithExponent method" in testUnitString.spec.js
- *
- * This particular regex has been tweaked several times. This one
- * works with the following test strings:
- * "m[H2O]-21 gives ["m[H2O]-21", "m[H2O]", "-21"]
- * "m[H2O]+21 gives ["m[H2O]+21", "m[H2O]", "+21"]
- * "m[H2O]21 gives ["m[H2O]-21", "m[H2O]", "21"]
- * "s2" gives ["s2", "s, "2"]
- * "kg" gives null
- * "m[H2O]" gives null
- * "m[H2O]23X" gives null
- *
- * @params uCode the code being tested
- * @returns an array containing: (1) the code without the exponent (or
- * trailing number); and (2) the exponent/trailing number. Returns null
- * if there is no trailing number or something follows the trailing
- * number, or if the first part is not characters.
- */
- _isCodeWithExponent(uCode) {
- let ret = [];
- let res = uCode.match(/(^[^\-\+]+?)([\-\+\d]+)$/);
-
- // If we got a return with an exponent, separate the exponent from the
- // unit and return both (as separate values)
- if (res && res[2] && res[2] !== "") {
- ret.push(res[1]);
- ret.push(res[2]);
- } // end if we got an exponent
- else {
- ret = null;
- }
- return ret;
- } // end _isCodeWithExponent
-} // end class UnitString
-
-/**
- * This function exists ONLY until the original UnitString constructor
- * is called for the first time. It's defined here in case getInstance
- * is called before the constructor. This calls the constructor.
- *
- * The constructor redefines the getInstance function to return the
- * singleton UnitString object. This is based on the UnitTables singleton
- * implementation; see more detail in the UnitTables constructor description.
- *
- * @return the singleton UnitString object.
- */
-exports.UnitString = UnitString;
-_defineProperty(UnitString, "INVALID_ANNOTATION_CHAR_MSG", 'An invalid character was found in the annotation ');
-_defineProperty(UnitString, "VALID_ANNOTATION_REGEX", /^\{[!-z|~]*\}$/);
-UnitString.getInstance = function () {
- return new UnitString();
-};
-
-/*
-// Perform the first request for the object, to set the getInstance method.
-UnitString.getInstance();
-
-*/
-
-
-},{"./config.js":62,"./prefixTables.js":66,"./ucumInternalUtils.js":68,"./unit.js":72,"./unitTables.js":74}],74:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.UnitTables = void 0;
-/**
- * This class manages Hashtables that provide references to
- * defined units.
- *
- * @author Lee Mericle, based on java version by Gunther Schadow
- *
- */
-
-var Ucum = require('./config.js').Ucum;
-class UnitTablesFactory {
- /**
- * Constructor. This creates the empty unit tables (hashes) once. After the
- * tables are created, it redefines this constructor to throw an error
- * stating that the constructor is no longer available and that the
- * getInstance function must be used. Here's a description of the first
- * and then all subsequent calls to this constructor.
- *
- * First call to constructor:
- * 1. creates OBJECT1
- * 2. initializes attributes of OBJECT1
- * 3. stores reference to OBJECT1.prototype in holdthis local variable
- * 4. redefines OBJECT1 as a function that throws an error
- * 5. defines the getInstance function (which is also defined outside of
- * the class definition - see below).
- *
- * All subsequent calls to constructor:
- * 1. throw error message referring to getInstance
- * 2. call getInstance, returns this - which is OBJECT1.
- */
- constructor() {
- /**
- * Tracks units by name
- * @type hash - key is the name;
- * value is an array of references to the Unit objects
- * with the name. More than one unit may have the same
- * name, e.g., "second", which is shared by the base unit
- * with the code = "s" and the unit with code = "'".
- */
- this.unitNames_ = {};
-
- /**
- * Tracks units by code using case-sensitive version.
- *
- * @type hash - key is the code;
- * value is the reference to the Unit object. Codes must
- * be unique.
- */
- this.unitCodes_ = {};
-
- /**
- * Keeps track of the order in which units are defined. The order is
- * important because unit definitions build on previous definitions.
- *
- * @type {Array}
- */
- this.codeOrder_ = [];
-
- /**
- * Tracks units by unit strings, e.g., cm-1
- *
- * @type hash - key is the unit string
- * value is an array of unit objects with that ciUnitString.
- */
- this.unitStrings_ = {};
-
- /**
- * Tracks units by Dimension vector
- *
- * @type hash - key is the dimension vector (not the object, just the
- * vector);
- * value is an array of references to the Unit objects
- * with that vector. More than one unit may have the same
- * unit vector, and this can be used to provide a list
- * of commensurable units.
- */
- this.unitDimensions_ = {};
-
- /**
- * Maps synonyms to units. Not built until first requested.
- *
- * @type hash - key is the synonym
- * value is an array of references to Unit objects that
- * include that synonym.
- */
- this.unitSynonyms_ = {};
-
- /*
- * Holds onto the index of the index of the dimension vector flag for
- * the base mass unit (gram). This is set when the base unit (gram) is
- * created, and is stored here so that it doesn't have to be found
- * over and over again to try to determine whether or not a unit is
- * mass-based (for mole<->mass conversions)
- *
- * @type integer
- */
- this.massDimIndex_ = 0;
-
- /**
- * Map of indices in the dimension vector to base unit symbols.
- */
- this.dimVecIndexToBaseUnit_ = {};
- }
-
- /**
- * Provides the number of unit objects written to the tables, using the
- * codes table since codes must be unique.
- *
- * @returns count of the number of unit objects in the unitCodes_ table.
- */
- unitsCount() {
- return Object.keys(this.unitCodes_).length;
- }
-
- /**
- * Adds a Unit object to the tables.
- *
- * @param theUnit the unit to be added
- * @returns nothing
- * @throws passes on an error if one is thrown by the called functions for
- * a problem with the unit code or unit name
- */
- addUnit(theUnit) {
- let uName = theUnit['name_'];
- if (uName) {
- this.addUnitName(theUnit);
- }
- this.addUnitCode(theUnit);
- this.addUnitString(theUnit);
- try {
- if (theUnit['dim_'].getProperty('dimVec_')) this.addUnitDimension(theUnit);
- } catch (err) {
- // do nothing - throws error if the property is null
- // and that's OK here.
- }
- if (theUnit.isBase_) {
- const dimVec = theUnit.dim_.dimVec_;
- let nonZeroIndex;
- for (let i = 0, len = dimVec.length; nonZeroIndex == undefined && i < len; ++i) {
- if (dimVec[i] != 0) nonZeroIndex = i;
- }
- this.dimVecIndexToBaseUnit_[nonZeroIndex] = theUnit.csCode_;
- }
- } // end addUnit
-
- /**
- * Adds a Unit object to the unitNames_ table. More than one unit
- * can have the same name, e.g., the two units with the name "second",
- * where the code for one of them is 's' and the code for the other is
- * "'". Because of this, an array of unit objects is stored for the
- * name. In most cases it will be an array of one object, but this
- * clarifies that there may be more than one.
- *
- * @param theUnit the unit to be added
- * @returns nothing
- * @throws an error if the unit has no name
- */
- addUnitName(theUnit) {
- let uName = theUnit['name_'];
- if (uName) {
- if (this.unitNames_[uName]) this.unitNames_[uName].push(theUnit);else this.unitNames_[uName] = [theUnit];
- } else throw new Error('UnitTables.addUnitName called for a unit with no name. ' + `Unit code = ${theUnit['csCode_']}.`);
- } // end addUnitName
-
- /**
- * Adds a Unit object to the unitCodes_, unitUcCodes_, unitLcCodes_ and
- * codeOrder_ tables. This also sets the mass dimension index when the
- * base mass unit (gram) is read.
- *
- * @param theUnit the unit to be added
- * @returns nothing
- * @throws an error if the unitCodes_ table already contains a unit with
- * the code
- */
- addUnitCode(theUnit) {
- let uCode = theUnit['csCode_'];
- if (uCode) {
- if (this.unitCodes_[uCode]) throw new Error(`UnitTables.addUnitCode called, already contains entry for ` + `unit with code = ${uCode}`);else {
- this.unitCodes_[uCode] = theUnit;
- this.codeOrder_.push(uCode);
- if (uCode == 'g') {
- let dimVec = theUnit.dim_.dimVec_;
- let d = 0;
- for (; d < dimVec.length && dimVec[d] < 1; d++);
- this.massDimIndex_ = d;
- }
- }
- } else throw new Error('UnitTables.addUnitCode called for unit that has ' + 'no code.');
- } // end addUnitCode
-
- /**
- * Adds a unit object to the unitStrings_ table. More than one unit
- * can have the same string, so an array of unit objects is stored
- * for the string. The unit string is the string that creates a non-base
- * unit, e.g., a Newton has a unit code of N, a name of Newton, and a
- * unitString of kg.m/s2.
- *
- * If the unit has no string, nothing is stored and no error is reported.
- *
- * @param theUnit the unit to be added
- * @returns nothing
- */
- addUnitString(theUnit) {
- let uString = null;
- if (Ucum.caseSensitive_ == true) uString = theUnit['csUnitString_'];else uString = theUnit['ciUnitString_'];
- if (uString) {
- let uEntry = {
- mag: theUnit['baseFactorStr_'],
- unit: theUnit
- };
- if (this.unitStrings_[uString]) this.unitStrings_[uString].push(uEntry);else this.unitStrings_[uString] = [uEntry];
- }
- } // end addUnitString
-
- /**
- * Adds a Unit object to the unitDimensions_ table. More than one unit
- * can have the same dimension (commensurable units have the same dimension).
- * Because of this, an array of unit objects is stored for the
- * dimension.
- *
- * @param theUnit the unit to be added
- * @returns nothing
- * @throws an error if the unit has no dimension
- */
- addUnitDimension(theUnit) {
- let uDim = theUnit['dim_'].getProperty('dimVec_');
- if (uDim) {
- if (this.unitDimensions_[uDim]) this.unitDimensions_[uDim].push(theUnit);else this.unitDimensions_[uDim] = [theUnit];
- } else throw new Error('UnitTables.addUnitDimension called for a unit with no dimension. ' + `Unit code = ${theUnit['csCode_']}.`);
- } // end addUnitDimension
-
- /**
- * Builds the unitSynonyms_ table. This is called the first time the
- * getUnitsBySynonym method is called. The table/hash contains each word
- * (once) from each synonym as well as each word from each unit name.
- *
- * Hash keys are the words. Hash values are an array of unit codes for
- * each unit that has that word in its synonyms or name.
- *
- * @returns nothing
- */
- buildUnitSynonyms() {
- for (let code in this.unitCodes_) {
- let theUnit = this.unitCodes_[code];
- let uSyns = theUnit.synonyms_;
-
- // If the current unit has synonyms, process each synonym (often multiples)
- if (uSyns) {
- let synsAry = uSyns.split(';');
- if (synsAry[0] !== '') {
- let aLen = synsAry.length;
- for (let a = 0; a < aLen; a++) {
- let theSyn = synsAry[a].trim();
-
- // call addSynonymCodes to process each word in the
- // synonym, e.g., "British fluid ounces"
- this.addSynonymCodes(code, theSyn);
- } // end do for each synonym
- } // end if the current unit has a non-null synonym attribute
- } // end if the unit has any synonyms
-
- // Now call addSynonymCodes to process each word in the unit's name
- this.addSynonymCodes(code, theUnit.name_);
- } // end do for each unit
- } // end buildUnitSynonyms
-
- /**
- * Adds unit code entries to the synonyms table for a string containing
- * one or more words to be considered as synonyms.
- *
- * @param theCode the unit code to be connected to the synonyms
- * @param theSynonyms a string containing one or more words to be
- * considered synonyms (and thus to be added to the unitSynonyms hash).
- */
- addSynonymCodes(theCode, theSynonyms) {
- let words = theSynonyms.split(' ');
- let wLen = words.length;
- for (let w = 0; w < wLen; w++) {
- let word = words[w];
-
- // if there is already a synonyms entry for the word,
- // get the array of unit codes currently assigned to
- // the word and add the code for the current word to
- // the synonyms array if it's not already there.
- if (this.unitSynonyms_[word]) {
- let synCodes = this.unitSynonyms_[word];
- if (synCodes.indexOf(theCode) === -1) {
- this.unitSynonyms_[word].push(theCode);
- }
- }
- // else there are no synonyms entry for the word. Create a
- // synonyms array for the word, setting it to contain the unit code.
- else {
- this.unitSynonyms_[word] = [theCode];
- }
- } // end do for each word in the synonyms being processed
- } // end addSynonymCodes
-
- /**
- * Returns a unit object with a case-sensitive code matching the
- * uCode parameter, or null if no unit is found with that code.
- *
- * @param uCode the code of the unit to be returned
- * @returns the unit object or null if it is not found
- */
- getUnitByCode(uCode) {
- let retUnit = null;
- if (uCode) {
- retUnit = this.unitCodes_[uCode];
- }
- return retUnit;
- }
-
- /**
- * Returns a array of unit objects based on the unit's name. Usually this
- * will be an array of one, but there may be more, since unit names are
- * not necessarily unique.
- *
- * @param uName the name of the unit to be returned. If more than one
- * unit has the same name and you only want one specific unit, append the
- * csCode of the unit you want to the end of the name, separated by the
- * Ucum.codeSep_ value, e.g., inch - [in_i] vs. inch - [in_us].
- * @returns null if no unit was found for the specified name OR an array of
- * unit objects with the specified name. Normally this will be an array
- * of one object.
- * @throws an error if no name is provided to search on
- */
- getUnitByName(uName) {
- if (uName === null || uName === undefined) {
- throw new Error('Unable to find unit by name because no name was provided.');
- }
- let sepPos = uName.indexOf(Ucum.codeSep_);
- let uCode = null;
- if (sepPos >= 1) {
- uCode = uName.substr(sepPos + Ucum.codeSep_.length);
- uName = uName.substr(0, sepPos);
- }
- let retUnits = this.unitNames_[uName];
- if (retUnits) {
- let uLen = retUnits.length;
- if (uCode && uLen > 1) {
- let i = 0;
- for (; retUnits[i].csCode_ !== uCode && i < uLen; i++);
- if (i < uLen) retUnits = [retUnits[i]];else {
- retUnits = null;
- }
- } // end if we need to find both a name and a code
- } // end if we got an array of units
- return retUnits;
- } // end getUnitByName
-
- /**
- * Returns an array of unit objects with the specified unit string.
- * The array may contain one or more unit reference objects.
- * Or none, if no units have a matching unit string (which is not
- * considered an error)
- *
- * @param name the name of the unit to be returned
- * @returns the array of unit references or null if none were found
- */
- getUnitByString(uString) {
- let retAry = null;
- if (uString) {
- retAry = this.unitStrings_[uString];
- if (retAry === undefined) retAry = null;
- }
- return retAry;
- }
-
- /**
- * Returns a array of unit objects based on the unit's dimension vector.
- *
- * @param uName the dimension vector of the units to be returned.
- *
- * @returns null if no unit was found for the specified vector OR an array of
- * one or more unit objects with the specified vector.
- * @throws an error if no vector is provided to search on
- * logs an error to the console if no unit is found
- */
- getUnitsByDimension(uDim) {
- let unitsArray = null;
- if (uDim === null || uDim === undefined) {
- throw new Error('Unable to find unit by because no dimension ' + 'vector was provided.');
- }
- unitsArray = this.unitDimensions_[uDim];
- if (unitsArray === undefined || unitsArray === null) {
- console.log(`Unable to find unit with dimension = ${uDim}`);
- }
- return unitsArray;
- } // end getUnitsByDimension
-
- /**
- * Returns a array of unit objects that include the specified synonym.
- *
- * @param uSyn the synonym of the units to be returned.
- *
- * @returns an object with two of the following three elements:
- * 'status' will be error, failed or succeeded
- * 'msg' will be included for returns with status = error or failed and
- * will explain why the request did not return any units
- * 'units' any array of unit objects with the specified synonym will be
- * returned for requests with status = succeeded
- */
- getUnitBySynonym(uSyn) {
- let retObj = {};
- let unitsArray = [];
- try {
- if (uSyn === null || uSyn === undefined) {
- retObj['status'] = 'error';
- throw new Error('Unable to find unit by synonym because no synonym ' + 'was provided.');
- }
- // If this is the first request for a unit by synonym, build the hash map
- if (Object.keys(this.unitSynonyms_).length === 0) {
- this.buildUnitSynonyms();
- }
- let foundCodes = [];
- foundCodes = this.unitSynonyms_[uSyn];
- if (foundCodes) {
- retObj['status'] = 'succeeded';
- let fLen = foundCodes.length;
- for (let f = 0; f < fLen; f++) {
- unitsArray.push(this.unitCodes_[foundCodes[f]]);
- }
- retObj['units'] = unitsArray;
- }
- if (unitsArray.length === 0) {
- retObj['status'] = 'failed';
- retObj['msg'] = `Unable to find any units with synonym = ${uSyn}`;
- }
- } catch (err) {
- retObj['msg'] = err.message;
- }
- return retObj;
- } // end getUnitBySynonym
-
- /**
- * Gets a list of all unit names in the Unit tables
- *
- * @returns an array of the unit names
- */
- getAllUnitNames() {
- return Object.keys(this.unitNames_);
- } // end getAllUnitNames
-
- /**
- * Gets a list of all unit names in the tables. Where more than one
- * unit has the same name, the unit code, in parentheses, is appended
- * to the end of the name.
- *
- * @returns {Array}
- */
- getUnitNamesList() {
- let nameList = [];
- let codes = Object.keys(this.unitCodes_);
- codes.sort(this.compareCodes);
- let uLen = codes.length;
- for (let i = 0; i < uLen; i++) {
- nameList[i] = codes[i] + Ucum.codeSep_ + this.unitCodes_[codes[i]].name_;
- } // end do for each code
- return nameList;
- }
-
- /*
- * Returns the mass dimension index
- * @returns this.massDimIndex_
- */
- getMassDimensionIndex() {
- return this.massDimIndex_;
- }
-
- /**
- * This provides a sort function for unit codes so that sorting ignores
- * square brackets and case.
- *
- * @param a first value
- * @param b second value
- * @returns -1 if a is should fall before b; otherwise 1.
- */
- compareCodes(a, b) {
- a = a.replace(/[\[\]]/g, '');
- a = a.toLowerCase();
- b = b.replace(/[\[\]]/g, '');
- b = b.toLowerCase();
- return a < b ? -1 : 1;
- }
-
- /**
- * Gets a list of all unit codes in the Unit tables
- *
- * @returns an array of the unit names
- */
- getAllUnitCodes() {
- return Object.keys(this.unitCodes_);
- } // end getAllUnitNames
-
- /**
- * This is used to get all unit objects. Currently it is used
- * to get the objects to write to the json ucum definitions file
- * that is used to provide prefix and unit definition objects for
- * conversions and validations.
- *
- * @returns an array containing all unit objects, ordered by definition
- * order
- */
- allUnitsByDef() {
- let unitsList = [];
- let uLen = this.codeOrder_.length;
- for (let u = 0; u < uLen; u++) {
- unitsList.push(this.getUnitByCode(this.codeOrder_[u]));
- }
- return unitsList;
- } // end allUnitsByDef
-
- /**
- * This is used to get all unit objects, ordered by unit name. Currently it
- * is used to create a csv list of all units.
- * @param sep separator character (or string) to be used to separate each
- * column in the output. Optional, defaults to '|' if not specified.
- * (Used to use ; but the synonyms use that extensively). Don't use a
- * comma or any other punctuation found in the output data.
- * @returns a buffer containing all unit objects, ordered by name
- * order
- */
- allUnitsByName(cols, sep) {
- if (sep === undefined || sep === null) sep = '|';
- let unitBuff = '';
- let unitsList = this.getAllUnitNames();
- let uLen = unitsList.length;
- let cLen = cols.length;
- for (let i = 0; i < uLen; i++) {
- let nameRecs = this.getUnitByName(unitsList[i]);
- for (let u = 0; u < nameRecs.length; u++) {
- let rec = nameRecs[u];
- for (let c = 0; c < cLen; c++) {
- if (c > 0) unitBuff += sep;
- if (cols[c] === 'dim_') {
- if (rec.dim_ !== null && rec.dim_ !== undefined && rec.dim_.dimVec_ instanceof Array) unitBuff += '[' + rec.dim_.dimVec_.join(',') + ']';else unitBuff += '';
- } else {
- let cbuf = rec[cols[c]];
- if (typeof cbuf === 'string') unitBuff += cbuf.replace(/[\n\r]/g, ' ');else unitBuff += cbuf;
- }
- } // end do for each column requested
- unitBuff += '\r\n';
- } // end do for each unit in the unit names array
- }
- return unitBuff;
- } // end allUnitsByName
-
- /**
- * This creates a list of all units in the tables. It uses the byCode
- * table, and uses the codeOrder_ array to determine the order in which
- * the units are listed.
- *
- * @param doLong boolean indicating how much to output. If true, all data
- * from the unit objects is included. If false, only a few major values
- * are included.
- * @param sep separator character (or string) to be used to separate each
- * column in the output. Optional, defaults to '|' if not specified.
- * (Used to use ; but the synonyms use that extensively).
- * @returns {string} buffer containing all the listings
- */
- printUnits(doLong, sep) {
- if (doLong === undefined) doLong = false;
- if (sep === undefined) sep = '|';
- let codeList = '';
- let uLen = this.codeOrder_.length;
- let unitString = 'csCode' + sep;
- if (doLong) {
- unitString += 'ciCode' + sep;
- }
- unitString += 'name' + sep;
- if (doLong) unitString += 'isBase' + sep;
- unitString += 'magnitude' + sep + 'dimension' + sep + 'from unit(s)' + sep + 'value' + sep + 'function' + sep;
- if (doLong) unitString += 'property' + sep + 'printSymbol' + sep + 'synonyms' + sep + 'source' + sep + 'class' + sep + 'isMetric' + sep + 'variable' + sep + 'isSpecial' + sep + 'isAbitrary' + sep;
- unitString += 'comment';
- codeList = unitString + '\n';
- for (let u = 0; u < uLen; u++) {
- let curUnit = this.getUnitByCode(this.codeOrder_[u]);
- unitString = this.codeOrder_[u] + sep;
- if (doLong) {
- unitString += curUnit.getProperty('ciCode_') + sep;
- }
- unitString += curUnit.getProperty('name_') + sep;
- if (doLong) {
- if (curUnit.getProperty('isBase_')) unitString += 'true' + sep;else unitString += 'false' + sep;
- }
- unitString += curUnit.getProperty('magnitude_') + sep;
- let curDim = curUnit.getProperty('dim_');
- if (curDim) {
- unitString += curDim.dimVec_ + sep;
- } else {
- unitString += 'null' + sep;
- }
- if (curUnit.csUnitString_) unitString += curUnit.csUnitString_ + sep + curUnit.baseFactor_ + sep;else unitString += 'null' + sep + 'null' + sep;
- if (curUnit.cnv_) unitString += curUnit.cnv_ + sep;else unitString += 'null' + sep;
- if (doLong) {
- unitString += curUnit.getProperty('property_') + sep + curUnit.getProperty('printSymbol_') + sep + curUnit.getProperty('synonyms_') + sep + curUnit.getProperty('source_') + sep + curUnit.getProperty('class_') + sep + curUnit.getProperty('isMetric_') + sep + curUnit.getProperty('variable_') + sep + curUnit.getProperty('isSpecial_') + sep + curUnit.getProperty('isArbitrary_') + sep;
- }
- if (curUnit.defError_) unitString += 'problem parsing this one, deferred to later.';
- codeList += unitString + '\n';
- }
- return codeList;
- }
-} // end UnitTablesFactory
-
-// Create a singleton instance and (to preserve the existing API) an object that
-// provides that instance via getInstance().
-var unitTablesInstance = new UnitTablesFactory();
-const UnitTables = exports.UnitTables = {
- getInstance: function () {
- return unitTablesInstance;
- }
-};
-
-
-},{"./config.js":62}],75:[function(require,module,exports){
-/**
- * @license
- * MIT License
- *
- * Copyright (c) 2014-present, Lee Byron and other contributors.
- *
- * 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' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Immutable = {}));
-})(this, (function (exports) { 'use strict';
-
- var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@';
- /**
- * True if `maybeIndexed` is a Collection.Indexed, or any of its subclasses.
- *
- * ```js
- * import { isIndexed, Map, List, Stack, Set } from 'immutable';
- *
- * isIndexed([]); // false
- * isIndexed({}); // false
- * isIndexed(Map()); // false
- * isIndexed(List()); // true
- * isIndexed(Stack()); // true
- * isIndexed(Set()); // false
- * ```
- */
- function isIndexed(maybeIndexed) {
- return Boolean(maybeIndexed &&
- // @ts-expect-error: maybeIndexed is typed as `{}`, need to change in 6.0 to `maybeIndexed && typeof maybeIndexed === 'object' && IS_INDEXED_SYMBOL in maybeIndexed`
- maybeIndexed[IS_INDEXED_SYMBOL]);
- }
-
- var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@';
- /**
- * True if `maybeKeyed` is a Collection.Keyed, or any of its subclasses.
- *
- * ```js
- * import { isKeyed, Map, List, Stack } from 'immutable';
- *
- * isKeyed([]); // false
- * isKeyed({}); // false
- * isKeyed(Map()); // true
- * isKeyed(List()); // false
- * isKeyed(Stack()); // false
- * ```
- */
- function isKeyed(maybeKeyed) {
- return Boolean(maybeKeyed &&
- // @ts-expect-error: maybeKeyed is typed as `{}`, need to change in 6.0 to `maybeKeyed && typeof maybeKeyed === 'object' && IS_KEYED_SYMBOL in maybeKeyed`
- maybeKeyed[IS_KEYED_SYMBOL]);
- }
-
- /**
- * True if `maybeAssociative` is either a Keyed or Indexed Collection.
- *
- * ```js
- * import { isAssociative, Map, List, Stack, Set } from 'immutable';
- *
- * isAssociative([]); // false
- * isAssociative({}); // false
- * isAssociative(Map()); // true
- * isAssociative(List()); // true
- * isAssociative(Stack()); // true
- * isAssociative(Set()); // false
- * ```
- */
- function isAssociative(maybeAssociative) {
- return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
- }
-
- // Note: value is unchanged to not break immutable-devtools.
- var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@';
- /**
- * True if `maybeCollection` is a Collection, or any of its subclasses.
- *
- * ```js
- * import { isCollection, Map, List, Stack } from 'immutable';
- *
- * isCollection([]); // false
- * isCollection({}); // false
- * isCollection(Map()); // true
- * isCollection(List()); // true
- * isCollection(Stack()); // true
- * ```
- */
- function isCollection(maybeCollection) {
- return Boolean(maybeCollection &&
- // @ts-expect-error: maybeCollection is typed as `{}`, need to change in 6.0 to `maybeCollection && typeof maybeCollection === 'object' && IS_COLLECTION_SYMBOL in maybeCollection`
- maybeCollection[IS_COLLECTION_SYMBOL]);
- }
-
- var Collection = function Collection(value) {
- // eslint-disable-next-line no-constructor-return
- return isCollection(value) ? value : Seq(value);
- };
-
- var KeyedCollection = /*@__PURE__*/(function (Collection) {
- function KeyedCollection(value) {
- // eslint-disable-next-line no-constructor-return
- return isKeyed(value) ? value : KeyedSeq(value);
- }
-
- if ( Collection ) KeyedCollection.__proto__ = Collection;
- KeyedCollection.prototype = Object.create( Collection && Collection.prototype );
- KeyedCollection.prototype.constructor = KeyedCollection;
-
- return KeyedCollection;
- }(Collection));
-
- var IndexedCollection = /*@__PURE__*/(function (Collection) {
- function IndexedCollection(value) {
- // eslint-disable-next-line no-constructor-return
- return isIndexed(value) ? value : IndexedSeq(value);
- }
-
- if ( Collection ) IndexedCollection.__proto__ = Collection;
- IndexedCollection.prototype = Object.create( Collection && Collection.prototype );
- IndexedCollection.prototype.constructor = IndexedCollection;
-
- return IndexedCollection;
- }(Collection));
-
- var SetCollection = /*@__PURE__*/(function (Collection) {
- function SetCollection(value) {
- // eslint-disable-next-line no-constructor-return
- return isCollection(value) && !isAssociative(value) ? value : SetSeq(value);
- }
-
- if ( Collection ) SetCollection.__proto__ = Collection;
- SetCollection.prototype = Object.create( Collection && Collection.prototype );
- SetCollection.prototype.constructor = SetCollection;
-
- return SetCollection;
- }(Collection));
-
- Collection.Keyed = KeyedCollection;
- Collection.Indexed = IndexedCollection;
- Collection.Set = SetCollection;
-
- var ITERATE_KEYS = 0;
- var ITERATE_VALUES = 1;
- var ITERATE_ENTRIES = 2;
- // TODO Symbol is widely available in modern JavaScript environments, clean this
- var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
- var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
- // @ts-expect-error: properties are not supported in buble
- var Iterator = function Iterator(next) {
- // @ts-expect-error: properties are not supported in buble
- this.next = next;
- };
- Iterator.prototype.toString = function toString () {
- return '[Iterator]';
- };
- // @ts-expect-error: static properties are not supported in buble
- Iterator.KEYS = ITERATE_KEYS;
- // @ts-expect-error: static properties are not supported in buble
- Iterator.VALUES = ITERATE_VALUES;
- // @ts-expect-error: static properties are not supported in buble
- Iterator.ENTRIES = ITERATE_ENTRIES;
- // @ts-expect-error: properties are not supported in buble
- Iterator.prototype.inspect = Iterator.prototype.toSource = function () {
- return this.toString();
- };
- // @ts-expect-error don't know how to type this
- Iterator.prototype[ITERATOR_SYMBOL] = function () {
- return this;
- };
- function iteratorValue(type, k, v, iteratorResult) {
- var value = type === ITERATE_KEYS ? k : type === ITERATE_VALUES ? v : [k, v];
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- iteratorResult
- ? (iteratorResult.value = value)
- : (iteratorResult = {
- // @ts-expect-error ensure value is not undefined
- value: value,
- done: false,
- });
- return iteratorResult;
- }
- function iteratorDone() {
- return { value: undefined, done: true };
- }
- function hasIterator(maybeIterable) {
- if (Array.isArray(maybeIterable)) {
- // IE11 trick as it does not support `Symbol.iterator`
- return true;
- }
- return !!getIteratorFn(maybeIterable);
- }
- function isIterator(maybeIterator) {
- return !!(maybeIterator &&
- // @ts-expect-error: maybeIterator is typed as `{}`
- typeof maybeIterator.next === 'function');
- }
- function getIterator(iterable) {
- var iteratorFn = getIteratorFn(iterable);
- return iteratorFn && iteratorFn.call(iterable);
- }
- function getIteratorFn(iterable) {
- var iteratorFn = iterable &&
- // @ts-expect-error: maybeIterator is typed as `{}`
- ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
- // @ts-expect-error: maybeIterator is typed as `{}`
- iterable[FAUX_ITERATOR_SYMBOL]);
- if (typeof iteratorFn === 'function') {
- return iteratorFn;
- }
- }
- function isEntriesIterable(maybeIterable) {
- var iteratorFn = getIteratorFn(maybeIterable);
- // @ts-expect-error: maybeIterator is typed as `{}`
- return iteratorFn && iteratorFn === maybeIterable.entries;
- }
- function isKeysIterable(maybeIterable) {
- var iteratorFn = getIteratorFn(maybeIterable);
- // @ts-expect-error: maybeIterator is typed as `{}`
- return iteratorFn && iteratorFn === maybeIterable.keys;
- }
-
- // Used for setting prototype methods that IE8 chokes on.
- var DELETE = 'delete';
- // Constants describing the size of trie nodes.
- var SHIFT = 5; // Resulted in best performance after ______?
- var SIZE = 1 << SHIFT;
- var MASK = SIZE - 1;
- // A consistent shared value representing "not set" which equals nothing other
- // than itself, and nothing that could be provided externally.
- var NOT_SET = {};
- // Boolean references, Rough equivalent of `bool &`.
- function MakeRef() {
- return { value: false };
- }
- function SetRef(ref) {
- if (ref) {
- ref.value = true;
- }
- }
- // A function which returns a value representing an "owner" for transient writes
- // to tries. The return value will only ever equal itself, and will not equal
- // the return of any subsequent call of this function.
- function OwnerID() { }
- function ensureSize(iter) {
- // @ts-expect-error size should exists on Collection
- if (iter.size === undefined) {
- // @ts-expect-error size should exists on Collection, __iterate does exist on Collection
- iter.size = iter.__iterate(returnTrue);
- }
- // @ts-expect-error size should exists on Collection
- return iter.size;
- }
- function wrapIndex(iter, index) {
- // This implements "is array index" which the ECMAString spec defines as:
- //
- // A String property name P is an array index if and only if
- // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
- // to 2^32−1.
- //
- // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
- if (typeof index !== 'number') {
- var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
- if ('' + uint32Index !== index || uint32Index === 4294967295) {
- return NaN;
- }
- index = uint32Index;
- }
- return index < 0 ? ensureSize(iter) + index : index;
- }
- function returnTrue() {
- return true;
- }
- function wholeSlice(begin, end, size) {
- return (((begin === 0 && !isNeg(begin)) ||
- (size !== undefined && begin <= -size)) &&
- (end === undefined || (size !== undefined && end >= size)));
- }
- function resolveBegin(begin, size) {
- return resolveIndex(begin, size, 0);
- }
- function resolveEnd(end, size) {
- return resolveIndex(end, size, size);
- }
- function resolveIndex(index, size, defaultIndex) {
- // Sanitize indices using this shorthand for ToInt32(argument)
- // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
- return index === undefined
- ? defaultIndex
- : isNeg(index)
- ? size === Infinity
- ? size
- : Math.max(0, size + index) | 0
- : size === undefined || size === index
- ? index
- : Math.min(size, index) | 0;
- }
- function isNeg(value) {
- // Account for -0 which is negative, but not less than 0.
- return value < 0 || (value === 0 && 1 / value === -Infinity);
- }
-
- var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@';
- /**
- * True if `maybeRecord` is a Record.
- */
- function isRecord(maybeRecord) {
- return Boolean(maybeRecord &&
- // @ts-expect-error: maybeRecord is typed as `{}`, need to change in 6.0 to `maybeRecord && typeof maybeRecord === 'object' && IS_RECORD_SYMBOL in maybeRecord`
- maybeRecord[IS_RECORD_SYMBOL]);
- }
-
- /**
- * True if `maybeImmutable` is an Immutable Collection or Record.
- *
- * Note: Still returns true even if the collections is within a `withMutations()`.
- *
- * ```js
- * import { isImmutable, Map, List, Stack } from 'immutable';
- * isImmutable([]); // false
- * isImmutable({}); // false
- * isImmutable(Map()); // true
- * isImmutable(List()); // true
- * isImmutable(Stack()); // true
- * isImmutable(Map().asMutable()); // true
- * ```
- */
- function isImmutable(maybeImmutable) {
- return isCollection(maybeImmutable) || isRecord(maybeImmutable);
- }
-
- var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@';
- function isOrdered(maybeOrdered) {
- return Boolean(maybeOrdered &&
- // @ts-expect-error: maybeOrdered is typed as `{}`, need to change in 6.0 to `maybeOrdered && typeof maybeOrdered === 'object' && IS_ORDERED_SYMBOL in maybeOrdered`
- maybeOrdered[IS_ORDERED_SYMBOL]);
- }
-
- var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@';
- /**
- * True if `maybeSeq` is a Seq.
- */
- function isSeq(maybeSeq) {
- return Boolean(maybeSeq &&
- // @ts-expect-error: maybeSeq is typed as `{}`, need to change in 6.0 to `maybeSeq && typeof maybeSeq === 'object' && MAYBE_SEQ_SYMBOL in maybeSeq`
- maybeSeq[IS_SEQ_SYMBOL]);
- }
-
- var hasOwnProperty = Object.prototype.hasOwnProperty;
-
- function isArrayLike(value) {
- if (Array.isArray(value) || typeof value === 'string') {
- return true;
- }
- // @ts-expect-error "Type 'unknown' is not assignable to type 'boolean'" : convert to Boolean
- return (value &&
- typeof value === 'object' &&
- // @ts-expect-error check that `'length' in value &&`
- Number.isInteger(value.length) &&
- // @ts-expect-error check that `'length' in value &&`
- value.length >= 0 &&
- // @ts-expect-error check that `'length' in value &&`
- (value.length === 0
- ? // Only {length: 0} is considered Array-like.
- Object.keys(value).length === 1
- : // An object is only Array-like if it has a property where the last value
- // in the array-like may be found (which could be undefined).
- // @ts-expect-error check that `'length' in value &&`
- value.hasOwnProperty(value.length - 1)));
- }
-
- var Seq = /*@__PURE__*/(function (Collection) {
- function Seq(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptySequence()
- : isImmutable(value)
- ? value.toSeq()
- : seqFromValue(value);
- }
-
- if ( Collection ) Seq.__proto__ = Collection;
- Seq.prototype = Object.create( Collection && Collection.prototype );
- Seq.prototype.constructor = Seq;
-
- Seq.prototype.toSeq = function toSeq () {
- return this;
- };
-
- Seq.prototype.toString = function toString () {
- return this.__toString('Seq {', '}');
- };
-
- Seq.prototype.cacheResult = function cacheResult () {
- if (!this._cache && this.__iterateUncached) {
- this._cache = this.entrySeq().toArray();
- this.size = this._cache.length;
- }
- return this;
- };
-
- // abstract __iterateUncached(fn, reverse)
-
- Seq.prototype.__iterate = function __iterate (fn, reverse) {
- var cache = this._cache;
- if (cache) {
- var size = cache.length;
- var i = 0;
- while (i !== size) {
- var entry = cache[reverse ? size - ++i : i++];
- if (fn(entry[1], entry[0], this) === false) {
- break;
- }
- }
- return i;
- }
- return this.__iterateUncached(fn, reverse);
- };
-
- // abstract __iteratorUncached(type, reverse)
-
- Seq.prototype.__iterator = function __iterator (type, reverse) {
- var cache = this._cache;
- if (cache) {
- var size = cache.length;
- var i = 0;
- return new Iterator(function () {
- if (i === size) {
- return iteratorDone();
- }
- var entry = cache[reverse ? size - ++i : i++];
- return iteratorValue(type, entry[0], entry[1]);
- });
- }
- return this.__iteratorUncached(type, reverse);
- };
-
- return Seq;
- }(Collection));
-
- var KeyedSeq = /*@__PURE__*/(function (Seq) {
- function KeyedSeq(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptySequence().toKeyedSeq()
- : isCollection(value)
- ? isKeyed(value)
- ? value.toSeq()
- : value.fromEntrySeq()
- : isRecord(value)
- ? value.toSeq()
- : keyedSeqFromValue(value);
- }
-
- if ( Seq ) KeyedSeq.__proto__ = Seq;
- KeyedSeq.prototype = Object.create( Seq && Seq.prototype );
- KeyedSeq.prototype.constructor = KeyedSeq;
-
- KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () {
- return this;
- };
-
- return KeyedSeq;
- }(Seq));
-
- var IndexedSeq = /*@__PURE__*/(function (Seq) {
- function IndexedSeq(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptySequence()
- : isCollection(value)
- ? isKeyed(value)
- ? value.entrySeq()
- : value.toIndexedSeq()
- : isRecord(value)
- ? value.toSeq().entrySeq()
- : indexedSeqFromValue(value);
- }
-
- if ( Seq ) IndexedSeq.__proto__ = Seq;
- IndexedSeq.prototype = Object.create( Seq && Seq.prototype );
- IndexedSeq.prototype.constructor = IndexedSeq;
-
- IndexedSeq.of = function of (/*...values*/) {
- return IndexedSeq(arguments);
- };
-
- IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () {
- return this;
- };
-
- IndexedSeq.prototype.toString = function toString () {
- return this.__toString('Seq [', ']');
- };
-
- return IndexedSeq;
- }(Seq));
-
- var SetSeq = /*@__PURE__*/(function (Seq) {
- function SetSeq(value) {
- // eslint-disable-next-line no-constructor-return
- return (
- isCollection(value) && !isAssociative(value) ? value : IndexedSeq(value)
- ).toSetSeq();
- }
-
- if ( Seq ) SetSeq.__proto__ = Seq;
- SetSeq.prototype = Object.create( Seq && Seq.prototype );
- SetSeq.prototype.constructor = SetSeq;
-
- SetSeq.of = function of (/*...values*/) {
- return SetSeq(arguments);
- };
-
- SetSeq.prototype.toSetSeq = function toSetSeq () {
- return this;
- };
-
- return SetSeq;
- }(Seq));
-
- Seq.isSeq = isSeq;
- Seq.Keyed = KeyedSeq;
- Seq.Set = SetSeq;
- Seq.Indexed = IndexedSeq;
-
- Seq.prototype[IS_SEQ_SYMBOL] = true;
-
- // #pragma Root Sequences
-
- var ArraySeq = /*@__PURE__*/(function (IndexedSeq) {
- function ArraySeq(array) {
- this._array = array;
- this.size = array.length;
- }
-
- if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq;
- ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
- ArraySeq.prototype.constructor = ArraySeq;
-
- ArraySeq.prototype.get = function get (index, notSetValue) {
- return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
- };
-
- ArraySeq.prototype.__iterate = function __iterate (fn, reverse) {
- var array = this._array;
- var size = array.length;
- var i = 0;
- while (i !== size) {
- var ii = reverse ? size - ++i : i++;
- if (fn(array[ii], ii, this) === false) {
- break;
- }
- }
- return i;
- };
-
- ArraySeq.prototype.__iterator = function __iterator (type, reverse) {
- var array = this._array;
- var size = array.length;
- var i = 0;
- return new Iterator(function () {
- if (i === size) {
- return iteratorDone();
- }
- var ii = reverse ? size - ++i : i++;
- return iteratorValue(type, ii, array[ii]);
- });
- };
-
- return ArraySeq;
- }(IndexedSeq));
-
- var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) {
- function ObjectSeq(object) {
- var keys = Object.keys(object).concat(
- Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []
- );
- this._object = object;
- this._keys = keys;
- this.size = keys.length;
- }
-
- if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq;
- ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
- ObjectSeq.prototype.constructor = ObjectSeq;
-
- ObjectSeq.prototype.get = function get (key, notSetValue) {
- if (notSetValue !== undefined && !this.has(key)) {
- return notSetValue;
- }
- return this._object[key];
- };
-
- ObjectSeq.prototype.has = function has (key) {
- return hasOwnProperty.call(this._object, key);
- };
-
- ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) {
- var object = this._object;
- var keys = this._keys;
- var size = keys.length;
- var i = 0;
- while (i !== size) {
- var key = keys[reverse ? size - ++i : i++];
- if (fn(object[key], key, this) === false) {
- break;
- }
- }
- return i;
- };
-
- ObjectSeq.prototype.__iterator = function __iterator (type, reverse) {
- var object = this._object;
- var keys = this._keys;
- var size = keys.length;
- var i = 0;
- return new Iterator(function () {
- if (i === size) {
- return iteratorDone();
- }
- var key = keys[reverse ? size - ++i : i++];
- return iteratorValue(type, key, object[key]);
- });
- };
-
- return ObjectSeq;
- }(KeyedSeq));
- ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true;
-
- var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) {
- function CollectionSeq(collection) {
- this._collection = collection;
- this.size = collection.length || collection.size;
- }
-
- if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq;
- CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
- CollectionSeq.prototype.constructor = CollectionSeq;
-
- CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) {
- if (reverse) {
- return this.cacheResult().__iterate(fn, reverse);
- }
- var collection = this._collection;
- var iterator = getIterator(collection);
- var iterations = 0;
- if (isIterator(iterator)) {
- var step;
- while (!(step = iterator.next()).done) {
- if (fn(step.value, iterations++, this) === false) {
- break;
- }
- }
- }
- return iterations;
- };
-
- CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) {
- if (reverse) {
- return this.cacheResult().__iterator(type, reverse);
- }
- var collection = this._collection;
- var iterator = getIterator(collection);
- if (!isIterator(iterator)) {
- return new Iterator(iteratorDone);
- }
- var iterations = 0;
- return new Iterator(function () {
- var step = iterator.next();
- return step.done ? step : iteratorValue(type, iterations++, step.value);
- });
- };
-
- return CollectionSeq;
- }(IndexedSeq));
-
- // # pragma Helper functions
-
- var EMPTY_SEQ;
-
- function emptySequence() {
- return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
- }
-
- function keyedSeqFromValue(value) {
- var seq = maybeIndexedSeqFromValue(value);
- if (seq) {
- return seq.fromEntrySeq();
- }
- if (typeof value === 'object') {
- return new ObjectSeq(value);
- }
- throw new TypeError(
- 'Expected Array or collection object of [k, v] entries, or keyed object: ' +
- value
- );
- }
-
- function indexedSeqFromValue(value) {
- var seq = maybeIndexedSeqFromValue(value);
- if (seq) {
- return seq;
- }
- throw new TypeError(
- 'Expected Array or collection object of values: ' + value
- );
- }
-
- function seqFromValue(value) {
- var seq = maybeIndexedSeqFromValue(value);
- if (seq) {
- return isEntriesIterable(value)
- ? seq.fromEntrySeq()
- : isKeysIterable(value)
- ? seq.toSetSeq()
- : seq;
- }
- if (typeof value === 'object') {
- return new ObjectSeq(value);
- }
- throw new TypeError(
- 'Expected Array or collection object of values, or keyed object: ' + value
- );
- }
-
- function maybeIndexedSeqFromValue(value) {
- return isArrayLike(value)
- ? new ArraySeq(value)
- : hasIterator(value)
- ? new CollectionSeq(value)
- : undefined;
- }
-
- function asImmutable() {
- return this.__ensureOwner();
- }
-
- function asMutable() {
- return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
- }
-
- // TODO remove in v6 as Math.imul is widely available now: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
- var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2
- ? Math.imul
- : function imul(a, b) {
- a |= 0; // int
- b |= 0; // int
- var c = a & 0xffff;
- var d = b & 0xffff;
- // Shift by 0 fixes the sign on the high part.
- return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int
- };
- // v8 has an optimization for storing 31-bit signed numbers.
- // Values which have either 00 or 11 as the high order bits qualify.
- // This function drops the highest order bit in a signed number, maintaining
- // the sign bit.
- function smi(i32) {
- return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
- }
-
- var defaultValueOf = Object.prototype.valueOf;
- function hash(o) {
- // eslint-disable-next-line eqeqeq
- if (o == null) {
- return hashNullish(o);
- }
- // @ts-expect-error don't care about object beeing typed as `{}` here
- if (typeof o.hashCode === 'function') {
- // Drop any high bits from accidentally long hash codes.
- // @ts-expect-error don't care about object beeing typed as `{}` here
- return smi(o.hashCode(o));
- }
- var v = valueOf(o);
- // eslint-disable-next-line eqeqeq
- if (v == null) {
- return hashNullish(v);
- }
- switch (typeof v) {
- case 'boolean':
- // The hash values for built-in constants are a 1 value for each 5-byte
- // shift region expect for the first, which encodes the value. This
- // reduces the odds of a hash collision for these common values.
- return v ? 0x42108421 : 0x42108420;
- case 'number':
- return hashNumber(v);
- case 'string':
- return v.length > STRING_HASH_CACHE_MIN_STRLEN
- ? cachedHashString(v)
- : hashString(v);
- case 'object':
- case 'function':
- return hashJSObj(v);
- case 'symbol':
- return hashSymbol(v);
- default:
- if (typeof v.toString === 'function') {
- return hashString(v.toString());
- }
- throw new Error('Value type ' + typeof v + ' cannot be hashed.');
- }
- }
- function hashNullish(nullish) {
- return nullish === null ? 0x42108422 : /* undefined */ 0x42108423;
- }
- // Compress arbitrarily large numbers into smi hashes.
- function hashNumber(n) {
- if (n !== n || n === Infinity) {
- return 0;
- }
- var hash = n | 0;
- if (hash !== n) {
- hash ^= n * 0xffffffff;
- }
- while (n > 0xffffffff) {
- n /= 0xffffffff;
- hash ^= n;
- }
- return smi(hash);
- }
- function cachedHashString(string) {
- var hashed = stringHashCache[string];
- if (hashed === undefined) {
- hashed = hashString(string);
- if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
- STRING_HASH_CACHE_SIZE = 0;
- stringHashCache = {};
- }
- STRING_HASH_CACHE_SIZE++;
- stringHashCache[string] = hashed;
- }
- return hashed;
- }
- // http://jsperf.com/hashing-strings
- function hashString(string) {
- // This is the hash from JVM
- // The hash code for a string is computed as
- // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
- // where s[i] is the ith character of the string and n is the length of
- // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
- // (exclusive) by dropping high bits.
- var hashed = 0;
- for (var ii = 0; ii < string.length; ii++) {
- hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
- }
- return smi(hashed);
- }
- // Per-process seed for the secondary collision hash. Never exposed nor
- // serialized, so the public `hash()` stays deterministic. An odd base in
- // [3, 2^20) keeps `base * h` exact as a double (no `Math.imul`).
- var COLLISION_HASH_BASE = ((Math.random() * 0x100000) | 1) % 0x100000 || 0x9e37;
- // Secondary hash to index entries within a `HashCollisionNode`, where every key
- // shares the same primary `hash()`. Using a different, seeded base scatters
- // crafted collision families (e.g. "Aa"/"BB", which only collide under base 31)
- // that an attacker cannot precompute without the seed. It only narrows
- // candidates — `is()` still decides equality — so non-string keys can safely
- // fall back to the (here constant) primary hash and a linear scan.
- function hashCollisionKey(key) {
- if (typeof key !== 'string') {
- return hash(key);
- }
- var hashed = 0;
- for (var ii = 0; ii < key.length; ii++) {
- hashed = (COLLISION_HASH_BASE * hashed + key.charCodeAt(ii)) | 0;
- }
- return hashed;
- }
- function hashSymbol(sym) {
- var hashed = symbolMap[sym];
- if (hashed !== undefined) {
- return hashed;
- }
- hashed = nextHash();
- symbolMap[sym] = hashed;
- return hashed;
- }
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- function hashJSObj(obj) {
- var hashed;
- if (usingWeakMap) {
- // @ts-expect-error weakMap is defined
- hashed = weakMap.get(obj);
- if (hashed !== undefined) {
- return hashed;
- }
- }
- // @ts-expect-error used for old code, will be removed
- hashed = obj[UID_HASH_KEY];
- if (hashed !== undefined) {
- return hashed;
- }
- if (!canDefineProperty) {
- // @ts-expect-error used for old code, will be removed
- hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
- if (hashed !== undefined) {
- return hashed;
- }
- hashed = getIENodeHash(obj);
- if (hashed !== undefined) {
- return hashed;
- }
- }
- hashed = nextHash();
- if (usingWeakMap) {
- // @ts-expect-error weakMap is defined
- weakMap.set(obj, hashed);
- }
- else if (isExtensible !== undefined && isExtensible(obj) === false) {
- throw new Error('Non-extensible objects are not allowed as keys.');
- }
- else if (canDefineProperty) {
- Object.defineProperty(obj, UID_HASH_KEY, {
- enumerable: false,
- configurable: false,
- writable: false,
- value: hashed,
- });
- }
- else if (obj.propertyIsEnumerable !== undefined &&
- obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
- // Since we can't define a non-enumerable property on the object
- // we'll hijack one of the less-used non-enumerable properties to
- // save our hash on it. Since this is a function it will not show up in
- // `JSON.stringify` which is what we want.
- obj.propertyIsEnumerable = function () {
- return this.constructor.prototype.propertyIsEnumerable.apply(this,
- // eslint-disable-next-line prefer-rest-params
- arguments);
- };
- // @ts-expect-error used for old code, will be removed
- obj.propertyIsEnumerable[UID_HASH_KEY] = hashed;
- // @ts-expect-error used for old code, will be removed
- }
- else if (obj.nodeType !== undefined) {
- // At this point we couldn't get the IE `uniqueID` to use as a hash
- // and we couldn't use a non-enumerable property to exploit the
- // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
- // itself.
- // @ts-expect-error used for old code, will be removed
- obj[UID_HASH_KEY] = hashed;
- }
- else {
- throw new Error('Unable to set a non-enumerable property on object.');
- }
- return hashed;
- }
- // Get references to ES5 object methods.
- var isExtensible = Object.isExtensible;
- // True if Object.defineProperty works as expected. IE8 fails this test.
- // TODO remove this as widely available https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
- var canDefineProperty = (function () {
- try {
- Object.defineProperty({}, '@', {});
- return true;
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- }
- catch (e) {
- return false;
- }
- })();
- // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
- // and avoid memory leaks from the IE cloneNode bug.
- // TODO remove this method as only used if `canDefineProperty` is false
- function getIENodeHash(node) {
- // @ts-expect-error don't care
- if (node && node.nodeType > 0) {
- // @ts-expect-error don't care
- switch (node.nodeType) {
- case 1: // Element
- // @ts-expect-error don't care
- return node.uniqueID;
- case 9: // Document
- // @ts-expect-error don't care
- return node.documentElement && node.documentElement.uniqueID;
- }
- }
- }
- function valueOf(obj) {
- return obj.valueOf !== defaultValueOf && typeof obj.valueOf === 'function'
- ? // @ts-expect-error weird the "obj" parameter as `valueOf` should not have a parameter
- obj.valueOf(obj)
- : obj;
- }
- function nextHash() {
- var nextHash = ++_objHashUID;
- if (_objHashUID & 0x40000000) {
- _objHashUID = 0;
- }
- return nextHash;
- }
- // If possible, use a WeakMap.
- // TODO using WeakMap should be true everywhere now that WeakMap is widely supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
- var usingWeakMap = typeof WeakMap === 'function';
- var weakMap;
- if (usingWeakMap) {
- weakMap = new WeakMap();
- }
- var symbolMap = Object.create(null);
- var _objHashUID = 0;
- // TODO remove string as Symbol is now widely supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
- var UID_HASH_KEY = '__immutablehash__';
- if (typeof Symbol === 'function') {
- UID_HASH_KEY = Symbol(UID_HASH_KEY);
- }
- var STRING_HASH_CACHE_MIN_STRLEN = 16;
- var STRING_HASH_CACHE_MAX_SIZE = 255;
- var STRING_HASH_CACHE_SIZE = 0;
- var stringHashCache = {};
-
- var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq) {
- function ToKeyedSequence(indexed, useKeys) {
- this._iter = indexed;
- this._useKeys = useKeys;
- this.size = indexed.size;
- }
-
- if ( KeyedSeq ) ToKeyedSequence.__proto__ = KeyedSeq;
- ToKeyedSequence.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
- ToKeyedSequence.prototype.constructor = ToKeyedSequence;
-
- ToKeyedSequence.prototype.get = function get (key, notSetValue) {
- return this._iter.get(key, notSetValue);
- };
-
- ToKeyedSequence.prototype.has = function has (key) {
- return this._iter.has(key);
- };
-
- ToKeyedSequence.prototype.valueSeq = function valueSeq () {
- return this._iter.valueSeq();
- };
-
- ToKeyedSequence.prototype.reverse = function reverse () {
- var this$1$1 = this;
-
- var reversedSequence = reverseFactory(this, true);
- if (!this._useKeys) {
- reversedSequence.valueSeq = function () { return this$1$1._iter.toSeq().reverse(); };
- }
- return reversedSequence;
- };
-
- ToKeyedSequence.prototype.map = function map (mapper, context) {
- var this$1$1 = this;
-
- var mappedSequence = mapFactory(this, mapper, context);
- if (!this._useKeys) {
- mappedSequence.valueSeq = function () { return this$1$1._iter.toSeq().map(mapper, context); };
- }
- return mappedSequence;
- };
-
- ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- return this._iter.__iterate(function (v, k) { return fn(v, k, this$1$1); }, reverse);
- };
-
- ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) {
- return this._iter.__iterator(type, reverse);
- };
-
- return ToKeyedSequence;
- }(KeyedSeq));
- ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true;
-
- var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq) {
- function ToIndexedSequence(iter) {
- this._iter = iter;
- this.size = iter.size;
- }
-
- if ( IndexedSeq ) ToIndexedSequence.__proto__ = IndexedSeq;
- ToIndexedSequence.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
- ToIndexedSequence.prototype.constructor = ToIndexedSequence;
-
- ToIndexedSequence.prototype.includes = function includes (value) {
- return this._iter.includes(value);
- };
-
- ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- var i = 0;
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- reverse && ensureSize(this);
- return this._iter.__iterate(
- function (v) { return fn(v, reverse ? this$1$1.size - ++i : i++, this$1$1); },
- reverse
- );
- };
-
- ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) {
- var this$1$1 = this;
-
- var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
- var i = 0;
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- reverse && ensureSize(this);
- return new Iterator(function () {
- var step = iterator.next();
- return step.done
- ? step
- : iteratorValue(
- type,
- reverse ? this$1$1.size - ++i : i++,
- step.value,
- step
- );
- });
- };
-
- return ToIndexedSequence;
- }(IndexedSeq));
-
- var ToSetSequence = /*@__PURE__*/(function (SetSeq) {
- function ToSetSequence(iter) {
- this._iter = iter;
- this.size = iter.size;
- }
-
- if ( SetSeq ) ToSetSequence.__proto__ = SetSeq;
- ToSetSequence.prototype = Object.create( SetSeq && SetSeq.prototype );
- ToSetSequence.prototype.constructor = ToSetSequence;
-
- ToSetSequence.prototype.has = function has (key) {
- return this._iter.includes(key);
- };
-
- ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- return this._iter.__iterate(function (v) { return fn(v, v, this$1$1); }, reverse);
- };
-
- ToSetSequence.prototype.__iterator = function __iterator (type, reverse) {
- var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
- return new Iterator(function () {
- var step = iterator.next();
- return step.done
- ? step
- : iteratorValue(type, step.value, step.value, step);
- });
- };
-
- return ToSetSequence;
- }(SetSeq));
-
- var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq) {
- function FromEntriesSequence(entries) {
- this._iter = entries;
- this.size = entries.size;
- }
-
- if ( KeyedSeq ) FromEntriesSequence.__proto__ = KeyedSeq;
- FromEntriesSequence.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
- FromEntriesSequence.prototype.constructor = FromEntriesSequence;
-
- FromEntriesSequence.prototype.entrySeq = function entrySeq () {
- return this._iter.toSeq();
- };
-
- FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- return this._iter.__iterate(function (entry) {
- // Check if entry exists first so array access doesn't throw for holes
- // in the parent iteration.
- if (entry) {
- validateEntry(entry);
- var indexedCollection = isCollection(entry);
- return fn(
- indexedCollection ? entry.get(1) : entry[1],
- indexedCollection ? entry.get(0) : entry[0],
- this$1$1
- );
- }
- }, reverse);
- };
-
- FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) {
- var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
- return new Iterator(function () {
- while (true) {
- var step = iterator.next();
- if (step.done) {
- return step;
- }
- var entry = step.value;
- // Check if entry exists first so array access doesn't throw for holes
- // in the parent iteration.
- if (entry) {
- validateEntry(entry);
- var indexedCollection = isCollection(entry);
- return iteratorValue(
- type,
- indexedCollection ? entry.get(0) : entry[0],
- indexedCollection ? entry.get(1) : entry[1],
- step
- );
- }
- }
- });
- };
-
- return FromEntriesSequence;
- }(KeyedSeq));
-
- ToIndexedSequence.prototype.cacheResult =
- ToKeyedSequence.prototype.cacheResult =
- ToSetSequence.prototype.cacheResult =
- FromEntriesSequence.prototype.cacheResult =
- cacheResultThrough;
-
- function flipFactory(collection) {
- var flipSequence = makeSequence(collection);
- flipSequence._iter = collection;
- flipSequence.size = collection.size;
- flipSequence.flip = function () { return collection; };
- flipSequence.reverse = function () {
- var reversedSequence = collection.reverse.apply(this); // super.reverse()
- reversedSequence.flip = function () { return collection.reverse(); };
- return reversedSequence;
- };
- flipSequence.has = function (key) { return collection.includes(key); };
- flipSequence.includes = function (key) { return collection.has(key); };
- flipSequence.cacheResult = cacheResultThrough;
- flipSequence.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- return collection.__iterate(function (v, k) { return fn(k, v, this$1$1) !== false; }, reverse);
- };
- flipSequence.__iteratorUncached = function (type, reverse) {
- if (type === ITERATE_ENTRIES) {
- var iterator = collection.__iterator(type, reverse);
- return new Iterator(function () {
- var step = iterator.next();
- if (!step.done) {
- var k = step.value[0];
- step.value[0] = step.value[1];
- step.value[1] = k;
- }
- return step;
- });
- }
- return collection.__iterator(
- type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
- reverse
- );
- };
- return flipSequence;
- }
-
- function mapFactory(collection, mapper, context) {
- var mappedSequence = makeSequence(collection);
- mappedSequence.size = collection.size;
- mappedSequence.has = function (key) { return collection.has(key); };
- mappedSequence.get = function (key, notSetValue) {
- var v = collection.get(key, NOT_SET);
- return v === NOT_SET
- ? notSetValue
- : mapper.call(context, v, key, collection);
- };
- mappedSequence.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- return collection.__iterate(
- function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1$1) !== false; },
- reverse
- );
- };
- mappedSequence.__iteratorUncached = function (type, reverse) {
- var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
- return new Iterator(function () {
- var step = iterator.next();
- if (step.done) {
- return step;
- }
- var entry = step.value;
- var key = entry[0];
- return iteratorValue(
- type,
- key,
- mapper.call(context, entry[1], key, collection),
- step
- );
- });
- };
- return mappedSequence;
- }
-
- function reverseFactory(collection, useKeys) {
- var reversedSequence = makeSequence(collection);
- reversedSequence._iter = collection;
- reversedSequence.size = collection.size;
- reversedSequence.reverse = function () { return collection; };
- if (collection.flip) {
- reversedSequence.flip = function () {
- var flipSequence = flipFactory(collection);
- flipSequence.reverse = function () { return collection.flip(); };
- return flipSequence;
- };
- }
- reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); };
- reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); };
- reversedSequence.includes = function (value) { return collection.includes(value); };
- reversedSequence.cacheResult = cacheResultThrough;
- reversedSequence.__iterate = function (fn, reverse) {
- var this$1$1 = this;
-
- var i = 0;
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- reverse && ensureSize(collection);
- return collection.__iterate(
- function (v, k) { return fn(v, useKeys ? k : reverse ? this$1$1.size - ++i : i++, this$1$1); },
- !reverse
- );
- };
- reversedSequence.__iterator = function (type, reverse) {
- var i = 0;
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- reverse && ensureSize(collection);
- var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse);
- return new Iterator(function () {
- var step = iterator.next();
- if (step.done) {
- return step;
- }
- var entry = step.value;
- return iteratorValue(
- type,
- // `__iterator` is an arrow function, so `this` is not the reversed
- // sequence here — read `reversedSequence.size` explicitly.
- useKeys ? entry[0] : reverse ? reversedSequence.size - ++i : i++,
- entry[1],
- step
- );
- });
- };
- return reversedSequence;
- }
-
- function filterFactory(collection, predicate, context, useKeys) {
- var filterSequence = makeSequence(collection);
- if (useKeys) {
- filterSequence.has = function (key) {
- var v = collection.get(key, NOT_SET);
- return v !== NOT_SET && !!predicate.call(context, v, key, collection);
- };
- filterSequence.get = function (key, notSetValue) {
- var v = collection.get(key, NOT_SET);
- return v !== NOT_SET && predicate.call(context, v, key, collection)
- ? v
- : notSetValue;
- };
- }
- filterSequence.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- var iterations = 0;
- collection.__iterate(function (v, k, c) {
- if (predicate.call(context, v, k, c)) {
- iterations++;
- return fn(v, useKeys ? k : iterations - 1, this$1$1);
- }
- }, reverse);
- return iterations;
- };
- filterSequence.__iteratorUncached = function (type, reverse) {
- var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
- var iterations = 0;
- return new Iterator(function () {
- while (true) {
- var step = iterator.next();
- if (step.done) {
- return step;
- }
- var entry = step.value;
- var key = entry[0];
- var value = entry[1];
- if (predicate.call(context, value, key, collection)) {
- return iteratorValue(type, useKeys ? key : iterations++, value, step);
- }
- }
- });
- };
- return filterSequence;
- }
-
- function countByFactory(collection, grouper, context) {
- var groups = Map().asMutable();
- collection.__iterate(function (v, k) {
- groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; });
- });
- return groups.asImmutable();
- }
-
- function groupByFactory(collection, grouper, context) {
- var isKeyedIter = isKeyed(collection);
- var groups = (isOrdered(collection) ? OrderedMap() : Map()).asMutable();
- collection.__iterate(function (v, k) {
- groups.update(
- grouper.call(context, v, k, collection),
- function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); }
- );
- });
- var coerce = collectionClass(collection);
- return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable();
- }
-
- function partitionFactory(collection, predicate, context) {
- var isKeyedIter = isKeyed(collection);
- var groups = [[], []];
- collection.__iterate(function (v, k) {
- groups[predicate.call(context, v, k, collection) ? 1 : 0].push(
- isKeyedIter ? [k, v] : v
- );
- });
- var coerce = collectionClass(collection);
- return groups.map(function (arr) { return reify(collection, coerce(arr)); });
- }
-
- function sliceFactory(collection, begin, end, useKeys) {
- var originalSize = collection.size;
-
- if (wholeSlice(begin, end, originalSize)) {
- return collection;
- }
-
- // begin or end can not be resolved if they were provided as negative numbers and
- // this collection's size is unknown. In that case, cache first so there is
- // a known size and these do not resolve to NaN.
- if (typeof originalSize === 'undefined' && (begin < 0 || end < 0)) {
- return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
- }
-
- var resolvedBegin = resolveBegin(begin, originalSize);
- var resolvedEnd = resolveEnd(end, originalSize);
-
- // Note: resolvedEnd is undefined when the original sequence's length is
- // unknown and this slice did not supply an end and should contain all
- // elements after resolvedBegin.
- // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
- var resolvedSize = resolvedEnd - resolvedBegin;
- var sliceSize;
- if (resolvedSize === resolvedSize) {
- sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
- }
-
- var sliceSeq = makeSequence(collection);
-
- // If collection.size is undefined, the size of the realized sliceSeq is
- // unknown at this point unless the number of items to slice is 0
- sliceSeq.size =
- sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
-
- if (!useKeys && isSeq(collection) && sliceSize >= 0) {
- sliceSeq.get = function (index, notSetValue) {
- index = wrapIndex(this, index);
- return index >= 0 && index < sliceSize
- ? collection.get(index + resolvedBegin, notSetValue)
- : notSetValue;
- };
- }
-
- sliceSeq.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- if (sliceSize === 0) {
- return 0;
- }
- if (reverse) {
- return this.cacheResult().__iterate(fn, reverse);
- }
- var skipped = 0;
- var isSkipping = true;
- var iterations = 0;
- collection.__iterate(function (v, k) {
- if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
- iterations++;
- return (
- fn(v, useKeys ? k : iterations - 1, this$1$1) !== false &&
- iterations !== sliceSize
- );
- }
- });
- return iterations;
- };
-
- sliceSeq.__iteratorUncached = function (type, reverse) {
- if (sliceSize !== 0 && reverse) {
- return this.cacheResult().__iterator(type, reverse);
- }
- // Don't bother instantiating parent iterator if taking 0.
- if (sliceSize === 0) {
- return new Iterator(iteratorDone);
- }
- var iterator = collection.__iterator(type, reverse);
- var skipped = 0;
- var iterations = 0;
- return new Iterator(function () {
- while (skipped++ < resolvedBegin) {
- iterator.next();
- }
- if (++iterations > sliceSize) {
- return iteratorDone();
- }
- var step = iterator.next();
- if (useKeys || type === ITERATE_VALUES || step.done) {
- return step;
- }
- if (type === ITERATE_KEYS) {
- return iteratorValue(type, iterations - 1, undefined, step);
- }
- return iteratorValue(type, iterations - 1, step.value[1], step);
- });
- };
-
- return sliceSeq;
- }
-
- function takeWhileFactory(collection, predicate, context) {
- var takeSequence = makeSequence(collection);
- takeSequence.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- if (reverse) {
- return this.cacheResult().__iterate(fn, reverse);
- }
- var iterations = 0;
- collection.__iterate(
- function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1$1); }
- );
- return iterations;
- };
- takeSequence.__iteratorUncached = function (type, reverse) {
- var this$1$1 = this;
-
- if (reverse) {
- return this.cacheResult().__iterator(type, reverse);
- }
- var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
- var iterating = true;
- return new Iterator(function () {
- if (!iterating) {
- return iteratorDone();
- }
- var step = iterator.next();
- if (step.done) {
- return step;
- }
- var entry = step.value;
- var k = entry[0];
- var v = entry[1];
- if (!predicate.call(context, v, k, this$1$1)) {
- iterating = false;
- return iteratorDone();
- }
- return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
- });
- };
- return takeSequence;
- }
-
- function skipWhileFactory(collection, predicate, context, useKeys) {
- var skipSequence = makeSequence(collection);
- skipSequence.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- if (reverse) {
- return this.cacheResult().__iterate(fn, reverse);
- }
- var isSkipping = true;
- var iterations = 0;
- collection.__iterate(function (v, k, c) {
- if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
- iterations++;
- return fn(v, useKeys ? k : iterations - 1, this$1$1);
- }
- });
- return iterations;
- };
- skipSequence.__iteratorUncached = function (type, reverse) {
- var this$1$1 = this;
-
- if (reverse) {
- return this.cacheResult().__iterator(type, reverse);
- }
- var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
- var skipping = true;
- var iterations = 0;
- return new Iterator(function () {
- var step;
- var k;
- var v;
- do {
- step = iterator.next();
- if (step.done) {
- if (useKeys || type === ITERATE_VALUES) {
- return step;
- }
- if (type === ITERATE_KEYS) {
- return iteratorValue(type, iterations++, undefined, step);
- }
- return iteratorValue(type, iterations++, step.value[1], step);
- }
- var entry = step.value;
- k = entry[0];
- v = entry[1];
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- skipping && (skipping = predicate.call(context, v, k, this$1$1));
- } while (skipping);
- return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
- });
- };
- return skipSequence;
- }
-
- var ConcatSeq = /*@__PURE__*/(function (Seq) {
- function ConcatSeq(iterables) {
- this._wrappedIterables = iterables.flatMap(function (iterable) {
- if (iterable._wrappedIterables) {
- return iterable._wrappedIterables;
- }
- return [iterable];
- });
- this.size = this._wrappedIterables.reduce(function (sum, iterable) {
- if (sum !== undefined) {
- var size = iterable.size;
- if (size !== undefined) {
- return sum + size;
- }
- }
- }, 0);
- this[IS_KEYED_SYMBOL] = this._wrappedIterables[0][IS_KEYED_SYMBOL];
- this[IS_INDEXED_SYMBOL] = this._wrappedIterables[0][IS_INDEXED_SYMBOL];
- this[IS_ORDERED_SYMBOL] = this._wrappedIterables[0][IS_ORDERED_SYMBOL];
- }
-
- if ( Seq ) ConcatSeq.__proto__ = Seq;
- ConcatSeq.prototype = Object.create( Seq && Seq.prototype );
- ConcatSeq.prototype.constructor = ConcatSeq;
-
- ConcatSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) {
- if (this._wrappedIterables.length === 0) {
- return;
- }
-
- if (reverse) {
- return this.cacheResult().__iterate(fn, reverse);
- }
-
- var iterableIndex = 0;
- var useKeys = isKeyed(this);
- var iteratorType = useKeys ? ITERATE_ENTRIES : ITERATE_VALUES;
- var currentIterator = this._wrappedIterables[iterableIndex].__iterator(
- iteratorType,
- reverse
- );
-
- var keepGoing = true;
- var index = 0;
- while (keepGoing) {
- var next = currentIterator.next();
- while (next.done) {
- iterableIndex++;
- if (iterableIndex === this._wrappedIterables.length) {
- return index;
- }
- currentIterator = this._wrappedIterables[iterableIndex].__iterator(
- iteratorType,
- reverse
- );
- next = currentIterator.next();
- }
- var fnResult = useKeys
- ? fn(next.value[1], next.value[0], this)
- : fn(next.value, index, this);
- keepGoing = fnResult !== false;
- index++;
- }
- return index;
- };
-
- ConcatSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) {
- var this$1$1 = this;
-
- if (this._wrappedIterables.length === 0) {
- return new Iterator(iteratorDone);
- }
-
- if (reverse) {
- return this.cacheResult().__iterator(type, reverse);
- }
-
- var iterableIndex = 0;
- var currentIterator = this._wrappedIterables[iterableIndex].__iterator(
- type,
- reverse
- );
- return new Iterator(function () {
- var next = currentIterator.next();
- while (next.done) {
- iterableIndex++;
- if (iterableIndex === this$1$1._wrappedIterables.length) {
- return next;
- }
- currentIterator = this$1$1._wrappedIterables[iterableIndex].__iterator(
- type,
- reverse
- );
- next = currentIterator.next();
- }
- return next;
- });
- };
-
- return ConcatSeq;
- }(Seq));
-
- function concatFactory(collection, values) {
- var isKeyedCollection = isKeyed(collection);
- var iters = [collection]
- .concat(values)
- .map(function (v) {
- if (!isCollection(v)) {
- v = isKeyedCollection
- ? keyedSeqFromValue(v)
- : indexedSeqFromValue(Array.isArray(v) ? v : [v]);
- } else if (isKeyedCollection) {
- v = KeyedCollection(v);
- }
- return v;
- })
- .filter(function (v) { return v.size !== 0; });
-
- if (iters.length === 0) {
- return collection;
- }
-
- if (iters.length === 1) {
- var singleton = iters[0];
- if (
- singleton === collection ||
- (isKeyedCollection && isKeyed(singleton)) ||
- (isIndexed(collection) && isIndexed(singleton))
- ) {
- return singleton;
- }
- }
-
- return new ConcatSeq(iters);
- }
-
- function flattenFactory(collection, depth, useKeys) {
- var flatSequence = makeSequence(collection);
- flatSequence.__iterateUncached = function (fn, reverse) {
- if (reverse) {
- return this.cacheResult().__iterate(fn, reverse);
- }
- var iterations = 0;
- var stopped = false;
- function flatDeep(iter, currentDepth) {
- iter.__iterate(function (v, k) {
- if ((!depth || currentDepth < depth) && isCollection(v)) {
- flatDeep(v, currentDepth + 1);
- } else {
- iterations++;
- if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) {
- stopped = true;
- }
- }
- return !stopped;
- }, reverse);
- }
- flatDeep(collection, 0);
- return iterations;
- };
- flatSequence.__iteratorUncached = function (type, reverse) {
- if (reverse) {
- return this.cacheResult().__iterator(type, reverse);
- }
- var iterator = collection.__iterator(type, reverse);
- var stack = [];
- var iterations = 0;
- return new Iterator(function () {
- while (iterator) {
- var step = iterator.next();
- if (step.done !== false) {
- iterator = stack.pop();
- continue;
- }
- var v = step.value;
- if (type === ITERATE_ENTRIES) {
- v = v[1];
- }
- if ((!depth || stack.length < depth) && isCollection(v)) {
- stack.push(iterator);
- iterator = v.__iterator(type, reverse);
- } else {
- return useKeys ? step : iteratorValue(type, iterations++, v, step);
- }
- }
- return iteratorDone();
- });
- };
- return flatSequence;
- }
-
- function flatMapFactory(collection, mapper, context) {
- var coerce = collectionClass(collection);
- return collection
- .toSeq()
- .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); })
- .flatten(true);
- }
-
- function interposeFactory(collection, separator) {
- var interposedSequence = makeSequence(collection);
- interposedSequence.size = collection.size && collection.size * 2 - 1;
- interposedSequence.__iterateUncached = function (fn, reverse) {
- var this$1$1 = this;
-
- var iterations = 0;
- collection.__iterate(
- function (v) { return (!iterations || fn(separator, iterations++, this$1$1) !== false) &&
- fn(v, iterations++, this$1$1) !== false; },
- reverse
- );
- return iterations;
- };
- interposedSequence.__iteratorUncached = function (type, reverse) {
- var iterator = collection.__iterator(ITERATE_VALUES, reverse);
- var iterations = 0;
- var step;
- return new Iterator(function () {
- if (!step || iterations % 2) {
- step = iterator.next();
- if (step.done) {
- return step;
- }
- }
- return iterations % 2
- ? iteratorValue(type, iterations++, separator)
- : iteratorValue(type, iterations++, step.value, step);
- });
- };
- return interposedSequence;
- }
-
- function sortFactory(collection, comparator, mapper) {
- if (!comparator) {
- comparator = defaultComparator;
- }
- var isKeyedCollection = isKeyed(collection);
- var index = 0;
- var entries = collection
- .toSeq()
- .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; })
- .valueSeq()
- .toArray();
- entries
- .sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; })
- .forEach(
- isKeyedCollection
- ? function (v, i) {
- entries[i].length = 2;
- }
- : function (v, i) {
- entries[i] = v[1];
- }
- );
- return isKeyedCollection
- ? KeyedSeq(entries)
- : isIndexed(collection)
- ? IndexedSeq(entries)
- : SetSeq(entries);
- }
-
- function maxFactory(collection, comparator, mapper) {
- if (!comparator) {
- comparator = defaultComparator;
- }
- if (mapper) {
- var entry = collection
- .toSeq()
- .map(function (v, k) { return [v, mapper(v, k, collection)]; })
- .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); });
- return entry && entry[0];
- }
- return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); });
- }
-
- function maxCompare(comparator, a, b) {
- var comp = comparator(b, a);
- // b is considered the new max if the comparator declares them equal, but
- // they are not equal and b is in fact a nullish value.
- return (
- (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) ||
- comp > 0
- );
- }
-
- function zipWithFactory(keyIter, zipper, iters, zipAll) {
- var zipSequence = makeSequence(keyIter);
- var sizes = new ArraySeq(iters).map(function (i) { return i.size; });
- zipSequence.size = zipAll ? sizes.max() : sizes.min();
- // Note: this a generic base implementation of __iterate in terms of
- // __iterator which may be more generically useful in the future.
- zipSequence.__iterate = function (fn, reverse) {
- /* generic:
- var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
- var step;
- var iterations = 0;
- while (!(step = iterator.next()).done) {
- iterations++;
- if (fn(step.value[1], step.value[0], this) === false) {
- break;
- }
- }
- return iterations;
- */
- // indexed:
- var iterator = this.__iterator(ITERATE_VALUES, reverse);
- var step;
- var iterations = 0;
- while (!(step = iterator.next()).done) {
- if (fn(step.value, iterations++, this) === false) {
- break;
- }
- }
- return iterations;
- };
- zipSequence.__iteratorUncached = function (type, reverse) {
- var iterators = iters.map(
- function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); }
- );
- var iterations = 0;
- var isDone = false;
- return new Iterator(function () {
- var steps;
- if (!isDone) {
- steps = iterators.map(function (i) { return i.next(); });
- isDone = zipAll
- ? steps.every(function (s) { return s.done; })
- : steps.some(function (s) { return s.done; });
- }
- if (isDone) {
- return iteratorDone();
- }
- return iteratorValue(
- type,
- iterations++,
- zipper.apply(
- null,
- steps.map(function (s) { return s.value; })
- )
- );
- });
- };
- return zipSequence;
- }
-
- // #pragma Helper Functions
-
- function reify(iter, seq) {
- return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
- }
-
- function validateEntry(entry) {
- if (entry !== Object(entry)) {
- throw new TypeError('Expected [K, V] tuple: ' + entry);
- }
- }
-
- function collectionClass(collection) {
- return isKeyed(collection)
- ? KeyedCollection
- : isIndexed(collection)
- ? IndexedCollection
- : SetCollection;
- }
-
- function makeSequence(collection) {
- return Object.create(
- (isKeyed(collection)
- ? KeyedSeq
- : isIndexed(collection)
- ? IndexedSeq
- : SetSeq
- ).prototype
- );
- }
-
- function cacheResultThrough() {
- if (this._iter.cacheResult) {
- this._iter.cacheResult();
- this.size = this._iter.size;
- return this;
- }
- return Seq.prototype.cacheResult.call(this);
- }
-
- function defaultComparator(a, b) {
- if (a === undefined && b === undefined) {
- return 0;
- }
-
- if (a === undefined) {
- return 1;
- }
-
- if (b === undefined) {
- return -1;
- }
-
- return a > b ? 1 : a < b ? -1 : 0;
- }
-
- /**
- * True if `maybeValue` is a JavaScript Object which has *both* `equals()`
- * and `hashCode()` methods.
- *
- * Any two instances of *value objects* can be compared for value equality with
- * `Immutable.is()` and can be used as keys in a `Map` or members in a `Set`.
- */
- function isValueObject(maybeValue) {
- return Boolean(maybeValue &&
- // @ts-expect-error: maybeValue is typed as `{}`
- typeof maybeValue.equals === 'function' &&
- // @ts-expect-error: maybeValue is typed as `{}`
- typeof maybeValue.hashCode === 'function');
- }
-
- /**
- * An extension of the "same-value" algorithm as [described for use by ES6 Map
- * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
- *
- * NaN is considered the same as NaN, however -0 and 0 are considered the same
- * value, which is different from the algorithm described by
- * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
- *
- * This is extended further to allow Objects to describe the values they
- * represent, by way of `valueOf` or `equals` (and `hashCode`).
- *
- * Note: because of this extension, the key equality of Immutable.Map and the
- * value equality of Immutable.Set will differ from ES6 Map and Set.
- *
- * ### Defining custom values
- *
- * The easiest way to describe the value an object represents is by implementing
- * `valueOf`. For example, `Date` represents a value by returning a unix
- * timestamp for `valueOf`:
- *
- * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
- * var date2 = new Date(1234567890000);
- * date1.valueOf(); // 1234567890000
- * assert( date1 !== date2 );
- * assert( Immutable.is( date1, date2 ) );
- *
- * Note: overriding `valueOf` may have other implications if you use this object
- * where JavaScript expects a primitive, such as implicit string coercion.
- *
- * For more complex types, especially collections, implementing `valueOf` may
- * not be performant. An alternative is to implement `equals` and `hashCode`.
- *
- * `equals` takes another object, presumably of similar type, and returns true
- * if it is equal. Equality is symmetrical, so the same result should be
- * returned if this and the argument are flipped.
- *
- * assert( a.equals(b) === b.equals(a) );
- *
- * `hashCode` returns a 32bit integer number representing the object which will
- * be used to determine how to store the value object in a Map or Set. You must
- * provide both or neither methods, one must not exist without the other.
- *
- * Also, an important relationship between these methods must be upheld: if two
- * values are equal, they *must* return the same hashCode. If the values are not
- * equal, they might have the same hashCode; this is called a hash collision,
- * and while undesirable for performance reasons, it is acceptable.
- *
- * if (a.equals(b)) {
- * assert( a.hashCode() === b.hashCode() );
- * }
- *
- * All Immutable collections are Value Objects: they implement `equals()`
- * and `hashCode()`.
- */
- function is(valueA, valueB) {
- if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
- return true;
- }
- if (!valueA || !valueB) {
- return false;
- }
- if (typeof valueA.valueOf === 'function' &&
- typeof valueB.valueOf === 'function') {
- valueA = valueA.valueOf();
- valueB = valueB.valueOf();
- if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
- return true;
- }
- if (!valueA || !valueB) {
- return false;
- }
- }
- return !!(isValueObject(valueA) &&
- isValueObject(valueB) &&
- valueA.equals(valueB));
- }
-
- function update$1(collection, key, notSetValue, updater) {
- return updateIn(
- // @ts-expect-error Index signature for type string is missing in type V[]
- collection, [key], notSetValue, updater);
- }
-
- function merge$1() {
- var iters = [], len = arguments.length;
- while ( len-- ) iters[ len ] = arguments[ len ];
-
- return mergeIntoKeyedWith(this, iters);
- }
-
- function mergeWith$1(merger) {
- var iters = [], len = arguments.length - 1;
- while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
-
- if (typeof merger !== 'function') {
- throw new TypeError('Invalid merger function: ' + merger);
- }
- return mergeIntoKeyedWith(this, iters, merger);
- }
-
- function mergeIntoKeyedWith(collection, collections, merger) {
- var iters = [];
- for (var ii = 0; ii < collections.length; ii++) {
- var collection$1 = KeyedCollection(collections[ii]);
- if (collection$1.size !== 0) {
- iters.push(collection$1);
- }
- }
- if (iters.length === 0) {
- return collection;
- }
- if (
- collection.toSeq().size === 0 &&
- !collection.__ownerID &&
- iters.length === 1
- ) {
- return isRecord(collection)
- ? collection // Record is empty and will not be updated: return the same instance
- : collection.constructor(iters[0]);
- }
- return collection.withMutations(function (collection) {
- var mergeIntoCollection = merger
- ? function (value, key) {
- update$1(collection, key, NOT_SET, function (oldVal) { return oldVal === NOT_SET ? value : merger(oldVal, value, key); }
- );
- }
- : function (value, key) {
- collection.set(key, value);
- };
- for (var ii = 0; ii < iters.length; ii++) {
- iters[ii].forEach(mergeIntoCollection);
- }
- });
- }
-
- var toString = Object.prototype.toString;
- function isPlainObject(value) {
- // The base prototype's toString deals with Argument objects and native namespaces like Math
- if (!value ||
- typeof value !== 'object' ||
- toString.call(value) !== '[object Object]') {
- return false;
- }
- var proto = Object.getPrototypeOf(value);
- if (proto === null) {
- return true;
- }
- // Iteratively going up the prototype chain is needed for cross-realm environments (differing contexts, iframes, etc)
- var parentProto = proto;
- var nextProto = Object.getPrototypeOf(proto);
- while (nextProto !== null) {
- parentProto = nextProto;
- nextProto = Object.getPrototypeOf(parentProto);
- }
- return parentProto === proto;
- }
-
- /**
- * Returns true if the value is a potentially-persistent data structure, either
- * provided by Immutable.js or a plain Array or Object.
- */
- function isDataStructure(value) {
- return (typeof value === 'object' &&
- (isImmutable(value) || Array.isArray(value) || isPlainObject(value)));
- }
-
- function isProtoKey(key) {
- return (typeof key === 'string' && (key === '__proto__' || key === 'constructor'));
- }
-
- // http://jsperf.com/copy-array-inline
- function arrCopy(arr, offset) {
- offset = offset || 0;
- var len = Math.max(0, arr.length - offset);
- var newArr = new Array(len);
- for (var ii = 0; ii < len; ii++) {
- // @ts-expect-error We may want to guard for undefined values with `if (arr[ii + offset] !== undefined`, but ths should not happen by design
- newArr[ii] = arr[ii + offset];
- }
- return newArr;
- }
-
- function shallowCopy(from) {
- if (Array.isArray(from)) {
- return arrCopy(from);
- }
- var to = {};
- for (var key in from) {
- if (isProtoKey(key)) {
- continue;
- }
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
- return to;
- }
-
- function merge(collection) {
- var sources = [], len = arguments.length - 1;
- while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
-
- return mergeWithSources(collection, sources);
- }
-
- function mergeWith(merger, collection) {
- var sources = [], len = arguments.length - 2;
- while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
-
- return mergeWithSources(collection, sources, merger);
- }
-
- function mergeDeep$1(collection) {
- var sources = [], len = arguments.length - 1;
- while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
-
- return mergeDeepWithSources(collection, sources);
- }
-
- function mergeDeepWith$1(merger, collection) {
- var sources = [], len = arguments.length - 2;
- while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
-
- return mergeDeepWithSources(collection, sources, merger);
- }
-
- function mergeDeepWithSources(collection, sources, merger) {
- return mergeWithSources(collection, sources, deepMergerWith(merger));
- }
-
- function mergeWithSources(collection, sources, merger) {
- if (!isDataStructure(collection)) {
- throw new TypeError(
- 'Cannot merge into non-data-structure value: ' + collection
- );
- }
- if (isImmutable(collection)) {
- return typeof merger === 'function' && collection.mergeWith
- ? collection.mergeWith.apply(collection, [ merger ].concat( sources ))
- : collection.merge
- ? collection.merge.apply(collection, sources)
- : collection.concat.apply(collection, sources);
- }
- var isArray = Array.isArray(collection);
- var merged = collection;
- var Collection = isArray ? IndexedCollection : KeyedCollection;
- var mergeItem = isArray
- ? function (value) {
- // Copy on write
- if (merged === collection) {
- merged = shallowCopy(merged);
- }
- merged.push(value);
- }
- : function (value, key) {
- if (isProtoKey(key)) {
- return;
- }
-
- var hasVal = hasOwnProperty.call(merged, key);
- var nextVal =
- hasVal && merger ? merger(merged[key], value, key) : value;
- if (!hasVal || nextVal !== merged[key]) {
- // Copy on write
- if (merged === collection) {
- merged = shallowCopy(merged);
- }
- merged[key] = nextVal;
- }
- };
- for (var i = 0; i < sources.length; i++) {
- Collection(sources[i]).forEach(mergeItem);
- }
- return merged;
- }
-
- function deepMergerWith(merger) {
- function deepMerger(oldValue, newValue, key) {
- return isDataStructure(oldValue) &&
- isDataStructure(newValue) &&
- areMergeable(oldValue, newValue)
- ? mergeWithSources(oldValue, [newValue], deepMerger)
- : merger
- ? merger(oldValue, newValue, key)
- : newValue;
- }
- return deepMerger;
- }
-
- /**
- * It's unclear what the desired behavior is for merging two collections that
- * fall into separate categories between keyed, indexed, or set-like, so we only
- * consider them mergeable if they fall into the same category.
- */
- function areMergeable(oldDataStructure, newDataStructure) {
- var oldSeq = Seq(oldDataStructure);
- var newSeq = Seq(newDataStructure);
- // This logic assumes that a sequence can only fall into one of the three
- // categories mentioned above (since there's no `isSetLike()` method).
- return (
- isIndexed(oldSeq) === isIndexed(newSeq) &&
- isKeyed(oldSeq) === isKeyed(newSeq)
- );
- }
-
- function mergeDeep() {
- var iters = [], len = arguments.length;
- while ( len-- ) iters[ len ] = arguments[ len ];
-
- return mergeDeepWithSources(this, iters);
- }
-
- function mergeDeepWith(merger) {
- var iters = [], len = arguments.length - 1;
- while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
-
- return mergeDeepWithSources(this, iters, merger);
- }
-
- function mergeDeepIn(keyPath) {
- var iters = [], len = arguments.length - 1;
- while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
-
- return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); }
- );
- }
-
- function mergeIn(keyPath) {
- var iters = [], len = arguments.length - 1;
- while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
-
- return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); });
- }
-
- /**
- * Returns a copy of the collection with the value at the key path set to the
- * provided value.
- *
- * A functional alternative to `collection.setIn(keypath)` which will also
- * work with plain Objects and Arrays.
- */
- function setIn$1(collection, keyPath, value) {
- return updateIn(collection, keyPath, NOT_SET, function () { return value; });
- }
-
- function setIn(keyPath, v) {
- return setIn$1(this, keyPath, v);
- }
-
- function update(key, notSetValue, updater) {
- return arguments.length === 1
- ? key(this)
- : update$1(this, key, notSetValue, updater);
- }
-
- function updateIn$1(keyPath, notSetValue, updater) {
- return updateIn(this, keyPath, notSetValue, updater);
- }
-
- function wasAltered() {
- return this.__altered;
- }
-
- function withMutations(fn) {
- var mutable = this.asMutable();
- fn(mutable);
- return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
- }
-
- var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@';
- /**
- * True if `maybeMap` is a Map.
- *
- * Also true for OrderedMaps.
- */
- function isMap(maybeMap) {
- return Boolean(maybeMap &&
- // @ts-expect-error: maybeMap is typed as `{}`, need to change in 6.0 to `maybeMap && typeof maybeMap === 'object' && IS_MAP_SYMBOL in maybeMap`
- maybeMap[IS_MAP_SYMBOL]);
- }
-
- function invariant(condition, error) {
- if (!condition)
- { throw new Error(error); }
- }
-
- function assertNotInfinite(size) {
- invariant(size !== Infinity, 'Cannot perform this action with an infinite size.');
- }
-
- var Map = /*@__PURE__*/(function (KeyedCollection) {
- function Map(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptyMap()
- : isMap(value) && !isOrdered(value)
- ? value
- : emptyMap().withMutations(function (map) {
- var iter = KeyedCollection(value);
- assertNotInfinite(iter.size);
- iter.forEach(function (v, k) { return map.set(k, v); });
- });
- }
-
- if ( KeyedCollection ) Map.__proto__ = KeyedCollection;
- Map.prototype = Object.create( KeyedCollection && KeyedCollection.prototype );
- Map.prototype.constructor = Map;
-
- Map.prototype.toString = function toString () {
- return this.__toString('Map {', '}');
- };
-
- // @pragma Access
-
- Map.prototype.get = function get (k, notSetValue) {
- return this._root
- ? this._root.get(0, undefined, k, notSetValue)
- : notSetValue;
- };
-
- // @pragma Modification
-
- Map.prototype.set = function set (k, v) {
- return updateMap(this, k, v);
- };
-
- Map.prototype.remove = function remove (k) {
- return updateMap(this, k, NOT_SET);
- };
-
- Map.prototype.deleteAll = function deleteAll (keys) {
- var collection = Collection(keys);
-
- if (collection.size === 0) {
- return this;
- }
-
- return this.withMutations(function (map) {
- collection.forEach(function (key) { return map.remove(key); });
- });
- };
-
- Map.prototype.clear = function clear () {
- if (this.size === 0) {
- return this;
- }
- if (this.__ownerID) {
- this.size = 0;
- this._root = null;
- this.__hash = undefined;
- this.__altered = true;
- return this;
- }
- return emptyMap();
- };
-
- // @pragma Composition
-
- Map.prototype.sort = function sort (comparator) {
- // Late binding
- return OrderedMap(sortFactory(this, comparator));
- };
-
- Map.prototype.sortBy = function sortBy (mapper, comparator) {
- // Late binding
- return OrderedMap(sortFactory(this, comparator, mapper));
- };
-
- Map.prototype.map = function map (mapper, context) {
- var this$1$1 = this;
-
- return this.withMutations(function (map) {
- map.forEach(function (value, key) {
- map.set(key, mapper.call(context, value, key, this$1$1));
- });
- });
- };
-
- // @pragma Mutability
-
- Map.prototype.__iterator = function __iterator (type, reverse) {
- return new MapIterator(this, type, reverse);
- };
-
- Map.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- var iterations = 0;
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- this._root &&
- this._root.iterate(function (entry) {
- iterations++;
- return fn(entry[1], entry[0], this$1$1);
- }, reverse);
- return iterations;
- };
-
- Map.prototype.__ensureOwner = function __ensureOwner (ownerID) {
- if (ownerID === this.__ownerID) {
- return this;
- }
- if (!ownerID) {
- if (this.size === 0) {
- return emptyMap();
- }
- this.__ownerID = ownerID;
- this.__altered = false;
- return this;
- }
- return makeMap(this.size, this._root, ownerID, this.__hash);
- };
-
- return Map;
- }(KeyedCollection));
-
- Map.isMap = isMap;
-
- var MapPrototype = Map.prototype;
- MapPrototype[IS_MAP_SYMBOL] = true;
- MapPrototype[DELETE] = MapPrototype.remove;
- MapPrototype.removeAll = MapPrototype.deleteAll;
- MapPrototype.setIn = setIn;
- MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn;
- MapPrototype.update = update;
- MapPrototype.updateIn = updateIn$1;
- MapPrototype.merge = MapPrototype.concat = merge$1;
- MapPrototype.mergeWith = mergeWith$1;
- MapPrototype.mergeDeep = mergeDeep;
- MapPrototype.mergeDeepWith = mergeDeepWith;
- MapPrototype.mergeIn = mergeIn;
- MapPrototype.mergeDeepIn = mergeDeepIn;
- MapPrototype.withMutations = withMutations;
- MapPrototype.wasAltered = wasAltered;
- MapPrototype.asImmutable = asImmutable;
- MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable;
- MapPrototype['@@transducer/step'] = function (result, arr) {
- return result.set(arr[0], arr[1]);
- };
- MapPrototype['@@transducer/result'] = function (obj) {
- return obj.asImmutable();
- };
-
- // #pragma Trie Nodes
-
- var ArrayMapNode = function ArrayMapNode(ownerID, entries) {
- this.ownerID = ownerID;
- this.entries = entries;
- };
-
- ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
- var entries = this.entries;
- for (var ii = 0, len = entries.length; ii < len; ii++) {
- if (is(key, entries[ii][0])) {
- return entries[ii][1];
- }
- }
- return notSetValue;
- };
-
- ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
- var removed = value === NOT_SET;
-
- var entries = this.entries;
- var idx = 0;
- var len = entries.length;
- for (; idx < len; idx++) {
- if (is(key, entries[idx][0])) {
- break;
- }
- }
- var exists = idx < len;
-
- if (exists ? entries[idx][1] === value : removed) {
- return this;
- }
-
- SetRef(didAlter);
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- (removed || !exists) && SetRef(didChangeSize);
-
- if (removed && entries.length === 1) {
- return; // undefined
- }
-
- if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
- return createNodes(ownerID, entries, key, value);
- }
-
- var isEditable = ownerID && ownerID === this.ownerID;
- var newEntries = isEditable ? entries : arrCopy(entries);
-
- if (exists) {
- if (removed) {
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- idx === len - 1
- ? newEntries.pop()
- : (newEntries[idx] = newEntries.pop());
- } else {
- newEntries[idx] = [key, value];
- }
- } else {
- newEntries.push([key, value]);
- }
-
- if (isEditable) {
- this.entries = newEntries;
- return this;
- }
-
- return new ArrayMapNode(ownerID, newEntries);
- };
-
- var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) {
- this.ownerID = ownerID;
- this.bitmap = bitmap;
- this.nodes = nodes;
- };
-
- BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
- if (keyHash === undefined) {
- keyHash = hash(key);
- }
- var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK);
- var bitmap = this.bitmap;
- return (bitmap & bit) === 0
- ? notSetValue
- : this.nodes[popCount(bitmap & (bit - 1))].get(
- shift + SHIFT,
- keyHash,
- key,
- notSetValue
- );
- };
-
- BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
- if (keyHash === undefined) {
- keyHash = hash(key);
- }
- var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
- var bit = 1 << keyHashFrag;
- var bitmap = this.bitmap;
- var exists = (bitmap & bit) !== 0;
-
- if (!exists && value === NOT_SET) {
- return this;
- }
-
- var idx = popCount(bitmap & (bit - 1));
- var nodes = this.nodes;
- var node = exists ? nodes[idx] : undefined;
- var newNode = updateNode(
- node,
- ownerID,
- shift + SHIFT,
- keyHash,
- key,
- value,
- didChangeSize,
- didAlter
- );
-
- if (newNode === node) {
- return this;
- }
-
- if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
- return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
- }
-
- if (
- exists &&
- !newNode &&
- nodes.length === 2 &&
- isLeafNode(nodes[idx ^ 1])
- ) {
- return nodes[idx ^ 1];
- }
-
- if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
- return newNode;
- }
-
- var isEditable = ownerID && ownerID === this.ownerID;
- var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit;
- var newNodes = exists
- ? newNode
- ? setAt(nodes, idx, newNode, isEditable)
- : spliceOut(nodes, idx, isEditable)
- : spliceIn(nodes, idx, newNode, isEditable);
-
- if (isEditable) {
- this.bitmap = newBitmap;
- this.nodes = newNodes;
- return this;
- }
-
- return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
- };
-
- var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) {
- this.ownerID = ownerID;
- this.count = count;
- this.nodes = nodes;
- };
-
- HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
- if (keyHash === undefined) {
- keyHash = hash(key);
- }
- var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
- var node = this.nodes[idx];
- return node
- ? node.get(shift + SHIFT, keyHash, key, notSetValue)
- : notSetValue;
- };
-
- HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
- if (keyHash === undefined) {
- keyHash = hash(key);
- }
- var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
- var removed = value === NOT_SET;
- var nodes = this.nodes;
- var node = nodes[idx];
-
- if (removed && !node) {
- return this;
- }
-
- var newNode = updateNode(
- node,
- ownerID,
- shift + SHIFT,
- keyHash,
- key,
- value,
- didChangeSize,
- didAlter
- );
- if (newNode === node) {
- return this;
- }
-
- var newCount = this.count;
- if (!node) {
- newCount++;
- } else if (!newNode) {
- newCount--;
- if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
- return packNodes(ownerID, nodes, newCount, idx);
- }
- }
-
- var isEditable = ownerID && ownerID === this.ownerID;
- var newNodes = setAt(nodes, idx, newNode, isEditable);
-
- if (isEditable) {
- this.count = newCount;
- this.nodes = newNodes;
- return this;
- }
-
- return new HashArrayMapNode(ownerID, newCount, newNodes);
- };
-
- /**
- * Trie leaf gathering entries whose keys all share the same 32-bit `hash()`.
- * The trie routes by hash, so colliding keys cannot be separated and land here
- * in a flat `entries` array, disambiguated by `is()`.
- *
- * To guard against hash-flooding DoS (CWE-407), large buckets build a secondary
- * index keyed by a per-process seeded hash (`hashCollisionKey`). `is()` still
- * decides equality, so the index can only ever narrow candidates, never lose a key.
- */
- var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) {
- this.ownerID = ownerID;
- this.keyHash = keyHash;
- this.entries = entries;
- // Lazy `{ [secondaryHash]: number[] }`, built only past
- // MIN_HASH_COLLISION_INDEX_SIZE so small buckets keep their linear path.
- this._index = undefined;
- };
-
- // Returns the position of `key` in `this.entries`, or -1. Uses the secondary
- // index when present; builds it only when `buildIndex` is true (reads and
- // transient inserts, where the node is reused so the O(n) build amortizes).
- // Persistent inserts already pay an O(n) copy, so a throwaway index is skipped.
- HashCollisionNode.prototype._positionOf = function _positionOf (key, buildIndex) {
- var entries = this.entries;
- var index = this._index;
- if (
- index === undefined &&
- buildIndex &&
- entries.length >= MIN_HASH_COLLISION_INDEX_SIZE
- ) {
- index = this._buildIndex();
- }
- if (index !== undefined) {
- var positions = index[hashCollisionKey(key)];
- if (positions !== undefined) {
- for (var jj = 0; jj < positions.length; jj++) {
- var ii = positions[jj];
- if (is(key, entries[ii][0])) {
- return ii;
- }
- }
- }
- return -1;
- }
- for (var ii$1 = 0, len = entries.length; ii$1 < len; ii$1++) {
- if (is(key, entries[ii$1][0])) {
- return ii$1;
- }
- }
- return -1;
- };
-
- // Builds and memoizes the secondary index. A plain object, not `Map` — which
- // in this module resolves to the *Immutable* Map, not the native one.
- HashCollisionNode.prototype._buildIndex = function _buildIndex () {
- var index = Object.create(null);
- var entries = this.entries;
- for (var ii = 0, len = entries.length; ii < len; ii++) {
- var secondaryHash = hashCollisionKey(entries[ii][0]);
- var positions = index[secondaryHash];
- if (positions !== undefined) {
- positions.push(ii);
- } else {
- index[secondaryHash] = [ii];
- }
- }
- this._index = index;
- return index;
- };
-
- HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
- var idx = this._positionOf(key, true);
- return idx === -1 ? notSetValue : this.entries[idx][1];
- };
-
- HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
- if (keyHash === undefined) {
- keyHash = hash(key);
- }
-
- var removed = value === NOT_SET;
-
- if (keyHash !== this.keyHash) {
- if (removed) {
- return this;
- }
- SetRef(didAlter);
- SetRef(didChangeSize);
- return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
- }
-
- var entries = this.entries;
- var len = entries.length;
- var isEditable = ownerID && ownerID === this.ownerID;
- var foundIdx = this._positionOf(key, isEditable);
- var idx = foundIdx === -1 ? len : foundIdx;
- var exists = foundIdx !== -1;
-
- if (exists ? entries[idx][1] === value : removed) {
- return this;
- }
-
- SetRef(didAlter);
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- (removed || !exists) && SetRef(didChangeSize);
-
- if (removed && len === 2) {
- return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
- }
-
- var newEntries = isEditable ? entries : arrCopy(entries);
-
- if (exists) {
- if (removed) {
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- idx === len - 1
- ? newEntries.pop()
- : (newEntries[idx] = newEntries.pop());
- // The swap-pop reshuffles positions; drop the stale index (rebuilt lazily).
- if (isEditable) {
- this._index = undefined;
- }
- } else {
- // Same key, same position: the index stays valid.
- newEntries[idx] = [key, value];
- }
- } else {
- newEntries.push([key, value]);
- // Keep the index in sync on the transient insert path. Persistent inserts
- // return a fresh node below whose index rebuilds lazily, so skip them.
- if (isEditable && this._index !== undefined) {
- var secondaryHash = hashCollisionKey(key);
- var positions = this._index[secondaryHash];
- if (positions !== undefined) {
- positions.push(len);
- } else {
- this._index[secondaryHash] = [len];
- }
- }
- }
-
- if (isEditable) {
- this.entries = newEntries;
- return this;
- }
-
- return new HashCollisionNode(ownerID, this.keyHash, newEntries);
- };
-
- var ValueNode = function ValueNode(ownerID, keyHash, entry) {
- this.ownerID = ownerID;
- this.keyHash = keyHash;
- this.entry = entry;
- };
-
- ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
- return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
- };
-
- ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
- var removed = value === NOT_SET;
- var keyMatch = is(key, this.entry[0]);
- if (keyMatch ? value === this.entry[1] : removed) {
- return this;
- }
-
- SetRef(didAlter);
-
- if (removed) {
- SetRef(didChangeSize);
- return; // undefined
- }
-
- if (keyMatch) {
- if (ownerID && ownerID === this.ownerID) {
- this.entry[1] = value;
- return this;
- }
- return new ValueNode(ownerID, this.keyHash, [key, value]);
- }
-
- SetRef(didChangeSize);
- return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
- };
-
- // #pragma Iterators
-
- ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate =
- function (fn, reverse) {
- var entries = this.entries;
- for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
- if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
- return false;
- }
- }
- };
-
- BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate =
- function (fn, reverse) {
- var nodes = this.nodes;
- for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
- var node = nodes[reverse ? maxIndex - ii : ii];
- if (node && node.iterate(fn, reverse) === false) {
- return false;
- }
- }
- };
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- ValueNode.prototype.iterate = function (fn, reverse) {
- return fn(this.entry);
- };
-
- var MapIterator = /*@__PURE__*/(function (Iterator) {
- function MapIterator(map, type, reverse) {
- this._type = type;
- this._reverse = reverse;
- this._stack = map._root && mapIteratorFrame(map._root);
- }
-
- if ( Iterator ) MapIterator.__proto__ = Iterator;
- MapIterator.prototype = Object.create( Iterator && Iterator.prototype );
- MapIterator.prototype.constructor = MapIterator;
-
- MapIterator.prototype.next = function next () {
- var type = this._type;
- var stack = this._stack;
- while (stack) {
- var node = stack.node;
- var index = stack.index++;
- var maxIndex = (void 0);
- if (node.entry) {
- if (index === 0) {
- return mapIteratorValue(type, node.entry);
- }
- } else if (node.entries) {
- maxIndex = node.entries.length - 1;
- if (index <= maxIndex) {
- return mapIteratorValue(
- type,
- node.entries[this._reverse ? maxIndex - index : index]
- );
- }
- } else {
- maxIndex = node.nodes.length - 1;
- if (index <= maxIndex) {
- var subNode = node.nodes[this._reverse ? maxIndex - index : index];
- if (subNode) {
- if (subNode.entry) {
- return mapIteratorValue(type, subNode.entry);
- }
- stack = this._stack = mapIteratorFrame(subNode, stack);
- }
- continue;
- }
- }
- stack = this._stack = this._stack.__prev;
- }
- return iteratorDone();
- };
-
- return MapIterator;
- }(Iterator));
-
- function mapIteratorValue(type, entry) {
- return iteratorValue(type, entry[0], entry[1]);
- }
-
- function mapIteratorFrame(node, prev) {
- return {
- node: node,
- index: 0,
- __prev: prev,
- };
- }
-
- function makeMap(size, root, ownerID, hash) {
- var map = Object.create(MapPrototype);
- map.size = size;
- map._root = root;
- map.__ownerID = ownerID;
- map.__hash = hash;
- map.__altered = false;
- return map;
- }
-
- var EMPTY_MAP;
- function emptyMap() {
- return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
- }
-
- function updateMap(map, k, v) {
- var newRoot;
- var newSize;
- if (!map._root) {
- if (v === NOT_SET) {
- return map;
- }
- newSize = 1;
- newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
- } else {
- var didChangeSize = MakeRef();
- var didAlter = MakeRef();
- newRoot = updateNode(
- map._root,
- map.__ownerID,
- 0,
- undefined,
- k,
- v,
- didChangeSize,
- didAlter
- );
- if (!didAlter.value) {
- return map;
- }
- newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0);
- }
- if (map.__ownerID) {
- map.size = newSize;
- map._root = newRoot;
- map.__hash = undefined;
- map.__altered = true;
- return map;
- }
- return newRoot ? makeMap(newSize, newRoot) : emptyMap();
- }
-
- function updateNode(
- node,
- ownerID,
- shift,
- keyHash,
- key,
- value,
- didChangeSize,
- didAlter
- ) {
- if (!node) {
- if (value === NOT_SET) {
- return node;
- }
- SetRef(didAlter);
- SetRef(didChangeSize);
- return new ValueNode(ownerID, keyHash, [key, value]);
- }
- return node.update(
- ownerID,
- shift,
- keyHash,
- key,
- value,
- didChangeSize,
- didAlter
- );
- }
-
- function isLeafNode(node) {
- return (
- node.constructor === ValueNode || node.constructor === HashCollisionNode
- );
- }
-
- function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
- if (node.keyHash === keyHash) {
- return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
- }
-
- var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
- var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
-
- var newNode;
- var nodes =
- idx1 === idx2
- ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]
- : ((newNode = new ValueNode(ownerID, keyHash, entry)),
- idx1 < idx2 ? [node, newNode] : [newNode, node]);
-
- return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
- }
-
- function createNodes(ownerID, entries, key, value) {
- if (!ownerID) {
- ownerID = new OwnerID();
- }
- var node = new ValueNode(ownerID, hash(key), [key, value]);
- for (var ii = 0; ii < entries.length; ii++) {
- var entry = entries[ii];
- node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
- }
- return node;
- }
-
- function packNodes(ownerID, nodes, count, excluding) {
- var bitmap = 0;
- var packedII = 0;
- var packedNodes = new Array(count);
- for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
- var node = nodes[ii];
- if (node !== undefined && ii !== excluding) {
- bitmap |= bit;
- packedNodes[packedII++] = node;
- }
- }
- return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
- }
-
- function expandNodes(ownerID, nodes, bitmap, including, node) {
- var count = 0;
- var expandedNodes = new Array(SIZE);
- for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
- expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
- }
- expandedNodes[including] = node;
- return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
- }
-
- function popCount(x) {
- x -= (x >> 1) & 0x55555555;
- x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
- x = (x + (x >> 4)) & 0x0f0f0f0f;
- x += x >> 8;
- x += x >> 16;
- return x & 0x7f;
- }
-
- function setAt(array, idx, val, canEdit) {
- var newArray = canEdit ? array : arrCopy(array);
- newArray[idx] = val;
- return newArray;
- }
-
- function spliceIn(array, idx, val, canEdit) {
- var newLen = array.length + 1;
- if (canEdit && idx + 1 === newLen) {
- array[idx] = val;
- return array;
- }
- var newArray = new Array(newLen);
- var after = 0;
- for (var ii = 0; ii < newLen; ii++) {
- if (ii === idx) {
- newArray[ii] = val;
- after = -1;
- } else {
- newArray[ii] = array[ii + after];
- }
- }
- return newArray;
- }
-
- function spliceOut(array, idx, canEdit) {
- var newLen = array.length - 1;
- if (canEdit && idx === newLen) {
- array.pop();
- return array;
- }
- var newArray = new Array(newLen);
- var after = 0;
- for (var ii = 0; ii < newLen; ii++) {
- if (ii === idx) {
- after = 1;
- }
- newArray[ii] = array[ii + after];
- }
- return newArray;
- }
-
- var MAX_ARRAY_MAP_SIZE = SIZE / 4;
- var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
- var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
-
- // Above this many colliding entries, a `HashCollisionNode` builds a seeded
- // secondary index instead of scanning linearly. Kept small so the rare,
- // naturally-occurring collision buckets stay overhead-free, while adversarial
- // hash-flooding (thousands of keys sharing one hash) degrades gracefully.
- var MIN_HASH_COLLISION_INDEX_SIZE = 16;
-
- function coerceKeyPath(keyPath) {
- if (isArrayLike(keyPath) && typeof keyPath !== 'string') {
- return keyPath;
- }
- if (isOrdered(keyPath)) {
- return keyPath.toArray();
- }
- throw new TypeError('Invalid keyPath: expected Ordered Collection or Array: ' + keyPath);
- }
-
- /**
- * Converts a value to a string, adding quotes if a string was provided.
- */
- function quoteString(value) {
- try {
- return typeof value === 'string' ? JSON.stringify(value) : String(value);
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- }
- catch (_ignoreError) {
- return JSON.stringify(value);
- }
- }
-
- /**
- * Returns true if the key is defined in the provided collection.
- *
- * A functional alternative to `collection.has(key)` which will also work with
- * plain Objects and Arrays as an alternative for
- * `collection.hasOwnProperty(key)`.
- */
- function has(collection, key) {
- return isImmutable(collection)
- ? // @ts-expect-error key might be a number or symbol, which is not handled be Record key type
- collection.has(key)
- : // @ts-expect-error key might be anything else than PropertyKey, and will return false in that case but runtime is OK
- isDataStructure(collection) && hasOwnProperty.call(collection, key);
- }
-
- function get(collection, key, notSetValue) {
- return isImmutable(collection)
- ? collection.get(key, notSetValue)
- : !has(collection, key)
- ? notSetValue
- : // @ts-expect-error weird "get" here,
- typeof collection.get === 'function'
- ? // @ts-expect-error weird "get" here,
- collection.get(key)
- : // @ts-expect-error key is unknown here,
- collection[key];
- }
-
- function remove(collection, key) {
- if (!isDataStructure(collection)) {
- throw new TypeError('Cannot update non-data-structure value: ' + collection);
- }
- if (isImmutable(collection)) {
- // @ts-expect-error weird "remove" here,
- if (!collection.remove) {
- throw new TypeError('Cannot update immutable value without .remove() method: ' + collection);
- }
- // @ts-expect-error weird "remove" here,
- return collection.remove(key);
- }
- // @ts-expect-error assert that key is a string, a number or a symbol here
- if (!hasOwnProperty.call(collection, key)) {
- return collection;
- }
- var collectionCopy = shallowCopy(collection);
- if (Array.isArray(collectionCopy)) {
- // @ts-expect-error assert that key is a number here
- collectionCopy.splice(key, 1);
- }
- else {
- // @ts-expect-error assert that key is a string, a number or a symbol here
- delete collectionCopy[key];
- }
- return collectionCopy;
- }
-
- function set(collection, key, value) {
- if (isProtoKey(key)) {
- return collection;
- }
- if (!isDataStructure(collection)) {
- throw new TypeError('Cannot update non-data-structure value: ' + collection);
- }
- if (isImmutable(collection)) {
- // @ts-expect-error weird "set" here,
- if (!collection.set) {
- throw new TypeError('Cannot update immutable value without .set() method: ' + collection);
- }
- // @ts-expect-error weird "set" here,
- return collection.set(key, value);
- }
- // @ts-expect-error mix of key and string here. Probably need a more fine type here
- if (hasOwnProperty.call(collection, key) && value === collection[key]) {
- return collection;
- }
- var collectionCopy = shallowCopy(collection);
- // @ts-expect-error mix of key and string here. Probably need a more fine type here
- collectionCopy[key] = value;
- return collectionCopy;
- }
-
- function updateIn(collection, keyPath, notSetValue, updater) {
- if (!updater) {
- // handle the fact that `notSetValue` is optional here, in that case `updater` is the updater function
- // @ts-expect-error updater is a function here
- updater = notSetValue;
- notSetValue = undefined;
- }
- var updatedValue = updateInDeeply(isImmutable(collection),
- // @ts-expect-error type issues with Record and mixed types
- collection, coerceKeyPath(keyPath), 0, notSetValue, updater);
- // @ts-expect-error mixed return type
- return updatedValue === NOT_SET ? notSetValue : updatedValue;
- }
- function updateInDeeply(inImmutable, existing, keyPath, i, notSetValue, updater) {
- var wasNotSet = existing === NOT_SET;
- if (i === keyPath.length) {
- var existingValue = wasNotSet ? notSetValue : existing;
- // @ts-expect-error mixed type with optional value
- var newValue = updater(existingValue);
- // @ts-expect-error mixed type
- return newValue === existingValue ? existing : newValue;
- }
- if (!wasNotSet && !isDataStructure(existing)) {
- throw new TypeError('Cannot update within non-data-structure value in path [' +
- Array.from(keyPath).slice(0, i).map(quoteString) +
- ']: ' +
- existing);
- }
- var key = keyPath[i];
- var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET);
- var nextUpdated = updateInDeeply(nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting),
- // @ts-expect-error mixed type
- nextExisting, keyPath, i + 1, notSetValue, updater);
- return nextUpdated === nextExisting
- ? existing
- : nextUpdated === NOT_SET
- ? remove(existing, key)
- : set(wasNotSet ? (inImmutable ? emptyMap() : {}) : existing, key, nextUpdated);
- }
-
- /**
- * Returns a copy of the collection with the value at the key path removed.
- *
- * A functional alternative to `collection.removeIn(keypath)` which will also
- * work with plain Objects and Arrays.
- */
- function removeIn(collection, keyPath) {
- return updateIn(collection, keyPath, function () { return NOT_SET; });
- }
-
- function deleteIn(keyPath) {
- return removeIn(this, keyPath);
- }
-
- var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@';
- /**
- * True if `maybeList` is a List.
- */
- function isList(maybeList) {
- return Boolean(maybeList &&
- // @ts-expect-error: maybeList is typed as `{}`, need to change in 6.0 to `maybeList && typeof maybeList === 'object' && IS_LIST_SYMBOL in maybeList`
- maybeList[IS_LIST_SYMBOL]);
- }
-
- var List = /*@__PURE__*/(function (IndexedCollection) {
- function List(value) {
- var empty = emptyList();
- if (value === undefined || value === null) {
- // eslint-disable-next-line no-constructor-return
- return empty;
- }
- if (isList(value)) {
- // eslint-disable-next-line no-constructor-return
- return value;
- }
- var iter = IndexedCollection(value);
- var size = iter.size;
- if (size === 0) {
- // eslint-disable-next-line no-constructor-return
- return empty;
- }
- assertNotInfinite(size);
- if (size > 0 && size < SIZE) {
- // eslint-disable-next-line no-constructor-return
- return makeList(0, size, SHIFT, undefined, new VNode(iter.toArray()));
- }
- // eslint-disable-next-line no-constructor-return
- return empty.withMutations(function (list) {
- list.setSize(size);
- iter.forEach(function (v, i) { return list.set(i, v); });
- });
- }
-
- if ( IndexedCollection ) List.__proto__ = IndexedCollection;
- List.prototype = Object.create( IndexedCollection && IndexedCollection.prototype );
- List.prototype.constructor = List;
-
- List.of = function of (/*...values*/) {
- return this(arguments);
- };
-
- List.prototype.toString = function toString () {
- return this.__toString('List [', ']');
- };
-
- // @pragma Access
-
- List.prototype.get = function get (index, notSetValue) {
- index = wrapIndex(this, index);
- if (index >= 0 && index < this.size) {
- index += this._origin;
- var node = listNodeFor(this, index);
- return node && node.array[index & MASK];
- }
- return notSetValue;
- };
-
- // @pragma Modification
-
- List.prototype.set = function set (index, value) {
- return updateList(this, index, value);
- };
-
- List.prototype.remove = function remove (index) {
- return !this.has(index)
- ? this
- : index === 0
- ? this.shift()
- : index === this.size - 1
- ? this.pop()
- : this.splice(index, 1);
- };
-
- List.prototype.insert = function insert (index, value) {
- return this.splice(index, 0, value);
- };
-
- List.prototype.clear = function clear () {
- if (this.size === 0) {
- return this;
- }
- if (this.__ownerID) {
- this.size = this._origin = this._capacity = 0;
- this._level = SHIFT;
- this._root = this._tail = this.__hash = undefined;
- this.__altered = true;
- return this;
- }
- return emptyList();
- };
-
- List.prototype.push = function push (/*...values*/) {
- var values = arguments;
- var oldSize = this.size;
- return this.withMutations(function (list) {
- setListBounds(list, 0, oldSize + values.length);
- for (var ii = 0; ii < values.length; ii++) {
- list.set(oldSize + ii, values[ii]);
- }
- });
- };
-
- List.prototype.pop = function pop () {
- return setListBounds(this, 0, -1);
- };
-
- List.prototype.unshift = function unshift (/*...values*/) {
- var values = arguments;
- return this.withMutations(function (list) {
- setListBounds(list, -values.length);
- for (var ii = 0; ii < values.length; ii++) {
- list.set(ii, values[ii]);
- }
- });
- };
-
- List.prototype.shift = function shift () {
- return setListBounds(this, 1);
- };
-
- List.prototype.shuffle = function shuffle (random) {
- if ( random === void 0 ) random = Math.random;
-
- return this.withMutations(function (mutable) {
- // implementation of the Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
- var current = mutable.size;
- var destination;
- var tmp;
-
- while (current) {
- destination = Math.floor(random() * current--);
-
- tmp = mutable.get(destination);
- mutable.set(destination, mutable.get(current));
- mutable.set(current, tmp);
- }
- });
- };
-
- // @pragma Composition
-
- List.prototype.concat = function concat (/*...collections*/) {
- var arguments$1 = arguments;
-
- var seqs = [];
- for (var i = 0; i < arguments.length; i++) {
- var argument = arguments$1[i];
- var seq = IndexedCollection(
- typeof argument !== 'string' && hasIterator(argument)
- ? argument
- : [argument]
- );
- if (seq.size !== 0) {
- seqs.push(seq);
- }
- }
- if (seqs.length === 0) {
- return this;
- }
- if (this.size === 0 && !this.__ownerID && seqs.length === 1) {
- return this.constructor(seqs[0]);
- }
- return this.withMutations(function (list) {
- seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); });
- });
- };
-
- List.prototype.setSize = function setSize (size) {
- return setListBounds(this, 0, size);
- };
-
- List.prototype.map = function map (mapper, context) {
- var this$1$1 = this;
-
- return this.withMutations(function (list) {
- for (var i = 0; i < this$1$1.size; i++) {
- list.set(i, mapper.call(context, list.get(i), i, this$1$1));
- }
- });
- };
-
- // @pragma Iteration
-
- List.prototype.slice = function slice (begin, end) {
- var size = this.size;
- if (wholeSlice(begin, end, size)) {
- return this;
- }
- return setListBounds(
- this,
- resolveBegin(begin, size),
- resolveEnd(end, size)
- );
- };
-
- List.prototype.__iterator = function __iterator (type, reverse) {
- var index = reverse ? this.size : 0;
- var values = iterateList(this, reverse);
- return new Iterator(function () {
- var value = values();
- return value === DONE
- ? iteratorDone()
- : iteratorValue(type, reverse ? --index : index++, value);
- });
- };
-
- List.prototype.__iterate = function __iterate (fn, reverse) {
- var index = reverse ? this.size : 0;
- var values = iterateList(this, reverse);
- var value;
- while ((value = values()) !== DONE) {
- if (fn(value, reverse ? --index : index++, this) === false) {
- break;
- }
- }
- return index;
- };
-
- List.prototype.__ensureOwner = function __ensureOwner (ownerID) {
- if (ownerID === this.__ownerID) {
- return this;
- }
- if (!ownerID) {
- if (this.size === 0) {
- return emptyList();
- }
- this.__ownerID = ownerID;
- this.__altered = false;
- return this;
- }
- return makeList(
- this._origin,
- this._capacity,
- this._level,
- this._root,
- this._tail,
- ownerID,
- this.__hash
- );
- };
-
- return List;
- }(IndexedCollection));
-
- List.isList = isList;
-
- var ListPrototype = List.prototype;
- ListPrototype[IS_LIST_SYMBOL] = true;
- ListPrototype[DELETE] = ListPrototype.remove;
- ListPrototype.merge = ListPrototype.concat;
- ListPrototype.setIn = setIn;
- ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn;
- ListPrototype.update = update;
- ListPrototype.updateIn = updateIn$1;
- ListPrototype.mergeIn = mergeIn;
- ListPrototype.mergeDeepIn = mergeDeepIn;
- ListPrototype.withMutations = withMutations;
- ListPrototype.wasAltered = wasAltered;
- ListPrototype.asImmutable = asImmutable;
- ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable;
- ListPrototype['@@transducer/step'] = function (result, arr) {
- return result.push(arr);
- };
- ListPrototype['@@transducer/result'] = function (obj) {
- return obj.asImmutable();
- };
-
- /**
- * A node in the List's 32-wide trie. At inner levels `array` holds child
- * `VNode`s; at the leaf level it holds the List's values. Missing slots are
- * `undefined` array holes.
- *
- * @template T
- */
- var VNode = function VNode(array, ownerID) {
- this.array = array;
- this.ownerID = ownerID;
- };
-
- // TODO: seems like these methods are very similar
-
- VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) {
- if (
- (index & ((1 << (level + SHIFT)) - 1)) === 0 ||
- this.array.length === 0
- ) {
- return this;
- }
- var originIndex = (index >>> level) & MASK;
- if (originIndex >= this.array.length) {
- return new VNode([], ownerID);
- }
- var removingFirst = originIndex === 0;
- var newChild;
- if (level > 0) {
- var oldChild = this.array[originIndex];
- newChild =
- oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
- if (newChild === oldChild && removingFirst) {
- return this;
- }
- }
- if (removingFirst && !newChild) {
- return this;
- }
- var editable = editableVNode(this, ownerID);
- if (!removingFirst) {
- for (var ii = 0; ii < originIndex; ii++) {
- editable.array[ii] = undefined;
- }
- }
- if (newChild) {
- editable.array[originIndex] = newChild;
- }
- return editable;
- };
-
- VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) {
- if (
- index === (level ? 1 << (level + SHIFT) : SIZE) ||
- this.array.length === 0
- ) {
- return this;
- }
- var sizeIndex = ((index - 1) >>> level) & MASK;
- if (sizeIndex >= this.array.length) {
- return this;
- }
-
- var newChild;
- if (level > 0) {
- var oldChild = this.array[sizeIndex];
- newChild =
- oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
- if (newChild === oldChild && sizeIndex === this.array.length - 1) {
- return this;
- }
- }
-
- var editable = editableVNode(this, ownerID);
- editable.array.splice(sizeIndex + 1);
- if (newChild) {
- editable.array[sizeIndex] = newChild;
- }
- return editable;
- };
-
- var DONE = {};
-
- function iterateList(list, reverse) {
- var left = list._origin;
- var right = list._capacity;
- var tailPos = getTailOffset(right);
- var tail = list._tail;
-
- return iterateNodeOrLeaf(list._root, list._level, 0);
-
- function iterateNodeOrLeaf(node, level, offset) {
- return level === 0
- ? iterateLeaf(node, offset)
- : iterateNode(node, level, offset);
- }
-
- function iterateLeaf(node, offset) {
- var array = offset === tailPos ? tail && tail.array : node && node.array;
- var from = offset > left ? 0 : left - offset;
- var to = right - offset;
- if (to > SIZE) {
- to = SIZE;
- }
- return function () {
- if (from === to) {
- return DONE;
- }
- var idx = reverse ? --to : from++;
- return array && array[idx];
- };
- }
-
- function iterateNode(node, level, offset) {
- var values;
- var array = node && node.array;
- var from = offset > left ? 0 : (left - offset) >> level;
- var to = ((right - offset) >> level) + 1;
- if (to > SIZE) {
- to = SIZE;
- }
- return function () {
- while (true) {
- if (values) {
- var value = values();
- if (value !== DONE) {
- return value;
- }
- values = null;
- }
- if (from === to) {
- return DONE;
- }
- var idx = reverse ? --to : from++;
- values = iterateNodeOrLeaf(
- array && array[idx],
- level - SHIFT,
- offset + (idx << level)
- );
- }
- };
- }
- }
-
- /**
- * @param {number} origin
- * @param {number} capacity
- * @param {number} level
- * @param {VNode | undefined} [root] The trie root, or `undefined` when every
- * in-range value lives in the tail (or is a virtual `undefined`).
- * @param {VNode | undefined} [tail]
- * @param {OwnerID} [ownerID]
- * @param {number} [hash]
- */
- function makeList(origin, capacity, level, root, tail, ownerID, hash) {
- var list = Object.create(ListPrototype);
- list.size = capacity - origin;
- list._origin = origin;
- list._capacity = capacity;
- list._level = level;
- list._root = root;
- list._tail = tail;
- list.__ownerID = ownerID;
- list.__hash = hash;
- list.__altered = false;
- return list;
- }
-
- function emptyList() {
- return makeList(0, 0, SHIFT);
- }
-
- function updateList(list, index, value) {
- index = wrapIndex(list, index);
-
- if (index !== index) {
- return list;
- }
-
- if (index >= list.size || index < 0) {
- return list.withMutations(function (list) {
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- index < 0
- ? setListBounds(list, index).set(0, value)
- : setListBounds(list, 0, index + 1).set(index, value);
- });
- }
-
- index += list._origin;
-
- var newTail = list._tail;
- var newRoot = list._root;
- var didAlter = MakeRef();
- if (index >= getTailOffset(list._capacity)) {
- newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
- } else {
- newRoot = updateVNode(
- newRoot,
- list.__ownerID,
- list._level,
- index,
- value,
- didAlter
- );
- }
-
- if (!didAlter.value) {
- return list;
- }
-
- if (list.__ownerID) {
- list._root = newRoot;
- list._tail = newTail;
- list.__hash = undefined;
- list.__altered = true;
- return list;
- }
- return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
- }
-
- function updateVNode(node, ownerID, level, index, value, didAlter) {
- var idx = (index >>> level) & MASK;
- var nodeHas = node && idx < node.array.length;
- if (!nodeHas && value === undefined) {
- return node;
- }
-
- var newNode;
-
- if (level > 0) {
- var lowerNode = node && node.array[idx];
- var newLowerNode = updateVNode(
- lowerNode,
- ownerID,
- level - SHIFT,
- index,
- value,
- didAlter
- );
- if (newLowerNode === lowerNode) {
- return node;
- }
- newNode = editableVNode(node, ownerID);
- newNode.array[idx] = newLowerNode;
- return newNode;
- }
-
- if (nodeHas && node.array[idx] === value) {
- return node;
- }
-
- if (didAlter) {
- SetRef(didAlter);
- }
-
- newNode = editableVNode(node, ownerID);
- if (value === undefined && idx === newNode.array.length - 1) {
- newNode.array.pop();
- } else {
- newNode.array[idx] = value;
- }
- return newNode;
- }
-
- function editableVNode(node, ownerID) {
- if (ownerID && node && ownerID === node.ownerID) {
- return node;
- }
- return new VNode(node ? node.array.slice() : [], ownerID);
- }
-
- /**
- * Returns the leaf `VNode` holding `rawIndex`, or `undefined` when no node is
- * allocated for it (an all-`undefined` region).
- *
- * @param {List} list
- * @param {number} rawIndex
- * @returns {VNode | undefined}
- */
- function listNodeFor(list, rawIndex) {
- if (rawIndex >= getTailOffset(list._capacity)) {
- return list._tail;
- }
- if (rawIndex < 1 << (list._level + SHIFT)) {
- var node = list._root;
- var level = list._level;
- while (node && level > 0) {
- node = node.array[(rawIndex >>> level) & MASK];
- level -= SHIFT;
- }
- return node;
- }
- }
-
- /**
- * Validates requested bounds before int32 coercion in setListBounds().
- * Throws when origin/capacity would exceed the trie's safe range.
- */
- function validateListBoundsRequest(list, begin, end) {
- var requestedOrigin = list._origin + (begin === undefined ? 0 : begin);
- var requestedCapacity =
- end === undefined
- ? list._capacity
- : end < 0
- ? list._capacity + end
- : list._origin + end;
-
- // Keep origin/capacity within the trie's safe signed 32-bit range.
- if (
- (Number.isFinite(requestedCapacity) && requestedCapacity > MAX_LIST_SIZE) ||
- (Number.isFinite(requestedOrigin) && requestedOrigin < -MAX_LIST_SIZE) ||
- (Number.isFinite(requestedCapacity) &&
- Number.isFinite(requestedOrigin) &&
- requestedCapacity - requestedOrigin > MAX_LIST_SIZE)
- ) {
- throw new RangeError(
- 'Invalid List size: a List cannot hold more than ' +
- MAX_LIST_SIZE +
- ' (2 ** 30) values.'
- );
- }
- }
-
- function setListBounds(list, begin, end) {
- // Validate full-precision bounds before int32 coercion.
- validateListBoundsRequest(list, begin, end);
-
- // Sanitize begin & end using this shorthand for ToInt32(argument)
- // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
- if (begin !== undefined) {
- begin |= 0;
- }
- if (end !== undefined) {
- end |= 0;
- }
- var owner = list.__ownerID || new OwnerID();
- var oldOrigin = list._origin;
- var oldCapacity = list._capacity;
- var newOrigin = oldOrigin + begin;
- var newCapacity =
- end === undefined
- ? oldCapacity
- : end < 0
- ? oldCapacity + end
- : oldOrigin + end;
- if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
- return list;
- }
-
- // If it's going to end after it starts, it's empty.
- if (newOrigin >= newCapacity) {
- return list.clear();
- }
-
- var newLevel = list._level;
- var newRoot = list._root;
-
- // New origin might need creating a higher root.
- var offsetShift = 0;
- while (newOrigin + offsetShift < 0) {
- newRoot = new VNode(
- newRoot && newRoot.array.length ? [undefined, newRoot] : [],
- owner
- );
- newLevel += SHIFT;
- // Shift origin into non-negative space as trie height grows.
- offsetShift += levelCapacity(newLevel);
- }
- if (offsetShift) {
- newOrigin += offsetShift;
- oldOrigin += offsetShift;
- newCapacity += offsetShift;
- oldCapacity += offsetShift;
- }
-
- var oldTailOffset = getTailOffset(oldCapacity);
- var newTailOffset = getTailOffset(newCapacity);
-
- // New size might need creating a higher root.
- while (newTailOffset >= levelCapacity(newLevel + SHIFT)) {
- newRoot = new VNode(
- newRoot && newRoot.array.length ? [newRoot] : [],
- owner
- );
- newLevel += SHIFT;
- }
-
- // Locate or create the new tail.
- var oldTail = list._tail;
- var newTail =
- newTailOffset < oldTailOffset
- ? listNodeFor(list, newCapacity - 1)
- : newTailOffset > oldTailOffset
- ? new VNode([], owner)
- : oldTail;
-
- // Merge Tail into tree.
- if (
- oldTail &&
- newTailOffset > oldTailOffset &&
- newOrigin < oldCapacity &&
- oldTail.array.length
- ) {
- newRoot = editableVNode(newRoot, owner);
- var node = newRoot;
- for (var level = newLevel; level > SHIFT; level -= SHIFT) {
- var idx = (oldTailOffset >>> level) & MASK;
- node = node.array[idx] = editableVNode(node.array[idx], owner);
- }
- node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
- }
-
- // If the size has been reduced, there's a chance the tail needs to be trimmed.
- if (newCapacity < oldCapacity) {
- newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
- }
-
- // If the new origin is within the tail, then we do not need a root.
- if (newOrigin >= newTailOffset) {
- newOrigin -= newTailOffset;
- newCapacity -= newTailOffset;
- newLevel = SHIFT;
- newRoot = undefined;
- newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
-
- // Otherwise, if the root has been trimmed, garbage collect.
- } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
- offsetShift = 0;
-
- // Identify the new top root node of the subtree of the old root.
- while (newRoot) {
- var beginIndex = (newOrigin >>> newLevel) & MASK;
- if ((beginIndex !== newTailOffset >>> newLevel) & MASK) {
- break;
- }
- if (beginIndex) {
- offsetShift += (1 << newLevel) * beginIndex;
- }
- newLevel -= SHIFT;
- newRoot = newRoot.array[beginIndex];
- }
-
- // Trim the new sides of the new root.
- if (newRoot && newOrigin > oldOrigin) {
- newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
- }
- if (newRoot && newTailOffset < oldTailOffset) {
- newRoot = newRoot.removeAfter(
- owner,
- newLevel,
- newTailOffset - offsetShift
- );
- }
- if (offsetShift) {
- newOrigin -= offsetShift;
- newCapacity -= offsetShift;
- }
- }
-
- if (list.__ownerID) {
- list.size = newCapacity - newOrigin;
- list._origin = newOrigin;
- list._capacity = newCapacity;
- list._level = newLevel;
- list._root = newRoot;
- list._tail = newTail;
- list.__hash = undefined;
- list.__altered = true;
- return list;
- }
- return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
- }
-
- function getTailOffset(size) {
- return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT;
- }
-
- // The largest number of values a List can hold. Above this the 32-bit trie math
- // in setListBounds() stays in the safe signed 32-bit range.
- var MAX_LIST_SIZE = Math.pow( 2, 30 ); // 1073741824
-
- /**
- * Computes 2 ** exp for the trie level-raising loops in setListBounds().
- * Use the cheap bitwise operator shift whenever possible, otherwise fall back to exponentiation.
- * This is necessary because bitwise operators in JavaScript only work on 32-bit signed integers, so for exp >= 31, we need to use exponentiation to avoid overflow.
- */
- function levelCapacity(exp) {
- return exp < 31 ? 1 << exp : Math.pow( 2, exp );
- }
-
- /**
- * True if `maybeOrderedMap` is an OrderedMap.
- */
- function isOrderedMap(maybeOrderedMap) {
- return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
- }
-
- var OrderedMap = /*@__PURE__*/(function (Map) {
- function OrderedMap(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptyOrderedMap()
- : isOrderedMap(value)
- ? value
- : emptyOrderedMap().withMutations(function (map) {
- var iter = KeyedCollection(value);
- assertNotInfinite(iter.size);
- iter.forEach(function (v, k) { return map.set(k, v); });
- });
- }
-
- if ( Map ) OrderedMap.__proto__ = Map;
- OrderedMap.prototype = Object.create( Map && Map.prototype );
- OrderedMap.prototype.constructor = OrderedMap;
-
- OrderedMap.of = function of (/*...values*/) {
- return this(arguments);
- };
-
- OrderedMap.prototype.toString = function toString () {
- return this.__toString('OrderedMap {', '}');
- };
-
- // @pragma Access
-
- OrderedMap.prototype.get = function get (k, notSetValue) {
- var index = this._map.get(k);
- return index !== undefined ? this._list.get(index)[1] : notSetValue;
- };
-
- // @pragma Modification
-
- OrderedMap.prototype.clear = function clear () {
- if (this.size === 0) {
- return this;
- }
- if (this.__ownerID) {
- this.size = 0;
- this._map.clear();
- this._list.clear();
- this.__altered = true;
- return this;
- }
- return emptyOrderedMap();
- };
-
- OrderedMap.prototype.set = function set (k, v) {
- return updateOrderedMap(this, k, v);
- };
-
- OrderedMap.prototype.remove = function remove (k) {
- return updateOrderedMap(this, k, NOT_SET);
- };
-
- OrderedMap.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- return this._list.__iterate(
- function (entry) { return entry && fn(entry[1], entry[0], this$1$1); },
- reverse
- );
- };
-
- OrderedMap.prototype.__iterator = function __iterator (type, reverse) {
- return this._list.fromEntrySeq().__iterator(type, reverse);
- };
-
- OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) {
- if (ownerID === this.__ownerID) {
- return this;
- }
- var newMap = this._map.__ensureOwner(ownerID);
- var newList = this._list.__ensureOwner(ownerID);
- if (!ownerID) {
- if (this.size === 0) {
- return emptyOrderedMap();
- }
- this.__ownerID = ownerID;
- this.__altered = false;
- this._map = newMap;
- this._list = newList;
- return this;
- }
- return makeOrderedMap(newMap, newList, ownerID, this.__hash);
- };
-
- return OrderedMap;
- }(Map));
-
- OrderedMap.isOrderedMap = isOrderedMap;
-
- OrderedMap.prototype[IS_ORDERED_SYMBOL] = true;
- OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
-
- function makeOrderedMap(map, list, ownerID, hash) {
- var omap = Object.create(OrderedMap.prototype);
- omap.size = map ? map.size : 0;
- omap._map = map;
- omap._list = list;
- omap.__ownerID = ownerID;
- omap.__hash = hash;
- omap.__altered = false;
- return omap;
- }
-
- var EMPTY_ORDERED_MAP;
- function emptyOrderedMap() {
- return (
- EMPTY_ORDERED_MAP ||
- (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()))
- );
- }
-
- function updateOrderedMap(omap, k, v) {
- var map = omap._map;
- var list = omap._list;
- var i = map.get(k);
- var has = i !== undefined;
- var newMap;
- var newList;
- if (v === NOT_SET) {
- // removed
- if (!has) {
- return omap;
- }
- if (list.size >= SIZE && list.size >= map.size * 2) {
- newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; });
- newMap = newList
- .toKeyedSeq()
- .map(function (entry) { return entry[0]; })
- .flip()
- .toMap();
- if (omap.__ownerID) {
- newMap.__ownerID = newList.__ownerID = omap.__ownerID;
- }
- } else {
- newMap = map.remove(k);
- newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
- }
- } else if (has) {
- if (v === list.get(i)[1]) {
- return omap;
- }
- newMap = map;
- newList = list.set(i, [k, v]);
- } else {
- newMap = map.set(k, list.size);
- newList = list.set(list.size, [k, v]);
- }
- if (omap.__ownerID) {
- omap.size = newMap.size;
- omap._map = newMap;
- omap._list = newList;
- omap.__hash = undefined;
- omap.__altered = true;
- return omap;
- }
- return makeOrderedMap(newMap, newList);
- }
-
- var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@';
- /**
- * True if `maybeStack` is a Stack.
- */
- function isStack(maybeStack) {
- return Boolean(maybeStack &&
- // @ts-expect-error: maybeStack is typed as `{}`, need to change in 6.0 to `maybeStack && typeof maybeStack === 'object' && MAYBE_STACK_SYMBOL in maybeStack`
- maybeStack[IS_STACK_SYMBOL]);
- }
-
- var Stack = /*@__PURE__*/(function (IndexedCollection) {
- function Stack(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptyStack()
- : isStack(value)
- ? value
- : emptyStack().pushAll(value);
- }
-
- if ( IndexedCollection ) Stack.__proto__ = IndexedCollection;
- Stack.prototype = Object.create( IndexedCollection && IndexedCollection.prototype );
- Stack.prototype.constructor = Stack;
-
- Stack.of = function of (/*...values*/) {
- return this(arguments);
- };
-
- Stack.prototype.toString = function toString () {
- return this.__toString('Stack [', ']');
- };
-
- // @pragma Access
-
- Stack.prototype.get = function get (index, notSetValue) {
- var head = this._head;
- index = wrapIndex(this, index);
- while (head && index--) {
- head = head.next;
- }
- return head ? head.value : notSetValue;
- };
-
- Stack.prototype.peek = function peek () {
- return this._head && this._head.value;
- };
-
- // @pragma Modification
-
- Stack.prototype.push = function push (/*...values*/) {
- var arguments$1 = arguments;
-
- if (arguments.length === 0) {
- return this;
- }
- var newSize = this.size + arguments.length;
- var head = this._head;
- for (var ii = arguments.length - 1; ii >= 0; ii--) {
- head = {
- value: arguments$1[ii],
- next: head,
- };
- }
- if (this.__ownerID) {
- this.size = newSize;
- this._head = head;
- this.__hash = undefined;
- this.__altered = true;
- return this;
- }
- return makeStack(newSize, head);
- };
-
- Stack.prototype.pushAll = function pushAll (iter) {
- iter = IndexedCollection(iter);
- if (iter.size === 0) {
- return this;
- }
- if (this.size === 0 && isStack(iter)) {
- return iter;
- }
- assertNotInfinite(iter.size);
- var newSize = this.size;
- var head = this._head;
- iter.__iterate(function (value) {
- newSize++;
- head = {
- value: value,
- next: head,
- };
- }, /* reverse */ true);
- if (this.__ownerID) {
- this.size = newSize;
- this._head = head;
- this.__hash = undefined;
- this.__altered = true;
- return this;
- }
- return makeStack(newSize, head);
- };
-
- Stack.prototype.pop = function pop () {
- return this.slice(1);
- };
-
- Stack.prototype.clear = function clear () {
- if (this.size === 0) {
- return this;
- }
- if (this.__ownerID) {
- this.size = 0;
- this._head = undefined;
- this.__hash = undefined;
- this.__altered = true;
- return this;
- }
- return emptyStack();
- };
-
- Stack.prototype.slice = function slice (begin, end) {
- if (wholeSlice(begin, end, this.size)) {
- return this;
- }
- var resolvedBegin = resolveBegin(begin, this.size);
- var resolvedEnd = resolveEnd(end, this.size);
- if (resolvedEnd !== this.size) {
- // super.slice(begin, end);
- return IndexedCollection.prototype.slice.call(this, begin, end);
- }
- var newSize = this.size - resolvedBegin;
- var head = this._head;
- while (resolvedBegin--) {
- head = head.next;
- }
- if (this.__ownerID) {
- this.size = newSize;
- this._head = head;
- this.__hash = undefined;
- this.__altered = true;
- return this;
- }
- return makeStack(newSize, head);
- };
-
- // @pragma Mutability
-
- Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) {
- if (ownerID === this.__ownerID) {
- return this;
- }
- if (!ownerID) {
- if (this.size === 0) {
- return emptyStack();
- }
- this.__ownerID = ownerID;
- this.__altered = false;
- return this;
- }
- return makeStack(this.size, this._head, ownerID, this.__hash);
- };
-
- // @pragma Iteration
-
- Stack.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- if (reverse) {
- return new ArraySeq(this.toArray()).__iterate(
- function (v, k) { return fn(v, k, this$1$1); },
- reverse
- );
- }
- var iterations = 0;
- var node = this._head;
- while (node) {
- if (fn(node.value, iterations++, this) === false) {
- break;
- }
- node = node.next;
- }
- return iterations;
- };
-
- Stack.prototype.__iterator = function __iterator (type, reverse) {
- if (reverse) {
- return new ArraySeq(this.toArray()).__iterator(type, reverse);
- }
- var iterations = 0;
- var node = this._head;
- return new Iterator(function () {
- if (node) {
- var value = node.value;
- node = node.next;
- return iteratorValue(type, iterations++, value);
- }
- return iteratorDone();
- });
- };
-
- return Stack;
- }(IndexedCollection));
-
- Stack.isStack = isStack;
-
- var StackPrototype = Stack.prototype;
- StackPrototype[IS_STACK_SYMBOL] = true;
- StackPrototype.shift = StackPrototype.pop;
- StackPrototype.unshift = StackPrototype.push;
- StackPrototype.unshiftAll = StackPrototype.pushAll;
- StackPrototype.withMutations = withMutations;
- StackPrototype.wasAltered = wasAltered;
- StackPrototype.asImmutable = asImmutable;
- StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable;
- StackPrototype['@@transducer/step'] = function (result, arr) {
- return result.unshift(arr);
- };
- StackPrototype['@@transducer/result'] = function (obj) {
- return obj.asImmutable();
- };
-
- function makeStack(size, head, ownerID, hash) {
- var map = Object.create(StackPrototype);
- map.size = size;
- map._head = head;
- map.__ownerID = ownerID;
- map.__hash = hash;
- map.__altered = false;
- return map;
- }
-
- var EMPTY_STACK;
- function emptyStack() {
- return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
- }
-
- function reduce(collection, reducer, reduction, context, useFirst, reverse) {
- // @ts-expect-error Migrate to CollectionImpl in v6
- assertNotInfinite(collection.size);
- // @ts-expect-error Migrate to CollectionImpl in v6
- collection.__iterate(function (v, k, c) {
- if (useFirst) {
- useFirst = false;
- reduction = v;
- }
- else {
- // `reduction` has already been seeded here (either with the provided
- // initial value or with the first iterated value), so it is never the
- // `undefined` placeholder — only a `V` or a `R`.
- reduction = reducer.call(context, reduction, v, k, c);
- }
- }, reverse);
- return reduction;
- }
- function keyMapper(v, k) {
- return k;
- }
- function entryMapper(v, k) {
- return [k, v];
- }
- function not(predicate) {
- return function () {
- var args = [], len = arguments.length;
- while ( len-- ) args[ len ] = arguments[ len ];
-
- return !predicate.apply(this, args);
- };
- }
- function neg(predicate) {
- return function () {
- var args = [], len = arguments.length;
- while ( len-- ) args[ len ] = arguments[ len ];
-
- return -predicate.apply(this, args);
- };
- }
- function defaultNegComparator(a, b) {
- return a < b ? 1 : a > b ? -1 : 0;
- }
-
- function deepEqual(a, b) {
- if (a === b) {
- return true;
- }
- if (!isCollection(b) ||
- // @ts-expect-error size should exists on Collection
- (a.size !== undefined && b.size !== undefined && a.size !== b.size) ||
- // @ts-expect-error __hash exists on Collection
- (a.__hash !== undefined &&
- // @ts-expect-error __hash exists on Collection
- b.__hash !== undefined &&
- // @ts-expect-error __hash exists on Collection
- a.__hash !== b.__hash) ||
- isKeyed(a) !== isKeyed(b) ||
- isIndexed(a) !== isIndexed(b) ||
- // @ts-expect-error Range extends Collection, which implements [Symbol.iterator], so it is valid
- isOrdered(a) !== isOrdered(b)) {
- return false;
- }
- // @ts-expect-error size should exists on Collection
- if (a.size === 0 && b.size === 0) {
- return true;
- }
- var notAssociative = !isAssociative(a);
- // @ts-expect-error Range extends Collection, which implements [Symbol.iterator], so it is valid
- if (isOrdered(a)) {
- var entries = a.entries();
- // @ts-expect-error need to cast as boolean
- return (b.every(function (v, k) {
- var entry = entries.next().value;
- return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
- }) && entries.next().done);
- }
- var flipped = false;
- if (a.size === undefined) {
- // @ts-expect-error size should exists on Collection
- if (b.size === undefined) {
- if (typeof a.cacheResult === 'function') {
- a.cacheResult();
- }
- }
- else {
- flipped = true;
- var _ = a;
- a = b;
- b = _;
- }
- }
- var allEqual = true;
- var bSize =
- // @ts-expect-error b is Range | Repeat | Collection as it may have been flipped, and __iterate is valid
- b.__iterate(function (v, k) {
- if (notAssociative
- ? // @ts-expect-error has exists on Collection
- !a.has(v)
- : flipped
- ? // @ts-expect-error type of `get` does not "catch" the version with `notSetValue`
- !is(v, a.get(k, NOT_SET))
- : // @ts-expect-error type of `get` does not "catch" the version with `notSetValue`
- !is(a.get(k, NOT_SET), v)) {
- allEqual = false;
- return false;
- }
- });
- return (allEqual &&
- // @ts-expect-error size should exists on Collection
- a.size === bSize);
- }
-
- /**
- * Returns a lazy seq of nums from start (inclusive) to end
- * (exclusive), by step, where start defaults to 0, step to 1, and end to
- * infinity. When start is equal to end, returns empty list.
- */
- var Range = /*@__PURE__*/(function (IndexedSeq) {
- function Range(start, end, step) {
- if ( step === void 0 ) step = 1;
-
- if (!(this instanceof Range)) {
- // eslint-disable-next-line no-constructor-return
- return new Range(start, end, step);
- }
- invariant(step !== 0, 'Cannot step a Range by 0');
- invariant(
- start !== undefined,
- 'You must define a start value when using Range'
- );
- invariant(
- end !== undefined,
- 'You must define an end value when using Range'
- );
-
- step = Math.abs(step);
- if (end < start) {
- step = -step;
- }
- this._start = start;
- this._end = end;
- this._step = step;
- this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
- if (this.size === 0) {
- if (EMPTY_RANGE) {
- // eslint-disable-next-line no-constructor-return
- return EMPTY_RANGE;
- }
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- EMPTY_RANGE = this;
- }
- }
-
- if ( IndexedSeq ) Range.__proto__ = IndexedSeq;
- Range.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
- Range.prototype.constructor = Range;
-
- Range.prototype.toString = function toString () {
- return this.size === 0
- ? 'Range []'
- : ("Range [ " + (this._start) + "..." + (this._end) + (this._step !== 1 ? ' by ' + this._step : '') + " ]");
- };
-
- Range.prototype.get = function get (index, notSetValue) {
- return this.has(index)
- ? this._start + wrapIndex(this, index) * this._step
- : notSetValue;
- };
-
- Range.prototype.includes = function includes (searchValue) {
- var possibleIndex = (searchValue - this._start) / this._step;
- return (
- possibleIndex >= 0 &&
- possibleIndex < this.size &&
- possibleIndex === Math.floor(possibleIndex)
- );
- };
-
- Range.prototype.slice = function slice (begin, end) {
- if (wholeSlice(begin, end, this.size)) {
- return this;
- }
- begin = resolveBegin(begin, this.size);
- end = resolveEnd(end, this.size);
- if (end <= begin) {
- return new Range(0, 0);
- }
- return new Range(
- this.get(begin, this._end),
- this.get(end, this._end),
- this._step
- );
- };
-
- Range.prototype.indexOf = function indexOf (searchValue) {
- var offsetValue = searchValue - this._start;
- if (offsetValue % this._step === 0) {
- var index = offsetValue / this._step;
- if (index >= 0 && index < this.size) {
- return index;
- }
- }
- return -1;
- };
-
- Range.prototype.lastIndexOf = function lastIndexOf (searchValue) {
- return this.indexOf(searchValue);
- };
-
- Range.prototype.__iterate = function __iterate (fn, reverse) {
- var size = this.size;
- var step = this._step;
- var value = reverse ? this._start + (size - 1) * step : this._start;
- var i = 0;
- while (i !== size) {
- if (fn(value, reverse ? size - ++i : i++, this) === false) {
- break;
- }
- value += reverse ? -step : step;
- }
- return i;
- };
-
- Range.prototype.__iterator = function __iterator (type, reverse) {
- var size = this.size;
- var step = this._step;
- var value = reverse ? this._start + (size - 1) * step : this._start;
- var i = 0;
- return new Iterator(function () {
- if (i === size) {
- return iteratorDone();
- }
- var v = value;
- value += reverse ? -step : step;
- return iteratorValue(type, reverse ? size - ++i : i++, v);
- });
- };
-
- Range.prototype.equals = function equals (other) {
- return other instanceof Range
- ? this._start === other._start &&
- this._end === other._end &&
- this._step === other._step
- : deepEqual(this, other);
- };
-
- return Range;
- }(IndexedSeq));
-
- var EMPTY_RANGE;
-
- var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@';
- /**
- * True if `maybeSet` is a Set.
- *
- * Also true for OrderedSets.
- */
- function isSet(maybeSet) {
- return Boolean(maybeSet &&
- // @ts-expect-error: maybeSet is typed as `{}`, need to change in 6.0 to `maybeSeq && typeof maybeSet === 'object' && MAYBE_SET_SYMBOL in maybeSet`
- maybeSet[IS_SET_SYMBOL]);
- }
-
- var Set = /*@__PURE__*/(function (SetCollection) {
- function Set(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptySet()
- : isSet(value) && !isOrdered(value)
- ? value
- : emptySet().withMutations(function (set) {
- var iter = SetCollection(value);
- assertNotInfinite(iter.size);
- iter.forEach(function (v) { return set.add(v); });
- });
- }
-
- if ( SetCollection ) Set.__proto__ = SetCollection;
- Set.prototype = Object.create( SetCollection && SetCollection.prototype );
- Set.prototype.constructor = Set;
-
- Set.of = function of (/*...values*/) {
- return this(arguments);
- };
-
- Set.fromKeys = function fromKeys (value) {
- return this(KeyedCollection(value).keySeq());
- };
-
- Set.intersect = function intersect (sets) {
- sets = Collection(sets).toArray();
- return sets.length
- ? SetPrototype.intersect.apply(Set(sets.pop()), sets)
- : emptySet();
- };
-
- Set.union = function union (sets) {
- sets = Collection(sets).toArray();
- return sets.length
- ? SetPrototype.union.apply(Set(sets.pop()), sets)
- : emptySet();
- };
-
- Set.prototype.toString = function toString () {
- return this.__toString('Set {', '}');
- };
-
- // @pragma Access
-
- Set.prototype.has = function has (value) {
- return this._map.has(value);
- };
-
- // @pragma Modification
-
- Set.prototype.add = function add (value) {
- return updateSet(this, this._map.set(value, value));
- };
-
- Set.prototype.remove = function remove (value) {
- return updateSet(this, this._map.remove(value));
- };
-
- Set.prototype.clear = function clear () {
- return updateSet(this, this._map.clear());
- };
-
- // @pragma Composition
-
- Set.prototype.map = function map (mapper, context) {
- var this$1$1 = this;
-
- // keep track if the set is altered by the map function
- var didChanges = false;
-
- var newMap = updateSet(
- this,
- this._map.mapEntries(function (ref) {
- var v = ref[1];
-
- var mapped = mapper.call(context, v, v, this$1$1);
-
- if (mapped !== v) {
- didChanges = true;
- }
-
- return [mapped, mapped];
- }, context)
- );
-
- return didChanges ? newMap : this;
- };
-
- Set.prototype.union = function union () {
- var iters = [], len = arguments.length;
- while ( len-- ) iters[ len ] = arguments[ len ];
-
- iters = iters.filter(function (x) { return x.size !== 0; });
- if (iters.length === 0) {
- return this;
- }
- if (this.size === 0 && !this.__ownerID && iters.length === 1) {
- return this.constructor(iters[0]);
- }
- return this.withMutations(function (set) {
- for (var ii = 0; ii < iters.length; ii++) {
- if (typeof iters[ii] === 'string') {
- set.add(iters[ii]);
- } else {
- SetCollection(iters[ii]).forEach(function (value) { return set.add(value); });
- }
- }
- });
- };
-
- Set.prototype.intersect = function intersect () {
- var iters = [], len = arguments.length;
- while ( len-- ) iters[ len ] = arguments[ len ];
-
- if (iters.length === 0) {
- return this;
- }
- iters = iters.map(function (iter) { return SetCollection(iter); });
- var toRemove = [];
- this.forEach(function (value) {
- if (!iters.every(function (iter) { return iter.includes(value); })) {
- toRemove.push(value);
- }
- });
- return this.withMutations(function (set) {
- toRemove.forEach(function (value) {
- set.remove(value);
- });
- });
- };
-
- Set.prototype.subtract = function subtract () {
- var iters = [], len = arguments.length;
- while ( len-- ) iters[ len ] = arguments[ len ];
-
- if (iters.length === 0) {
- return this;
- }
- iters = iters.map(function (iter) { return SetCollection(iter); });
- var toRemove = [];
- this.forEach(function (value) {
- if (iters.some(function (iter) { return iter.includes(value); })) {
- toRemove.push(value);
- }
- });
- return this.withMutations(function (set) {
- toRemove.forEach(function (value) {
- set.remove(value);
- });
- });
- };
-
- Set.prototype.sort = function sort (comparator) {
- // Late binding
- return OrderedSet(sortFactory(this, comparator));
- };
-
- Set.prototype.sortBy = function sortBy (mapper, comparator) {
- // Late binding
- return OrderedSet(sortFactory(this, comparator, mapper));
- };
-
- Set.prototype.wasAltered = function wasAltered () {
- return this._map.wasAltered();
- };
-
- Set.prototype.__iterate = function __iterate (fn, reverse) {
- var this$1$1 = this;
-
- return this._map.__iterate(function (k) { return fn(k, k, this$1$1); }, reverse);
- };
-
- Set.prototype.__iterator = function __iterator (type, reverse) {
- return this._map.__iterator(type, reverse);
- };
-
- Set.prototype.__ensureOwner = function __ensureOwner (ownerID) {
- if (ownerID === this.__ownerID) {
- return this;
- }
- var newMap = this._map.__ensureOwner(ownerID);
- if (!ownerID) {
- if (this.size === 0) {
- return this.__empty();
- }
- this.__ownerID = ownerID;
- this._map = newMap;
- return this;
- }
- return this.__make(newMap, ownerID);
- };
-
- return Set;
- }(SetCollection));
-
- Set.isSet = isSet;
-
- var SetPrototype = Set.prototype;
- SetPrototype[IS_SET_SYMBOL] = true;
- SetPrototype[DELETE] = SetPrototype.remove;
- SetPrototype.merge = SetPrototype.concat = SetPrototype.union;
- SetPrototype.withMutations = withMutations;
- SetPrototype.asImmutable = asImmutable;
- SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable;
- SetPrototype['@@transducer/step'] = function (result, arr) {
- return result.add(arr);
- };
- SetPrototype['@@transducer/result'] = function (obj) {
- return obj.asImmutable();
- };
-
- SetPrototype.__empty = emptySet;
- SetPrototype.__make = makeSet;
-
- function updateSet(set, newMap) {
- if (set.__ownerID) {
- set.size = newMap.size;
- set._map = newMap;
- return set;
- }
- return newMap === set._map
- ? set
- : newMap.size === 0
- ? set.__empty()
- : set.__make(newMap);
- }
-
- function makeSet(map, ownerID) {
- var set = Object.create(SetPrototype);
- set.size = map ? map.size : 0;
- set._map = map;
- set.__ownerID = ownerID;
- return set;
- }
-
- var EMPTY_SET;
- function emptySet() {
- return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
- }
-
- /**
- * Returns the value at the provided key path starting at the provided
- * collection, or notSetValue if the key path is not defined.
- *
- * A functional alternative to `collection.getIn(keypath)` which will also
- * work with plain Objects and Arrays.
- */
- function getIn$1(collection, searchKeyPath, notSetValue) {
- var keyPath = coerceKeyPath(searchKeyPath);
- var i = 0;
- while (i !== keyPath.length) {
- // @ts-expect-error keyPath[i++] can not be undefined by design
- collection = get(collection, keyPath[i++], NOT_SET);
- if (collection === NOT_SET) {
- return notSetValue;
- }
- }
- return collection;
- }
-
- function getIn(searchKeyPath, notSetValue) {
- return getIn$1(this, searchKeyPath, notSetValue);
- }
-
- /**
- * Returns true if the key path is defined in the provided collection.
- *
- * A functional alternative to `collection.hasIn(keypath)` which will also
- * work with plain Objects and Arrays.
- */
- function hasIn$1(collection, keyPath) {
- return getIn$1(collection, keyPath, NOT_SET) !== NOT_SET;
- }
-
- function hasIn(searchKeyPath) {
- return hasIn$1(this, searchKeyPath);
- }
-
- function toObject() {
- assertNotInfinite(this.size);
- var object = {};
- this.__iterate(function (v, k) {
- if (isProtoKey(k)) {
- return;
- }
-
- object[k] = v;
- });
- return object;
- }
-
- function toJS(value) {
- if (!value || typeof value !== 'object') {
- return value;
- }
- if (!isCollection(value)) {
- if (!isDataStructure(value)) {
- return value;
- }
- // @ts-expect-error until Seq has been migrated to TypeScript
- value = Seq(value);
- }
- if (isKeyed(value)) {
- var result$1 = {};
- // @ts-expect-error `__iterate` exists on all Keyed collections but method is not defined in the type
- value.__iterate(function (v, k) {
- if (isProtoKey(k)) {
- return;
- }
- result$1[k] = toJS(v);
- });
- return result$1;
- }
- var result = [];
- // @ts-expect-error value "should" be a non-keyed collection, but we may need to assert for stricter types
- value.__iterate(function (v) {
- result.push(toJS(v));
- });
- return result;
- }
-
- function hashCollection(collection) {
- // @ts-expect-error Migrate to CollectionImpl in v6
- if (collection.size === Infinity) {
- return 0;
- }
- var ordered = isOrdered(collection);
- var keyed = isKeyed(collection);
- var h = ordered ? 1 : 0;
- // @ts-expect-error Migrate to CollectionImpl in v6
- collection.__iterate(keyed
- ? ordered
- ? function (v, k) {
- h = (31 * h + hashMerge(hash(v), hash(k))) | 0;
- }
- : function (v, k) {
- h = (h + hashMerge(hash(v), hash(k))) | 0;
- }
- : ordered
- ? function (v) {
- h = (31 * h + hash(v)) | 0;
- }
- : function (v) {
- h = (h + hash(v)) | 0;
- });
- // @ts-expect-error Migrate to CollectionImpl in v6
- return murmurHashOfSize(collection.size, h);
- }
- function murmurHashOfSize(size, h) {
- h = imul(h, 0xcc9e2d51);
- h = imul((h << 15) | (h >>> -15), 0x1b873593);
- h = imul((h << 13) | (h >>> -13), 5);
- h = ((h + 0xe6546b64) | 0) ^ size;
- h = imul(h ^ (h >>> 16), 0x85ebca6b);
- h = imul(h ^ (h >>> 13), 0xc2b2ae35);
- h = smi(h ^ (h >>> 16));
- return h;
- }
- function hashMerge(a, b) {
- return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int
- }
-
- /**
- * Contributes additional methods to a constructor
- */
- function mixin(ctor,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- methods) {
- var keyCopier = function (key) {
- // @ts-expect-error how to handle symbol ?
- ctor.prototype[key] = methods[key];
- };
- Object.keys(methods).forEach(keyCopier);
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- Object.getOwnPropertySymbols &&
- Object.getOwnPropertySymbols(methods).forEach(keyCopier);
- return ctor;
- }
-
- Collection.Iterator = Iterator;
-
- mixin(Collection, {
- // ### Conversion to other types
-
- toArray: function toArray() {
- assertNotInfinite(this.size);
- var array = new Array(this.size || 0);
- var useTuples = isKeyed(this);
- var i = 0;
- this.__iterate(function (v, k) {
- // Keyed collections produce an array of tuples.
- array[i++] = useTuples ? [k, v] : v;
- });
- return array;
- },
-
- toIndexedSeq: function toIndexedSeq() {
- return new ToIndexedSequence(this);
- },
-
- toJS: function toJS$1() {
- return toJS(this);
- },
-
- toKeyedSeq: function toKeyedSeq() {
- return new ToKeyedSequence(this, true);
- },
-
- toMap: function toMap() {
- // Use Late Binding here to solve the circular dependency.
- return Map(this.toKeyedSeq());
- },
-
- toObject: toObject,
-
- toOrderedMap: function toOrderedMap() {
- // Use Late Binding here to solve the circular dependency.
- return OrderedMap(this.toKeyedSeq());
- },
-
- toOrderedSet: function toOrderedSet() {
- // Use Late Binding here to solve the circular dependency.
- return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
- },
-
- toSet: function toSet() {
- // Use Late Binding here to solve the circular dependency.
- return Set(isKeyed(this) ? this.valueSeq() : this);
- },
-
- toSetSeq: function toSetSeq() {
- return new ToSetSequence(this);
- },
-
- toSeq: function toSeq() {
- return isIndexed(this)
- ? this.toIndexedSeq()
- : isKeyed(this)
- ? this.toKeyedSeq()
- : this.toSetSeq();
- },
-
- toStack: function toStack() {
- // Use Late Binding here to solve the circular dependency.
- return Stack(isKeyed(this) ? this.valueSeq() : this);
- },
-
- toList: function toList() {
- // Use Late Binding here to solve the circular dependency.
- return List(isKeyed(this) ? this.valueSeq() : this);
- },
-
- // ### Common JavaScript methods and properties
-
- toString: function toString() {
- return '[Collection]';
- },
-
- __toString: function __toString(head, tail) {
- if (this.size === 0) {
- return head + tail;
- }
- return (
- head +
- ' ' +
- this.toSeq().map(this.__toStringMapper).join(', ') +
- ' ' +
- tail
- );
- },
-
- // ### ES6 Collection methods (ES6 Array and Map)
-
- concat: function concat() {
- var values = [], len = arguments.length;
- while ( len-- ) values[ len ] = arguments[ len ];
-
- return reify(this, concatFactory(this, values));
- },
-
- includes: function includes(searchValue) {
- return this.some(function (value) { return is(value, searchValue); });
- },
-
- entries: function entries() {
- return this.__iterator(ITERATE_ENTRIES);
- },
-
- every: function every(predicate, context) {
- assertNotInfinite(this.size);
- var returnValue = true;
- this.__iterate(function (v, k, c) {
- if (!predicate.call(context, v, k, c)) {
- returnValue = false;
- return false;
- }
- });
- return returnValue;
- },
-
- filter: function filter(predicate, context) {
- return reify(this, filterFactory(this, predicate, context, true));
- },
-
- partition: function partition(predicate, context) {
- return partitionFactory(this, predicate, context);
- },
-
- find: function find(predicate, context, notSetValue) {
- var entry = this.findEntry(predicate, context);
- return entry ? entry[1] : notSetValue;
- },
-
- forEach: function forEach(sideEffect, context) {
- assertNotInfinite(this.size);
- return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
- },
-
- join: function join(separator) {
- assertNotInfinite(this.size);
- separator = separator !== undefined ? '' + separator : ',';
- var joined = '';
- var isFirst = true;
- this.__iterate(function (v) {
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- isFirst ? (isFirst = false) : (joined += separator);
- joined += v !== null && v !== undefined ? v.toString() : '';
- });
- return joined;
- },
-
- keys: function keys() {
- return this.__iterator(ITERATE_KEYS);
- },
-
- map: function map(mapper, context) {
- return reify(this, mapFactory(this, mapper, context));
- },
-
- reduce: function reduce$1(reducer, initialReduction, context) {
- return reduce(
- this,
- reducer,
- initialReduction,
- context,
- arguments.length < 2,
- false
- );
- },
-
- reduceRight: function reduceRight(reducer, initialReduction, context) {
- return reduce(
- this,
- reducer,
- initialReduction,
- context,
- arguments.length < 2,
- true
- );
- },
-
- reverse: function reverse() {
- return reify(this, reverseFactory(this, true));
- },
-
- slice: function slice(begin, end) {
- return reify(this, sliceFactory(this, begin, end, true));
- },
-
- some: function some(predicate, context) {
- assertNotInfinite(this.size);
- var returnValue = false;
- this.__iterate(function (v, k, c) {
- if (predicate.call(context, v, k, c)) {
- returnValue = true;
- return false;
- }
- });
- return returnValue;
- },
-
- sort: function sort(comparator) {
- return reify(this, sortFactory(this, comparator));
- },
-
- values: function values() {
- return this.__iterator(ITERATE_VALUES);
- },
-
- // ### More sequential methods
-
- butLast: function butLast() {
- return this.slice(0, -1);
- },
-
- isEmpty: function isEmpty() {
- return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; });
- },
-
- count: function count(predicate, context) {
- return ensureSize(
- predicate ? this.toSeq().filter(predicate, context) : this
- );
- },
-
- countBy: function countBy(grouper, context) {
- return countByFactory(this, grouper, context);
- },
-
- equals: function equals(other) {
- return deepEqual(this, other);
- },
-
- entrySeq: function entrySeq() {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- var collection = this;
- if (collection._cache) {
- // We cache as an entries array, so we can just return the cache!
- return new ArraySeq(collection._cache);
- }
- var entriesSequence = collection.toSeq().map(entryMapper).toIndexedSeq();
- entriesSequence.fromEntrySeq = function () { return collection.toSeq(); };
- return entriesSequence;
- },
-
- filterNot: function filterNot(predicate, context) {
- return this.filter(not(predicate), context);
- },
-
- findEntry: function findEntry(predicate, context, notSetValue) {
- var found = notSetValue;
- this.__iterate(function (v, k, c) {
- if (predicate.call(context, v, k, c)) {
- found = [k, v];
- return false;
- }
- });
- return found;
- },
-
- findKey: function findKey(predicate, context) {
- var entry = this.findEntry(predicate, context);
- return entry && entry[0];
- },
-
- findLast: function findLast(predicate, context, notSetValue) {
- return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
- },
-
- findLastEntry: function findLastEntry(predicate, context, notSetValue) {
- return this.toKeyedSeq()
- .reverse()
- .findEntry(predicate, context, notSetValue);
- },
-
- findLastKey: function findLastKey(predicate, context) {
- return this.toKeyedSeq().reverse().findKey(predicate, context);
- },
-
- first: function first(notSetValue) {
- return this.find(returnTrue, null, notSetValue);
- },
-
- flatMap: function flatMap(mapper, context) {
- return reify(this, flatMapFactory(this, mapper, context));
- },
-
- flatten: function flatten(depth) {
- return reify(this, flattenFactory(this, depth, true));
- },
-
- fromEntrySeq: function fromEntrySeq() {
- return new FromEntriesSequence(this);
- },
-
- get: function get(searchKey, notSetValue) {
- return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue);
- },
-
- getIn: getIn,
-
- groupBy: function groupBy(grouper, context) {
- return groupByFactory(this, grouper, context);
- },
-
- has: function has(searchKey) {
- return this.get(searchKey, NOT_SET) !== NOT_SET;
- },
-
- hasIn: hasIn,
-
- isSubset: function isSubset(iter) {
- iter = typeof iter.includes === 'function' ? iter : Collection(iter);
- return this.every(function (value) { return iter.includes(value); });
- },
-
- isSuperset: function isSuperset(iter) {
- iter = typeof iter.isSubset === 'function' ? iter : Collection(iter);
- return iter.isSubset(this);
- },
-
- keyOf: function keyOf(searchValue) {
- return this.findKey(function (value) { return is(value, searchValue); });
- },
-
- keySeq: function keySeq() {
- return this.toSeq().map(keyMapper).toIndexedSeq();
- },
-
- last: function last(notSetValue) {
- return this.toSeq().reverse().first(notSetValue);
- },
-
- lastKeyOf: function lastKeyOf(searchValue) {
- return this.toKeyedSeq().reverse().keyOf(searchValue);
- },
-
- max: function max(comparator) {
- return maxFactory(this, comparator);
- },
-
- maxBy: function maxBy(mapper, comparator) {
- return maxFactory(this, comparator, mapper);
- },
-
- min: function min(comparator) {
- return maxFactory(
- this,
- comparator ? neg(comparator) : defaultNegComparator
- );
- },
-
- minBy: function minBy(mapper, comparator) {
- return maxFactory(
- this,
- comparator ? neg(comparator) : defaultNegComparator,
- mapper
- );
- },
-
- rest: function rest() {
- return this.slice(1);
- },
-
- skip: function skip(amount) {
- return amount === 0 ? this : this.slice(Math.max(0, amount));
- },
-
- skipLast: function skipLast(amount) {
- return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
- },
-
- skipWhile: function skipWhile(predicate, context) {
- return reify(this, skipWhileFactory(this, predicate, context, true));
- },
-
- skipUntil: function skipUntil(predicate, context) {
- return this.skipWhile(not(predicate), context);
- },
-
- sortBy: function sortBy(mapper, comparator) {
- return reify(this, sortFactory(this, comparator, mapper));
- },
-
- take: function take(amount) {
- return this.slice(0, Math.max(0, amount));
- },
-
- takeLast: function takeLast(amount) {
- return this.slice(-Math.max(0, amount));
- },
-
- takeWhile: function takeWhile(predicate, context) {
- return reify(this, takeWhileFactory(this, predicate, context));
- },
-
- takeUntil: function takeUntil(predicate, context) {
- return this.takeWhile(not(predicate), context);
- },
-
- update: function update(fn) {
- return fn(this);
- },
-
- valueSeq: function valueSeq() {
- return this.toIndexedSeq();
- },
-
- // ### Hashable Object
-
- hashCode: function hashCode() {
- return this.__hash || (this.__hash = hashCollection(this));
- },
-
- // ### Internal
-
- // abstract __iterate(fn, reverse)
-
- // abstract __iterator(type, reverse)
- });
-
- var CollectionPrototype = Collection.prototype;
- CollectionPrototype[IS_COLLECTION_SYMBOL] = true;
- CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values;
- CollectionPrototype.toJSON = CollectionPrototype.toArray;
- CollectionPrototype.__toStringMapper = quoteString;
- CollectionPrototype.inspect = CollectionPrototype.toSource = function () {
- return this.toString();
- };
- CollectionPrototype.chain = CollectionPrototype.flatMap;
- CollectionPrototype.contains = CollectionPrototype.includes;
-
- mixin(KeyedCollection, {
- // ### More sequential methods
-
- flip: function flip() {
- return reify(this, flipFactory(this));
- },
-
- mapEntries: function mapEntries(mapper, context) {
- var this$1$1 = this;
-
- var iterations = 0;
- return reify(
- this,
- this.toSeq()
- .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1$1); })
- .fromEntrySeq()
- );
- },
-
- mapKeys: function mapKeys(mapper, context) {
- var this$1$1 = this;
-
- return reify(
- this,
- this.toSeq()
- .flip()
- .map(function (k, v) { return mapper.call(context, k, v, this$1$1); })
- .flip()
- );
- },
- });
-
- var KeyedCollectionPrototype = KeyedCollection.prototype;
- KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true;
- KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries;
- KeyedCollectionPrototype.toJSON = toObject;
- KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); };
-
- mixin(IndexedCollection, {
- // ### Conversion to other types
-
- toKeyedSeq: function toKeyedSeq() {
- return new ToKeyedSequence(this, false);
- },
-
- // ### ES6 Collection methods (ES6 Array and Map)
-
- filter: function filter(predicate, context) {
- return reify(this, filterFactory(this, predicate, context, false));
- },
-
- findIndex: function findIndex(predicate, context) {
- var entry = this.findEntry(predicate, context);
- return entry ? entry[0] : -1;
- },
-
- indexOf: function indexOf(searchValue) {
- var key = this.keyOf(searchValue);
- return key === undefined ? -1 : key;
- },
-
- lastIndexOf: function lastIndexOf(searchValue) {
- var key = this.lastKeyOf(searchValue);
- return key === undefined ? -1 : key;
- },
-
- reverse: function reverse() {
- return reify(this, reverseFactory(this, false));
- },
-
- slice: function slice(begin, end) {
- return reify(this, sliceFactory(this, begin, end, false));
- },
-
- splice: function splice(index, removeNum /*, ...values*/) {
- var numArgs = arguments.length;
- removeNum = Math.max(removeNum || 0, 0);
- if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
- return this;
- }
- // If index is negative, it should resolve relative to the size of the
- // collection. However size may be expensive to compute if not cached, so
- // only call count() if the number is in fact negative.
- index = resolveBegin(index, index < 0 ? this.count() : this.size);
- var spliced = this.slice(0, index);
- return reify(
- this,
- numArgs === 1
- ? spliced
- : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
- );
- },
-
- // ### More collection methods
-
- findLastIndex: function findLastIndex(predicate, context) {
- var entry = this.findLastEntry(predicate, context);
- return entry ? entry[0] : -1;
- },
-
- first: function first(notSetValue) {
- return this.get(0, notSetValue);
- },
-
- flatten: function flatten(depth) {
- return reify(this, flattenFactory(this, depth, false));
- },
-
- get: function get(index, notSetValue) {
- index = wrapIndex(this, index);
- return index < 0 ||
- this.size === Infinity ||
- (this.size !== undefined && index > this.size)
- ? notSetValue
- : this.find(function (_, key) { return key === index; }, undefined, notSetValue);
- },
-
- has: function has(index) {
- index = wrapIndex(this, index);
-
- return (
- index >= 0 &&
- (this.size !== undefined
- ? this.size === Infinity || index < this.size
- : this.find(function (_, key) { return key === index; }, undefined, NOT_SET) !== NOT_SET)
- );
- },
-
- interpose: function interpose(separator) {
- return reify(this, interposeFactory(this, separator));
- },
-
- interleave: function interleave(/*...collections*/) {
- var collections = [this].concat(arrCopy(arguments));
- var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections);
- var interleaved = zipped.flatten(true);
- if (zipped.size) {
- interleaved.size = zipped.size * collections.length;
- }
- return reify(this, interleaved);
- },
-
- keySeq: function keySeq() {
- return Range(0, this.size);
- },
-
- last: function last(notSetValue) {
- return this.get(-1, notSetValue);
- },
-
- skipWhile: function skipWhile(predicate, context) {
- return reify(this, skipWhileFactory(this, predicate, context, false));
- },
-
- zip: function zip(/*, ...collections */) {
- var collections = [this].concat(arrCopy(arguments));
- return reify(this, zipWithFactory(this, defaultZipper, collections));
- },
-
- zipAll: function zipAll(/*, ...collections */) {
- var collections = [this].concat(arrCopy(arguments));
- return reify(this, zipWithFactory(this, defaultZipper, collections, true));
- },
-
- zipWith: function zipWith(zipper /*, ...collections */) {
- var collections = arrCopy(arguments);
- collections[0] = this;
- return reify(this, zipWithFactory(this, zipper, collections));
- },
- });
-
- var IndexedCollectionPrototype = IndexedCollection.prototype;
- IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true;
- IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true;
-
- mixin(SetCollection, {
- // ### ES6 Collection methods (ES6 Array and Map)
-
- get: function get(value, notSetValue) {
- return this.has(value) ? value : notSetValue;
- },
-
- includes: function includes(value) {
- return this.has(value);
- },
-
- // ### More sequential methods
-
- keySeq: function keySeq() {
- return this.valueSeq();
- },
- });
-
- var SetCollectionPrototype = SetCollection.prototype;
- SetCollectionPrototype.has = CollectionPrototype.includes;
- SetCollectionPrototype.contains = SetCollectionPrototype.includes;
- SetCollectionPrototype.keys = SetCollectionPrototype.values;
-
- // Mixin subclasses
-
- mixin(KeyedSeq, KeyedCollectionPrototype);
- mixin(IndexedSeq, IndexedCollectionPrototype);
- mixin(SetSeq, SetCollectionPrototype);
-
- // #pragma Helper functions
-
- function defaultZipper() {
- return arrCopy(arguments);
- }
-
- /**
- * True if `maybeOrderedSet` is an OrderedSet.
- */
- function isOrderedSet(maybeOrderedSet) {
- return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
- }
-
- var OrderedSet = /*@__PURE__*/(function (Set) {
- function OrderedSet(value) {
- // eslint-disable-next-line no-constructor-return
- return value === undefined || value === null
- ? emptyOrderedSet()
- : isOrderedSet(value)
- ? value
- : emptyOrderedSet().withMutations(function (set) {
- var iter = SetCollection(value);
- assertNotInfinite(iter.size);
- iter.forEach(function (v) { return set.add(v); });
- });
- }
-
- if ( Set ) OrderedSet.__proto__ = Set;
- OrderedSet.prototype = Object.create( Set && Set.prototype );
- OrderedSet.prototype.constructor = OrderedSet;
-
- OrderedSet.of = function of (/*...values*/) {
- return this(arguments);
- };
-
- OrderedSet.fromKeys = function fromKeys (value) {
- return this(KeyedCollection(value).keySeq());
- };
-
- OrderedSet.prototype.toString = function toString () {
- return this.__toString('OrderedSet {', '}');
- };
-
- return OrderedSet;
- }(Set));
-
- OrderedSet.isOrderedSet = isOrderedSet;
-
- var OrderedSetPrototype = OrderedSet.prototype;
- OrderedSetPrototype[IS_ORDERED_SYMBOL] = true;
- OrderedSetPrototype.zip = IndexedCollectionPrototype.zip;
- OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith;
- OrderedSetPrototype.zipAll = IndexedCollectionPrototype.zipAll;
-
- OrderedSetPrototype.__empty = emptyOrderedSet;
- OrderedSetPrototype.__make = makeOrderedSet;
-
- function makeOrderedSet(map, ownerID) {
- var set = Object.create(OrderedSetPrototype);
- set.size = map ? map.size : 0;
- set._map = map;
- set.__ownerID = ownerID;
- return set;
- }
-
- var EMPTY_ORDERED_SET;
- function emptyOrderedSet() {
- return (
- EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()))
- );
- }
-
- /**
- * Describes which item in a pair should be placed first when sorting
- */
- var PairSorting = {
- LeftThenRight: -1,
- RightThenLeft: 1,
- };
-
- function throwOnInvalidDefaultValues(defaultValues) {
- if (isRecord(defaultValues)) {
- throw new Error(
- 'Can not call `Record` with an immutable Record as default values. Use a plain javascript object instead.'
- );
- }
-
- if (isImmutable(defaultValues)) {
- throw new Error(
- 'Can not call `Record` with an immutable Collection as default values. Use a plain javascript object instead.'
- );
- }
-
- if (defaultValues === null || typeof defaultValues !== 'object') {
- throw new Error(
- 'Can not call `Record` with a non-object as default values. Use a plain javascript object instead.'
- );
- }
- }
-
- var Record = function Record(defaultValues, name) {
- var hasInitialized;
-
- throwOnInvalidDefaultValues(defaultValues);
-
- var RecordType = function Record(values) {
- var this$1$1 = this;
-
- if (values instanceof RecordType) {
- return values;
- }
- if (!(this instanceof RecordType)) {
- return new RecordType(values);
- }
- if (!hasInitialized) {
- hasInitialized = true;
- var keys = Object.keys(defaultValues);
- var indices = (RecordTypePrototype._indices = {});
- // Deprecated: left to attempt not to break any external code which
- // relies on a ._name property existing on record instances.
- // Use Record.getDescriptiveName() instead
- RecordTypePrototype._name = name;
- RecordTypePrototype._keys = keys;
- RecordTypePrototype._defaultValues = defaultValues;
- for (var i = 0; i < keys.length; i++) {
- var propName = keys[i];
- indices[propName] = i;
- if (RecordTypePrototype[propName]) {
- /* eslint-disable no-console */
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- typeof console === 'object' &&
- console.warn &&
- console.warn(
- 'Cannot define ' +
- recordName(this) +
- ' with property "' +
- propName +
- '" since that property name is part of the Record API.'
- );
- /* eslint-enable no-console */
- } else {
- setProp(RecordTypePrototype, propName);
- }
- }
- }
- this.__ownerID = undefined;
- this._values = List().withMutations(function (l) {
- l.setSize(this$1$1._keys.length);
- KeyedCollection(values).forEach(function (v, k) {
- l.set(this$1$1._indices[k], v === this$1$1._defaultValues[k] ? undefined : v);
- });
- });
- return this;
- };
-
- var RecordTypePrototype = (RecordType.prototype =
- Object.create(RecordPrototype));
- RecordTypePrototype.constructor = RecordType;
-
- if (name) {
- RecordType.displayName = name;
- }
-
- // eslint-disable-next-line no-constructor-return
- return RecordType;
- };
-
- Record.prototype.toString = function toString () {
- var str = recordName(this) + ' { ';
- var keys = this._keys;
- var k;
- for (var i = 0, l = keys.length; i !== l; i++) {
- k = keys[i];
- str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k));
- }
- return str + ' }';
- };
-
- Record.prototype.equals = function equals (other) {
- return (
- this === other ||
- (isRecord(other) && recordSeq(this).equals(recordSeq(other)))
- );
- };
-
- Record.prototype.hashCode = function hashCode () {
- return recordSeq(this).hashCode();
- };
-
- // @pragma Access
-
- Record.prototype.has = function has (k) {
- return this._indices.hasOwnProperty(k);
- };
-
- Record.prototype.get = function get (k, notSetValue) {
- if (!this.has(k)) {
- return notSetValue;
- }
- var index = this._indices[k];
- var value = this._values.get(index);
- return value === undefined ? this._defaultValues[k] : value;
- };
-
- // @pragma Modification
-
- Record.prototype.set = function set (k, v) {
- if (this.has(k)) {
- var newValues = this._values.set(
- this._indices[k],
- v === this._defaultValues[k] ? undefined : v
- );
- if (newValues !== this._values && !this.__ownerID) {
- return makeRecord(this, newValues);
- }
- }
- return this;
- };
-
- Record.prototype.remove = function remove (k) {
- return this.set(k);
- };
-
- Record.prototype.clear = function clear () {
- var newValues = this._values.clear().setSize(this._keys.length);
-
- return this.__ownerID ? this : makeRecord(this, newValues);
- };
-
- Record.prototype.wasAltered = function wasAltered () {
- return this._values.wasAltered();
- };
-
- Record.prototype.toSeq = function toSeq () {
- return recordSeq(this);
- };
-
- Record.prototype.toJS = function toJS$1 () {
- return toJS(this);
- };
-
- Record.prototype.entries = function entries () {
- return this.__iterator(ITERATE_ENTRIES);
- };
-
- Record.prototype.__iterator = function __iterator (type, reverse) {
- return recordSeq(this).__iterator(type, reverse);
- };
-
- Record.prototype.__iterate = function __iterate (fn, reverse) {
- return recordSeq(this).__iterate(fn, reverse);
- };
-
- Record.prototype.__ensureOwner = function __ensureOwner (ownerID) {
- if (ownerID === this.__ownerID) {
- return this;
- }
- var newValues = this._values.__ensureOwner(ownerID);
- if (!ownerID) {
- this.__ownerID = ownerID;
- this._values = newValues;
- return this;
- }
- return makeRecord(this, newValues, ownerID);
- };
-
- Record.isRecord = isRecord;
- Record.getDescriptiveName = recordName;
- var RecordPrototype = Record.prototype;
- RecordPrototype[IS_RECORD_SYMBOL] = true;
- RecordPrototype[DELETE] = RecordPrototype.remove;
- RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn;
- RecordPrototype.getIn = getIn;
- RecordPrototype.hasIn = CollectionPrototype.hasIn;
- RecordPrototype.merge = merge$1;
- RecordPrototype.mergeWith = mergeWith$1;
- RecordPrototype.mergeIn = mergeIn;
- RecordPrototype.mergeDeep = mergeDeep;
- RecordPrototype.mergeDeepWith = mergeDeepWith;
- RecordPrototype.mergeDeepIn = mergeDeepIn;
- RecordPrototype.setIn = setIn;
- RecordPrototype.update = update;
- RecordPrototype.updateIn = updateIn$1;
- RecordPrototype.withMutations = withMutations;
- RecordPrototype.asMutable = asMutable;
- RecordPrototype.asImmutable = asImmutable;
- RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries;
- RecordPrototype.toJSON = RecordPrototype.toObject =
- CollectionPrototype.toObject;
- RecordPrototype.inspect = RecordPrototype.toSource = function () {
- return this.toString();
- };
-
- function makeRecord(likeRecord, values, ownerID) {
- var record = Object.create(Object.getPrototypeOf(likeRecord));
- record._values = values;
- record.__ownerID = ownerID;
- return record;
- }
-
- function recordName(record) {
- return record.constructor.displayName || record.constructor.name || 'Record';
- }
-
- function recordSeq(record) {
- return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; }));
- }
-
- function setProp(prototype, name) {
- try {
- Object.defineProperty(prototype, name, {
- get: function () {
- return this.get(name);
- },
- set: function (value) {
- invariant(this.__ownerID, 'Cannot set on an immutable record.');
- this.set(name, value);
- },
- });
- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO enable eslint here
- } catch (error) {
- // Object.defineProperty failed. Probably IE8.
- }
- }
-
- /**
- * Returns a lazy Seq of `value` repeated `times` times. When `times` is
- * undefined, returns an infinite sequence of `value`.
- */
- var Repeat = /*@__PURE__*/(function (IndexedSeq) {
- function Repeat(value, times) {
- if (!(this instanceof Repeat)) {
- // eslint-disable-next-line no-constructor-return
- return new Repeat(value, times);
- }
- this._value = value;
- this.size = times === undefined ? Infinity : Math.max(0, times);
- if (this.size === 0) {
- if (EMPTY_REPEAT) {
- // eslint-disable-next-line no-constructor-return
- return EMPTY_REPEAT;
- }
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- EMPTY_REPEAT = this;
- }
- }
-
- if ( IndexedSeq ) Repeat.__proto__ = IndexedSeq;
- Repeat.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
- Repeat.prototype.constructor = Repeat;
-
- Repeat.prototype.toString = function toString () {
- if (this.size === 0) {
- return 'Repeat []';
- }
- return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
- };
-
- Repeat.prototype.get = function get (index, notSetValue) {
- return this.has(index) ? this._value : notSetValue;
- };
-
- Repeat.prototype.includes = function includes (searchValue) {
- return is(this._value, searchValue);
- };
-
- Repeat.prototype.slice = function slice (begin, end) {
- var size = this.size;
- return wholeSlice(begin, end, size)
- ? this
- : new Repeat(
- this._value,
- resolveEnd(end, size) - resolveBegin(begin, size)
- );
- };
-
- Repeat.prototype.reverse = function reverse () {
- return this;
- };
-
- Repeat.prototype.indexOf = function indexOf (searchValue) {
- if (this.size !== 0 && is(this._value, searchValue)) {
- return 0;
- }
- return -1;
- };
-
- Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) {
- if (this.size !== 0 && is(this._value, searchValue)) {
- return this.size - 1;
- }
- return -1;
- };
-
- Repeat.prototype.__iterate = function __iterate (fn, reverse) {
- var size = this.size;
- var i = 0;
- while (i !== size) {
- if (fn(this._value, reverse ? size - ++i : i++, this) === false) {
- break;
- }
- }
- return i;
- };
-
- Repeat.prototype.__iterator = function __iterator (type, reverse) {
- var this$1$1 = this;
-
- var size = this.size;
- var i = 0;
- return new Iterator(function () { return i === size
- ? iteratorDone()
- : iteratorValue(type, reverse ? size - ++i : i++, this$1$1._value); }
- );
- };
-
- Repeat.prototype.equals = function equals (other) {
- return other instanceof Repeat
- ? is(this._value, other._value)
- : deepEqual(this, other);
- };
-
- return Repeat;
- }(IndexedSeq));
-
- var EMPTY_REPEAT;
-
- function fromJS(value, converter) {
- return fromJSWith(
- [],
- converter || defaultConverter,
- value,
- '',
- converter && converter.length > 2 ? [] : undefined,
- { '': value }
- );
- }
-
- function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
- if (
- typeof value !== 'string' &&
- !isImmutable(value) &&
- (isArrayLike(value) || hasIterator(value) || isPlainObject(value))
- ) {
- if (~stack.indexOf(value)) {
- throw new TypeError('Cannot convert circular structure to Immutable');
- }
- stack.push(value);
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- keyPath && key !== '' && keyPath.push(key);
- var converted = converter.call(
- parentValue,
- key,
- Seq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }
- ),
- keyPath && keyPath.slice()
- );
- stack.pop();
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here
- keyPath && keyPath.pop();
- return converted;
- }
- return value;
- }
-
- function defaultConverter(k, v) {
- // Effectively the opposite of "Collection.toSeq()"
- return isIndexed(v) ? v.toList() : isKeyed(v) ? v.toMap() : v.toSet();
- }
-
- var version = "5.1.9";
-
- /* eslint-disable import/order */
-
- // Note: Iterable is deprecated
- var Iterable = Collection;
-
- exports.Collection = Collection;
- exports.Iterable = Iterable;
- exports.List = List;
- exports.Map = Map;
- exports.OrderedMap = OrderedMap;
- exports.OrderedSet = OrderedSet;
- exports.PairSorting = PairSorting;
- exports.Range = Range;
- exports.Record = Record;
- exports.Repeat = Repeat;
- exports.Seq = Seq;
- exports.Set = Set;
- exports.Stack = Stack;
- exports.fromJS = fromJS;
- exports.get = get;
- exports.getIn = getIn$1;
- exports.has = has;
- exports.hasIn = hasIn$1;
- exports.hash = hash;
- exports.is = is;
- exports.isAssociative = isAssociative;
- exports.isCollection = isCollection;
- exports.isImmutable = isImmutable;
- exports.isIndexed = isIndexed;
- exports.isKeyed = isKeyed;
- exports.isList = isList;
- exports.isMap = isMap;
- exports.isOrdered = isOrdered;
- exports.isOrderedMap = isOrderedMap;
- exports.isOrderedSet = isOrderedSet;
- exports.isPlainObject = isPlainObject;
- exports.isRecord = isRecord;
- exports.isSeq = isSeq;
- exports.isSet = isSet;
- exports.isStack = isStack;
- exports.isValueObject = isValueObject;
- exports.merge = merge;
- exports.mergeDeep = mergeDeep$1;
- exports.mergeDeepWith = mergeDeepWith$1;
- exports.mergeWith = mergeWith;
- exports.remove = remove;
- exports.removeIn = removeIn;
- exports.set = set;
- exports.setIn = setIn$1;
- exports.update = update$1;
- exports.updateIn = updateIn;
- exports.version = version;
-
-}));
-
-},{}],76:[function(require,module,exports){
-'use strict';
-
-module.exports = Number.isFinite || function (value) {
- return !(typeof value !== 'number' || value !== value || value === Infinity || value === -Infinity);
-};
-
-},{}],77:[function(require,module,exports){
-// https://github.com/paulmillr/es6-shim
-// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isinteger
-var isFinite = require("is-finite");
-module.exports = Number.isInteger || function(val) {
- return typeof val === "number" &&
- isFinite(val) &&
- Math.floor(val) === val;
-};
-
-},{"is-finite":76}],78:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, '__esModule', { value: true });
-
-function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
- }
-}
-function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", {
- writable: false
- });
- return Constructor;
-}
-function _extends() {
- _extends = Object.assign ? Object.assign.bind() : function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
-}
-function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf(subClass, superClass);
-}
-function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
-}
-function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
-}
-function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
-}
-function _construct(Parent, args, Class) {
- if (_isNativeReflectConstruct()) {
- _construct = Reflect.construct.bind();
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
-}
-function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
-}
-function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !_isNativeFunction(Class)) return Class;
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
- _cache.set(Class, Wrapper);
- }
- function Wrapper() {
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
- }
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return _setPrototypeOf(Wrapper, Class);
- };
- return _wrapNativeSuper(Class);
-}
-function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
- return target;
-}
-function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
-}
-function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
- return arr2;
-}
-function _createForOfIteratorHelperLoose(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (it) return (it = it.call(o)).next.bind(it);
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
- return function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- };
- }
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
-function _toPrimitive(input, hint) {
- if (typeof input !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (typeof res !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return (hint === "string" ? String : Number)(input);
-}
-function _toPropertyKey(arg) {
- var key = _toPrimitive(arg, "string");
- return typeof key === "symbol" ? key : String(key);
-}
-
-// these aren't really private, but nor are they really useful to document
-/**
- * @private
- */
-var LuxonError = /*#__PURE__*/function (_Error) {
- _inheritsLoose(LuxonError, _Error);
- function LuxonError() {
- return _Error.apply(this, arguments) || this;
- }
- return LuxonError;
-}( /*#__PURE__*/_wrapNativeSuper(Error));
-/**
- * @private
- */
-var InvalidDateTimeError = /*#__PURE__*/function (_LuxonError) {
- _inheritsLoose(InvalidDateTimeError, _LuxonError);
- function InvalidDateTimeError(reason) {
- return _LuxonError.call(this, "Invalid DateTime: " + reason.toMessage()) || this;
- }
- return InvalidDateTimeError;
-}(LuxonError);
-
-/**
- * @private
- */
-var InvalidIntervalError = /*#__PURE__*/function (_LuxonError2) {
- _inheritsLoose(InvalidIntervalError, _LuxonError2);
- function InvalidIntervalError(reason) {
- return _LuxonError2.call(this, "Invalid Interval: " + reason.toMessage()) || this;
- }
- return InvalidIntervalError;
-}(LuxonError);
-
-/**
- * @private
- */
-var InvalidDurationError = /*#__PURE__*/function (_LuxonError3) {
- _inheritsLoose(InvalidDurationError, _LuxonError3);
- function InvalidDurationError(reason) {
- return _LuxonError3.call(this, "Invalid Duration: " + reason.toMessage()) || this;
- }
- return InvalidDurationError;
-}(LuxonError);
-
-/**
- * @private
- */
-var ConflictingSpecificationError = /*#__PURE__*/function (_LuxonError4) {
- _inheritsLoose(ConflictingSpecificationError, _LuxonError4);
- function ConflictingSpecificationError() {
- return _LuxonError4.apply(this, arguments) || this;
- }
- return ConflictingSpecificationError;
-}(LuxonError);
-
-/**
- * @private
- */
-var InvalidUnitError = /*#__PURE__*/function (_LuxonError5) {
- _inheritsLoose(InvalidUnitError, _LuxonError5);
- function InvalidUnitError(unit) {
- return _LuxonError5.call(this, "Invalid unit " + unit) || this;
- }
- return InvalidUnitError;
-}(LuxonError);
-
-/**
- * @private
- */
-var InvalidArgumentError = /*#__PURE__*/function (_LuxonError6) {
- _inheritsLoose(InvalidArgumentError, _LuxonError6);
- function InvalidArgumentError() {
- return _LuxonError6.apply(this, arguments) || this;
- }
- return InvalidArgumentError;
-}(LuxonError);
-
-/**
- * @private
- */
-var ZoneIsAbstractError = /*#__PURE__*/function (_LuxonError7) {
- _inheritsLoose(ZoneIsAbstractError, _LuxonError7);
- function ZoneIsAbstractError() {
- return _LuxonError7.call(this, "Zone is an abstract class") || this;
- }
- return ZoneIsAbstractError;
-}(LuxonError);
-
-/**
- * @private
- */
-
-var n = "numeric",
- s = "short",
- l = "long";
-var DATE_SHORT = {
- year: n,
- month: n,
- day: n
-};
-var DATE_MED = {
- year: n,
- month: s,
- day: n
-};
-var DATE_MED_WITH_WEEKDAY = {
- year: n,
- month: s,
- day: n,
- weekday: s
-};
-var DATE_FULL = {
- year: n,
- month: l,
- day: n
-};
-var DATE_HUGE = {
- year: n,
- month: l,
- day: n,
- weekday: l
-};
-var TIME_SIMPLE = {
- hour: n,
- minute: n
-};
-var TIME_WITH_SECONDS = {
- hour: n,
- minute: n,
- second: n
-};
-var TIME_WITH_SHORT_OFFSET = {
- hour: n,
- minute: n,
- second: n,
- timeZoneName: s
-};
-var TIME_WITH_LONG_OFFSET = {
- hour: n,
- minute: n,
- second: n,
- timeZoneName: l
-};
-var TIME_24_SIMPLE = {
- hour: n,
- minute: n,
- hourCycle: "h23"
-};
-var TIME_24_WITH_SECONDS = {
- hour: n,
- minute: n,
- second: n,
- hourCycle: "h23"
-};
-var TIME_24_WITH_SHORT_OFFSET = {
- hour: n,
- minute: n,
- second: n,
- hourCycle: "h23",
- timeZoneName: s
-};
-var TIME_24_WITH_LONG_OFFSET = {
- hour: n,
- minute: n,
- second: n,
- hourCycle: "h23",
- timeZoneName: l
-};
-var DATETIME_SHORT = {
- year: n,
- month: n,
- day: n,
- hour: n,
- minute: n
-};
-var DATETIME_SHORT_WITH_SECONDS = {
- year: n,
- month: n,
- day: n,
- hour: n,
- minute: n,
- second: n
-};
-var DATETIME_MED = {
- year: n,
- month: s,
- day: n,
- hour: n,
- minute: n
-};
-var DATETIME_MED_WITH_SECONDS = {
- year: n,
- month: s,
- day: n,
- hour: n,
- minute: n,
- second: n
-};
-var DATETIME_MED_WITH_WEEKDAY = {
- year: n,
- month: s,
- day: n,
- weekday: s,
- hour: n,
- minute: n
-};
-var DATETIME_FULL = {
- year: n,
- month: l,
- day: n,
- hour: n,
- minute: n,
- timeZoneName: s
-};
-var DATETIME_FULL_WITH_SECONDS = {
- year: n,
- month: l,
- day: n,
- hour: n,
- minute: n,
- second: n,
- timeZoneName: s
-};
-var DATETIME_HUGE = {
- year: n,
- month: l,
- day: n,
- weekday: l,
- hour: n,
- minute: n,
- timeZoneName: l
-};
-var DATETIME_HUGE_WITH_SECONDS = {
- year: n,
- month: l,
- day: n,
- weekday: l,
- hour: n,
- minute: n,
- second: n,
- timeZoneName: l
-};
-
-/**
- * @interface
- */
-var Zone = /*#__PURE__*/function () {
- function Zone() {}
- var _proto = Zone.prototype;
- /**
- * Returns the offset's common name (such as EST) at the specified timestamp
- * @abstract
- * @param {number} ts - Epoch milliseconds for which to get the name
- * @param {Object} opts - Options to affect the format
- * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
- * @param {string} opts.locale - What locale to return the offset name in.
- * @return {string}
- */
- _proto.offsetName = function offsetName(ts, opts) {
- throw new ZoneIsAbstractError();
- }
-
- /**
- * Returns the offset's value as a string
- * @abstract
- * @param {number} ts - Epoch milliseconds for which to get the offset
- * @param {string} format - What style of offset to return.
- * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
- * @return {string}
- */;
- _proto.formatOffset = function formatOffset(ts, format) {
- throw new ZoneIsAbstractError();
- }
-
- /**
- * Return the offset in minutes for this zone at the specified timestamp.
- * @abstract
- * @param {number} ts - Epoch milliseconds for which to compute the offset
- * @return {number}
- */;
- _proto.offset = function offset(ts) {
- throw new ZoneIsAbstractError();
- }
-
- /**
- * Return whether this Zone is equal to another zone
- * @abstract
- * @param {Zone} otherZone - the zone to compare
- * @return {boolean}
- */;
- _proto.equals = function equals(otherZone) {
- throw new ZoneIsAbstractError();
- }
-
- /**
- * Return whether this Zone is valid.
- * @abstract
- * @type {boolean}
- */;
- _createClass(Zone, [{
- key: "type",
- get:
- /**
- * The type of zone
- * @abstract
- * @type {string}
- */
- function get() {
- throw new ZoneIsAbstractError();
- }
-
- /**
- * The name of this zone.
- * @abstract
- * @type {string}
- */
- }, {
- key: "name",
- get: function get() {
- throw new ZoneIsAbstractError();
- }
-
- /**
- * The IANA name of this zone.
- * Defaults to `name` if not overwritten by a subclass.
- * @abstract
- * @type {string}
- */
- }, {
- key: "ianaName",
- get: function get() {
- return this.name;
- }
-
- /**
- * Returns whether the offset is known to be fixed for the whole year.
- * @abstract
- * @type {boolean}
- */
- }, {
- key: "isUniversal",
- get: function get() {
- throw new ZoneIsAbstractError();
- }
- }, {
- key: "isValid",
- get: function get() {
- throw new ZoneIsAbstractError();
- }
- }]);
- return Zone;
-}();
-
-var singleton$1 = null;
-
-/**
- * Represents the local zone for this JavaScript environment.
- * @implements {Zone}
- */
-var SystemZone = /*#__PURE__*/function (_Zone) {
- _inheritsLoose(SystemZone, _Zone);
- function SystemZone() {
- return _Zone.apply(this, arguments) || this;
- }
- var _proto = SystemZone.prototype;
- /** @override **/
- _proto.offsetName = function offsetName(ts, _ref) {
- var format = _ref.format,
- locale = _ref.locale;
- return parseZoneInfo(ts, format, locale);
- }
-
- /** @override **/;
- _proto.formatOffset = function formatOffset$1(ts, format) {
- return formatOffset(this.offset(ts), format);
- }
-
- /** @override **/;
- _proto.offset = function offset(ts) {
- return -new Date(ts).getTimezoneOffset();
- }
-
- /** @override **/;
- _proto.equals = function equals(otherZone) {
- return otherZone.type === "system";
- }
-
- /** @override **/;
- _createClass(SystemZone, [{
- key: "type",
- get: /** @override **/
- function get() {
- return "system";
- }
-
- /** @override **/
- }, {
- key: "name",
- get: function get() {
- return new Intl.DateTimeFormat().resolvedOptions().timeZone;
- }
-
- /** @override **/
- }, {
- key: "isUniversal",
- get: function get() {
- return false;
- }
- }, {
- key: "isValid",
- get: function get() {
- return true;
- }
- }], [{
- key: "instance",
- get:
- /**
- * Get a singleton instance of the local zone
- * @return {SystemZone}
- */
- function get() {
- if (singleton$1 === null) {
- singleton$1 = new SystemZone();
- }
- return singleton$1;
- }
- }]);
- return SystemZone;
-}(Zone);
-
-var dtfCache = new Map();
-function makeDTF(zoneName) {
- var dtf = dtfCache.get(zoneName);
- if (dtf === undefined) {
- dtf = new Intl.DateTimeFormat("en-US", {
- hour12: false,
- timeZone: zoneName,
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- era: "short"
- });
- dtfCache.set(zoneName, dtf);
- }
- return dtf;
-}
-var typeToPos = {
- year: 0,
- month: 1,
- day: 2,
- era: 3,
- hour: 4,
- minute: 5,
- second: 6
-};
-function hackyOffset(dtf, date) {
- var formatted = dtf.format(date).replace(/\u200E/g, ""),
- parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted),
- fMonth = parsed[1],
- fDay = parsed[2],
- fYear = parsed[3],
- fadOrBc = parsed[4],
- fHour = parsed[5],
- fMinute = parsed[6],
- fSecond = parsed[7];
- return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
-}
-function partsOffset(dtf, date) {
- var formatted = dtf.formatToParts(date);
- var filled = [];
- for (var i = 0; i < formatted.length; i++) {
- var _formatted$i = formatted[i],
- type = _formatted$i.type,
- value = _formatted$i.value;
- var pos = typeToPos[type];
- if (type === "era") {
- filled[pos] = value;
- } else if (!isUndefined(pos)) {
- filled[pos] = parseInt(value, 10);
- }
- }
- return filled;
-}
-var ianaZoneCache = new Map();
-/**
- * A zone identified by an IANA identifier, like America/New_York
- * @implements {Zone}
- */
-var IANAZone = /*#__PURE__*/function (_Zone) {
- _inheritsLoose(IANAZone, _Zone);
- /**
- * @param {string} name - Zone name
- * @return {IANAZone}
- */
- IANAZone.create = function create(name) {
- var zone = ianaZoneCache.get(name);
- if (zone === undefined) {
- ianaZoneCache.set(name, zone = new IANAZone(name));
- }
- return zone;
- }
-
- /**
- * Reset local caches. Should only be necessary in testing scenarios.
- * @return {void}
- */;
- IANAZone.resetCache = function resetCache() {
- ianaZoneCache.clear();
- dtfCache.clear();
- }
-
- /**
- * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
- * @param {string} s - The string to check validity on
- * @example IANAZone.isValidSpecifier("America/New_York") //=> true
- * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
- * @deprecated For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead.
- * @return {boolean}
- */;
- IANAZone.isValidSpecifier = function isValidSpecifier(s) {
- return this.isValidZone(s);
- }
-
- /**
- * Returns whether the provided string identifies a real zone
- * @param {string} zone - The string to check
- * @example IANAZone.isValidZone("America/New_York") //=> true
- * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
- * @example IANAZone.isValidZone("Sport~~blorp") //=> false
- * @return {boolean}
- */;
- IANAZone.isValidZone = function isValidZone(zone) {
- if (!zone) {
- return false;
- }
- try {
- new Intl.DateTimeFormat("en-US", {
- timeZone: zone
- }).format();
- return true;
- } catch (e) {
- return false;
- }
- };
- function IANAZone(name) {
- var _this;
- _this = _Zone.call(this) || this;
- /** @private **/
- _this.zoneName = name;
- /** @private **/
- _this.valid = IANAZone.isValidZone(name);
- return _this;
- }
-
- /**
- * The type of zone. `iana` for all instances of `IANAZone`.
- * @override
- * @type {string}
- */
- var _proto = IANAZone.prototype;
- /**
- * Returns the offset's common name (such as EST) at the specified timestamp
- * @override
- * @param {number} ts - Epoch milliseconds for which to get the name
- * @param {Object} opts - Options to affect the format
- * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
- * @param {string} opts.locale - What locale to return the offset name in.
- * @return {string}
- */
- _proto.offsetName = function offsetName(ts, _ref) {
- var format = _ref.format,
- locale = _ref.locale;
- return parseZoneInfo(ts, format, locale, this.name);
- }
-
- /**
- * Returns the offset's value as a string
- * @override
- * @param {number} ts - Epoch milliseconds for which to get the offset
- * @param {string} format - What style of offset to return.
- * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
- * @return {string}
- */;
- _proto.formatOffset = function formatOffset$1(ts, format) {
- return formatOffset(this.offset(ts), format);
- }
-
- /**
- * Return the offset in minutes for this zone at the specified timestamp.
- * @override
- * @param {number} ts - Epoch milliseconds for which to compute the offset
- * @return {number}
- */;
- _proto.offset = function offset(ts) {
- if (!this.valid) return NaN;
- var date = new Date(ts);
- if (isNaN(date)) return NaN;
- var dtf = makeDTF(this.name);
- var _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date),
- year = _ref2[0],
- month = _ref2[1],
- day = _ref2[2],
- adOrBc = _ref2[3],
- hour = _ref2[4],
- minute = _ref2[5],
- second = _ref2[6];
- if (adOrBc === "BC") {
- year = -Math.abs(year) + 1;
- }
-
- // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat
- var adjustedHour = hour === 24 ? 0 : hour;
- var asUTC = objToLocalTS({
- year: year,
- month: month,
- day: day,
- hour: adjustedHour,
- minute: minute,
- second: second,
- millisecond: 0
- });
- var asTS = +date;
- var over = asTS % 1000;
- asTS -= over >= 0 ? over : 1000 + over;
- return (asUTC - asTS) / (60 * 1000);
- }
-
- /**
- * Return whether this Zone is equal to another zone
- * @override
- * @param {Zone} otherZone - the zone to compare
- * @return {boolean}
- */;
- _proto.equals = function equals(otherZone) {
- return otherZone.type === "iana" && otherZone.name === this.name;
- }
-
- /**
- * Return whether this Zone is valid.
- * @override
- * @type {boolean}
- */;
- _createClass(IANAZone, [{
- key: "type",
- get: function get() {
- return "iana";
- }
-
- /**
- * The name of this zone (i.e. the IANA zone name).
- * @override
- * @type {string}
- */
- }, {
- key: "name",
- get: function get() {
- return this.zoneName;
- }
-
- /**
- * Returns whether the offset is known to be fixed for the whole year:
- * Always returns false for all IANA zones.
- * @override
- * @type {boolean}
- */
- }, {
- key: "isUniversal",
- get: function get() {
- return false;
- }
- }, {
- key: "isValid",
- get: function get() {
- return this.valid;
- }
- }]);
- return IANAZone;
-}(Zone);
-
-var _excluded = ["base"],
- _excluded2 = ["padTo", "floor"];
-
-// todo - remap caching
-
-var intlLFCache = {};
-function getCachedLF(locString, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var key = JSON.stringify([locString, opts]);
- var dtf = intlLFCache[key];
- if (!dtf) {
- dtf = new Intl.ListFormat(locString, opts);
- intlLFCache[key] = dtf;
- }
- return dtf;
-}
-var intlDTCache = new Map();
-function getCachedDTF(locString, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var key = JSON.stringify([locString, opts]);
- var dtf = intlDTCache.get(key);
- if (dtf === undefined) {
- dtf = new Intl.DateTimeFormat(locString, opts);
- intlDTCache.set(key, dtf);
- }
- return dtf;
-}
-var intlNumCache = new Map();
-function getCachedINF(locString, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var key = JSON.stringify([locString, opts]);
- var inf = intlNumCache.get(key);
- if (inf === undefined) {
- inf = new Intl.NumberFormat(locString, opts);
- intlNumCache.set(key, inf);
- }
- return inf;
-}
-var intlRelCache = new Map();
-function getCachedRTF(locString, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var _opts = opts;
- _opts.base;
- var cacheKeyOpts = _objectWithoutPropertiesLoose(_opts, _excluded); // exclude `base` from the options
- var key = JSON.stringify([locString, cacheKeyOpts]);
- var inf = intlRelCache.get(key);
- if (inf === undefined) {
- inf = new Intl.RelativeTimeFormat(locString, opts);
- intlRelCache.set(key, inf);
- }
- return inf;
-}
-var sysLocaleCache = null;
-function systemLocale() {
- if (sysLocaleCache) {
- return sysLocaleCache;
- } else {
- sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
- return sysLocaleCache;
- }
-}
-var intlResolvedOptionsCache = new Map();
-function getCachedIntResolvedOptions(locString) {
- var opts = intlResolvedOptionsCache.get(locString);
- if (opts === undefined) {
- opts = new Intl.DateTimeFormat(locString).resolvedOptions();
- intlResolvedOptionsCache.set(locString, opts);
- }
- return opts;
-}
-var weekInfoCache = new Map();
-function getCachedWeekInfo(locString) {
- var data = weekInfoCache.get(locString);
- if (!data) {
- var locale = new Intl.Locale(locString);
- // browsers currently implement this as a property, but spec says it should be a getter function
- data = "getWeekInfo" in locale ? locale.getWeekInfo() : locale.weekInfo;
- // minimalDays was removed from WeekInfo: https://github.com/tc39/proposal-intl-locale-info/issues/86
- if (!("minimalDays" in data)) {
- data = _extends({}, fallbackWeekSettings, data);
- }
- weekInfoCache.set(locString, data);
- }
- return data;
-}
-function parseLocaleString(localeStr) {
- // I really want to avoid writing a BCP 47 parser
- // see, e.g. https://github.com/wooorm/bcp-47
- // Instead, we'll do this:
-
- // a) if the string has no -u extensions, just leave it alone
- // b) if it does, use Intl to resolve everything
- // c) if Intl fails, try again without the -u
-
- // private subtags and unicode subtags have ordering requirements,
- // and we're not properly parsing this, so just strip out the
- // private ones if they exist.
- var xIndex = localeStr.indexOf("-x-");
- if (xIndex !== -1) {
- localeStr = localeStr.substring(0, xIndex);
- }
- var uIndex = localeStr.indexOf("-u-");
- if (uIndex === -1) {
- return [localeStr];
- } else {
- var options;
- var selectedStr;
- try {
- options = getCachedDTF(localeStr).resolvedOptions();
- selectedStr = localeStr;
- } catch (e) {
- var smaller = localeStr.substring(0, uIndex);
- options = getCachedDTF(smaller).resolvedOptions();
- selectedStr = smaller;
- }
- var _options = options,
- numberingSystem = _options.numberingSystem,
- calendar = _options.calendar;
- return [selectedStr, numberingSystem, calendar];
- }
-}
-function intlConfigString(localeStr, numberingSystem, outputCalendar) {
- if (outputCalendar || numberingSystem) {
- if (!localeStr.includes("-u-")) {
- localeStr += "-u";
- }
- if (outputCalendar) {
- localeStr += "-ca-" + outputCalendar;
- }
- if (numberingSystem) {
- localeStr += "-nu-" + numberingSystem;
- }
- return localeStr;
- } else {
- return localeStr;
- }
-}
-function mapMonths(f) {
- var ms = [];
- for (var i = 1; i <= 12; i++) {
- var dt = DateTime.utc(2009, i, 1);
- ms.push(f(dt));
- }
- return ms;
-}
-function mapWeekdays(f) {
- var ms = [];
- for (var i = 1; i <= 7; i++) {
- var dt = DateTime.utc(2016, 11, 13 + i);
- ms.push(f(dt));
- }
- return ms;
-}
-function listStuff(loc, length, englishFn, intlFn) {
- var mode = loc.listingMode();
- if (mode === "error") {
- return null;
- } else if (mode === "en") {
- return englishFn(length);
- } else {
- return intlFn(length);
- }
-}
-function supportsFastNumbers(loc) {
- if (loc.numberingSystem && loc.numberingSystem !== "latn") {
- return false;
- } else {
- return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || getCachedIntResolvedOptions(loc.locale).numberingSystem === "latn";
- }
-}
-
-/**
- * @private
- */
-var PolyNumberFormatter = /*#__PURE__*/function () {
- function PolyNumberFormatter(intl, forceSimple, opts) {
- this.padTo = opts.padTo || 0;
- this.floor = opts.floor || false;
- opts.padTo;
- opts.floor;
- var otherOpts = _objectWithoutPropertiesLoose(opts, _excluded2);
- if (!forceSimple || Object.keys(otherOpts).length > 0) {
- var intlOpts = _extends({
- useGrouping: false
- }, opts);
- if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
- this.inf = getCachedINF(intl, intlOpts);
- }
- }
- var _proto = PolyNumberFormatter.prototype;
- _proto.format = function format(i) {
- if (this.inf) {
- var fixed = this.floor ? Math.floor(i) : i;
- return this.inf.format(fixed);
- } else {
- // to match the browser's numberformatter defaults
- var _fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
- return padStart(_fixed, this.padTo);
- }
- };
- return PolyNumberFormatter;
-}();
-/**
- * @private
- */
-var PolyDateFormatter = /*#__PURE__*/function () {
- function PolyDateFormatter(dt, intl, opts) {
- this.opts = opts;
- this.originalZone = undefined;
- var z = undefined;
- if (this.opts.timeZone) {
- // Don't apply any workarounds if a timeZone is explicitly provided in opts
- this.dt = dt;
- } else if (dt.zone.type === "fixed") {
- // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.
- // That is why fixed-offset TZ is set to that unless it is:
- // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.
- // 2. Unsupported by the browser:
- // - some do not support Etc/
- // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata
- var gmtOffset = -1 * (dt.offset / 60);
- var offsetZ = gmtOffset >= 0 ? "Etc/GMT+" + gmtOffset : "Etc/GMT" + gmtOffset;
- if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {
- z = offsetZ;
- this.dt = dt;
- } else {
- // Not all fixed-offset zones like Etc/+4:30 are present in tzdata so
- // we manually apply the offset and substitute the zone as needed.
- z = "UTC";
- this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({
- minutes: dt.offset
- });
- this.originalZone = dt.zone;
- }
- } else if (dt.zone.type === "system") {
- this.dt = dt;
- } else if (dt.zone.type === "iana") {
- this.dt = dt;
- z = dt.zone.name;
- } else {
- // Custom zones can have any offset / offsetName so we just manually
- // apply the offset and substitute the zone as needed.
- z = "UTC";
- this.dt = dt.setZone("UTC").plus({
- minutes: dt.offset
- });
- this.originalZone = dt.zone;
- }
- var intlOpts = _extends({}, this.opts);
- intlOpts.timeZone = intlOpts.timeZone || z;
- this.dtf = getCachedDTF(intl, intlOpts);
- }
- var _proto2 = PolyDateFormatter.prototype;
- _proto2.format = function format() {
- if (this.originalZone) {
- // If we have to substitute in the actual zone name, we have to use
- // formatToParts so that the timezone can be replaced.
- return this.formatToParts().map(function (_ref) {
- var value = _ref.value;
- return value;
- }).join("");
- }
- return this.dtf.format(this.dt.toJSDate());
- };
- _proto2.formatToParts = function formatToParts() {
- var _this = this;
- var parts = this.dtf.formatToParts(this.dt.toJSDate());
- if (this.originalZone) {
- return parts.map(function (part) {
- if (part.type === "timeZoneName") {
- var offsetName = _this.originalZone.offsetName(_this.dt.ts, {
- locale: _this.dt.locale,
- format: _this.opts.timeZoneName
- });
- return _extends({}, part, {
- value: offsetName
- });
- } else {
- return part;
- }
- });
- }
- return parts;
- };
- _proto2.resolvedOptions = function resolvedOptions() {
- return this.dtf.resolvedOptions();
- };
- return PolyDateFormatter;
-}();
-/**
- * @private
- */
-var PolyRelFormatter = /*#__PURE__*/function () {
- function PolyRelFormatter(intl, isEnglish, opts) {
- this.opts = _extends({
- style: "long"
- }, opts);
- if (!isEnglish && hasRelative()) {
- this.rtf = getCachedRTF(intl, opts);
- }
- }
- var _proto3 = PolyRelFormatter.prototype;
- _proto3.format = function format(count, unit) {
- if (this.rtf) {
- return this.rtf.format(count, unit);
- } else {
- return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
- }
- };
- _proto3.formatToParts = function formatToParts(count, unit) {
- if (this.rtf) {
- return this.rtf.formatToParts(count, unit);
- } else {
- return [];
- }
- };
- return PolyRelFormatter;
-}();
-var fallbackWeekSettings = {
- firstDay: 1,
- minimalDays: 4,
- weekend: [6, 7]
-};
-
-/**
- * @private
- */
-var Locale = /*#__PURE__*/function () {
- Locale.fromOpts = function fromOpts(opts) {
- return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN);
- };
- Locale.create = function create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN) {
- if (defaultToEN === void 0) {
- defaultToEN = false;
- }
- var specifiedLocale = locale || Settings.defaultLocale;
- // the system locale is useful for human-readable strings but annoying for parsing/formatting known formats
- var localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale());
- var numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;
- var outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
- var weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings;
- return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale);
- };
- Locale.resetCache = function resetCache() {
- sysLocaleCache = null;
- intlDTCache.clear();
- intlNumCache.clear();
- intlRelCache.clear();
- intlResolvedOptionsCache.clear();
- weekInfoCache.clear();
- };
- Locale.fromObject = function fromObject(_temp) {
- var _ref2 = _temp === void 0 ? {} : _temp,
- locale = _ref2.locale,
- numberingSystem = _ref2.numberingSystem,
- outputCalendar = _ref2.outputCalendar,
- weekSettings = _ref2.weekSettings;
- return Locale.create(locale, numberingSystem, outputCalendar, weekSettings);
- };
- function Locale(locale, numbering, outputCalendar, weekSettings, specifiedLocale) {
- var _parseLocaleString = parseLocaleString(locale),
- parsedLocale = _parseLocaleString[0],
- parsedNumberingSystem = _parseLocaleString[1],
- parsedOutputCalendar = _parseLocaleString[2];
- this.locale = parsedLocale;
- this.numberingSystem = numbering || parsedNumberingSystem || null;
- this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
- this.weekSettings = weekSettings;
- this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
- this.weekdaysCache = {
- format: {},
- standalone: {}
- };
- this.monthsCache = {
- format: {},
- standalone: {}
- };
- this.meridiemCache = null;
- this.eraCache = {};
- this.specifiedLocale = specifiedLocale;
- this.fastNumbersCached = null;
- }
- var _proto4 = Locale.prototype;
- _proto4.listingMode = function listingMode() {
- var isActuallyEn = this.isEnglish();
- var hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
- return isActuallyEn && hasNoWeirdness ? "en" : "intl";
- };
- _proto4.clone = function clone(alts) {
- if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
- return this;
- } else {
- return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false);
- }
- };
- _proto4.redefaultToEN = function redefaultToEN(alts) {
- if (alts === void 0) {
- alts = {};
- }
- return this.clone(_extends({}, alts, {
- defaultToEN: true
- }));
- };
- _proto4.redefaultToSystem = function redefaultToSystem(alts) {
- if (alts === void 0) {
- alts = {};
- }
- return this.clone(_extends({}, alts, {
- defaultToEN: false
- }));
- };
- _proto4.months = function months$1(length, format) {
- var _this2 = this;
- if (format === void 0) {
- format = false;
- }
- return listStuff(this, length, months, function () {
- // Workaround for "ja" locale: formatToParts does not label all parts of the month
- // as "month" and for this locale there is no difference between "format" and "non-format".
- // As such, just use format() instead of formatToParts() and take the whole string
- var monthSpecialCase = _this2.intl === "ja" || _this2.intl.startsWith("ja-");
- format &= !monthSpecialCase;
- var intl = format ? {
- month: length,
- day: "numeric"
- } : {
- month: length
- },
- formatStr = format ? "format" : "standalone";
- if (!_this2.monthsCache[formatStr][length]) {
- var mapper = !monthSpecialCase ? function (dt) {
- return _this2.extract(dt, intl, "month");
- } : function (dt) {
- return _this2.dtFormatter(dt, intl).format();
- };
- _this2.monthsCache[formatStr][length] = mapMonths(mapper);
- }
- return _this2.monthsCache[formatStr][length];
- });
- };
- _proto4.weekdays = function weekdays$1(length, format) {
- var _this3 = this;
- if (format === void 0) {
- format = false;
- }
- return listStuff(this, length, weekdays, function () {
- var intl = format ? {
- weekday: length,
- year: "numeric",
- month: "long",
- day: "numeric"
- } : {
- weekday: length
- },
- formatStr = format ? "format" : "standalone";
- if (!_this3.weekdaysCache[formatStr][length]) {
- _this3.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) {
- return _this3.extract(dt, intl, "weekday");
- });
- }
- return _this3.weekdaysCache[formatStr][length];
- });
- };
- _proto4.meridiems = function meridiems$1() {
- var _this4 = this;
- return listStuff(this, undefined, function () {
- return meridiems;
- }, function () {
- // In theory there could be aribitrary day periods. We're gonna assume there are exactly two
- // for AM and PM. This is probably wrong, but it's makes parsing way easier.
- if (!_this4.meridiemCache) {
- var intl = {
- hour: "numeric",
- hourCycle: "h12"
- };
- _this4.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) {
- return _this4.extract(dt, intl, "dayperiod");
- });
- }
- return _this4.meridiemCache;
- });
- };
- _proto4.eras = function eras$1(length) {
- var _this5 = this;
- return listStuff(this, length, eras, function () {
- var intl = {
- era: length
- };
-
- // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates
- // to definitely enumerate them.
- if (!_this5.eraCache[length]) {
- _this5.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(function (dt) {
- return _this5.extract(dt, intl, "era");
- });
- }
- return _this5.eraCache[length];
- });
- };
- _proto4.extract = function extract(dt, intlOpts, field) {
- var df = this.dtFormatter(dt, intlOpts),
- results = df.formatToParts(),
- matching = results.find(function (m) {
- return m.type.toLowerCase() === field;
- });
- return matching ? matching.value : null;
- };
- _proto4.numberFormatter = function numberFormatter(opts) {
- if (opts === void 0) {
- opts = {};
- }
- // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)
- // (in contrast, the rest of the condition is used heavily)
- return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
- };
- _proto4.dtFormatter = function dtFormatter(dt, intlOpts) {
- if (intlOpts === void 0) {
- intlOpts = {};
- }
- return new PolyDateFormatter(dt, this.intl, intlOpts);
- };
- _proto4.relFormatter = function relFormatter(opts) {
- if (opts === void 0) {
- opts = {};
- }
- return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
- };
- _proto4.listFormatter = function listFormatter(opts) {
- if (opts === void 0) {
- opts = {};
- }
- return getCachedLF(this.intl, opts);
- };
- _proto4.isEnglish = function isEnglish() {
- return this.locale === "en" || this.locale.toLowerCase() === "en-us" || getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us");
- };
- _proto4.getWeekSettings = function getWeekSettings() {
- if (this.weekSettings) {
- return this.weekSettings;
- } else if (!hasLocaleWeekInfo()) {
- return fallbackWeekSettings;
- } else {
- return getCachedWeekInfo(this.locale);
- }
- };
- _proto4.getStartOfWeek = function getStartOfWeek() {
- return this.getWeekSettings().firstDay;
- };
- _proto4.getMinDaysInFirstWeek = function getMinDaysInFirstWeek() {
- return this.getWeekSettings().minimalDays;
- };
- _proto4.getWeekendDays = function getWeekendDays() {
- return this.getWeekSettings().weekend;
- };
- _proto4.equals = function equals(other) {
- return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
- };
- _proto4.toString = function toString() {
- return "Locale(" + this.locale + ", " + this.numberingSystem + ", " + this.outputCalendar + ")";
- };
- _createClass(Locale, [{
- key: "fastNumbers",
- get: function get() {
- if (this.fastNumbersCached == null) {
- this.fastNumbersCached = supportsFastNumbers(this);
- }
- return this.fastNumbersCached;
- }
- }]);
- return Locale;
-}();
-
-var singleton = null;
-
-/**
- * A zone with a fixed offset (meaning no DST)
- * @implements {Zone}
- */
-var FixedOffsetZone = /*#__PURE__*/function (_Zone) {
- _inheritsLoose(FixedOffsetZone, _Zone);
- /**
- * Get an instance with a specified offset
- * @param {number} offset - The offset in minutes
- * @return {FixedOffsetZone}
- */
- FixedOffsetZone.instance = function instance(offset) {
- return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);
- }
-
- /**
- * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
- * @param {string} s - The offset string to parse
- * @example FixedOffsetZone.parseSpecifier("UTC+6")
- * @example FixedOffsetZone.parseSpecifier("UTC+06")
- * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
- * @return {FixedOffsetZone}
- */;
- FixedOffsetZone.parseSpecifier = function parseSpecifier(s) {
- if (s) {
- var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
- if (r) {
- return new FixedOffsetZone(signedOffset(r[1], r[2]));
- }
- }
- return null;
- };
- function FixedOffsetZone(offset) {
- var _this;
- _this = _Zone.call(this) || this;
- /** @private **/
- _this.fixed = offset;
- return _this;
- }
-
- /**
- * The type of zone. `fixed` for all instances of `FixedOffsetZone`.
- * @override
- * @type {string}
- */
- var _proto = FixedOffsetZone.prototype;
- /**
- * Returns the offset's common name at the specified timestamp.
- *
- * For fixed offset zones this equals to the zone name.
- * @override
- */
- _proto.offsetName = function offsetName() {
- return this.name;
- }
-
- /**
- * Returns the offset's value as a string
- * @override
- * @param {number} ts - Epoch milliseconds for which to get the offset
- * @param {string} format - What style of offset to return.
- * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
- * @return {string}
- */;
- _proto.formatOffset = function formatOffset$1(ts, format) {
- return formatOffset(this.fixed, format);
- }
-
- /**
- * Returns whether the offset is known to be fixed for the whole year:
- * Always returns true for all fixed offset zones.
- * @override
- * @type {boolean}
- */;
- /**
- * Return the offset in minutes for this zone at the specified timestamp.
- *
- * For fixed offset zones, this is constant and does not depend on a timestamp.
- * @override
- * @return {number}
- */
- _proto.offset = function offset() {
- return this.fixed;
- }
-
- /**
- * Return whether this Zone is equal to another zone (i.e. also fixed and same offset)
- * @override
- * @param {Zone} otherZone - the zone to compare
- * @return {boolean}
- */;
- _proto.equals = function equals(otherZone) {
- return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
- }
-
- /**
- * Return whether this Zone is valid:
- * All fixed offset zones are valid.
- * @override
- * @type {boolean}
- */;
- _createClass(FixedOffsetZone, [{
- key: "type",
- get: function get() {
- return "fixed";
- }
-
- /**
- * The name of this zone.
- * All fixed zones' names always start with "UTC" (plus optional offset)
- * @override
- * @type {string}
- */
- }, {
- key: "name",
- get: function get() {
- return this.fixed === 0 ? "UTC" : "UTC" + formatOffset(this.fixed, "narrow");
- }
-
- /**
- * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn`
- *
- * @override
- * @type {string}
- */
- }, {
- key: "ianaName",
- get: function get() {
- if (this.fixed === 0) {
- return "Etc/UTC";
- } else {
- return "Etc/GMT" + formatOffset(-this.fixed, "narrow");
- }
- }
- }, {
- key: "isUniversal",
- get: function get() {
- return true;
- }
- }, {
- key: "isValid",
- get: function get() {
- return true;
- }
- }], [{
- key: "utcInstance",
- get:
- /**
- * Get a singleton instance of UTC
- * @return {FixedOffsetZone}
- */
- function get() {
- if (singleton === null) {
- singleton = new FixedOffsetZone(0);
- }
- return singleton;
- }
- }]);
- return FixedOffsetZone;
-}(Zone);
-
-/**
- * A zone that failed to parse. You should never need to instantiate this.
- * @implements {Zone}
- */
-var InvalidZone = /*#__PURE__*/function (_Zone) {
- _inheritsLoose(InvalidZone, _Zone);
- function InvalidZone(zoneName) {
- var _this;
- _this = _Zone.call(this) || this;
- /** @private */
- _this.zoneName = zoneName;
- return _this;
- }
-
- /** @override **/
- var _proto = InvalidZone.prototype;
- /** @override **/
- _proto.offsetName = function offsetName() {
- return null;
- }
-
- /** @override **/;
- _proto.formatOffset = function formatOffset() {
- return "";
- }
-
- /** @override **/;
- _proto.offset = function offset() {
- return NaN;
- }
-
- /** @override **/;
- _proto.equals = function equals() {
- return false;
- }
-
- /** @override **/;
- _createClass(InvalidZone, [{
- key: "type",
- get: function get() {
- return "invalid";
- }
-
- /** @override **/
- }, {
- key: "name",
- get: function get() {
- return this.zoneName;
- }
-
- /** @override **/
- }, {
- key: "isUniversal",
- get: function get() {
- return false;
- }
- }, {
- key: "isValid",
- get: function get() {
- return false;
- }
- }]);
- return InvalidZone;
-}(Zone);
-
-/**
- * @private
- */
-function normalizeZone(input, defaultZone) {
- if (isUndefined(input) || input === null) {
- return defaultZone;
- } else if (input instanceof Zone) {
- return input;
- } else if (isString(input)) {
- var lowered = input.toLowerCase();
- if (lowered === "default") return defaultZone;else if (lowered === "local" || lowered === "system") return SystemZone.instance;else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);
- } else if (isNumber(input)) {
- return FixedOffsetZone.instance(input);
- } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") {
- // This is dumb, but the instanceof check above doesn't seem to really work
- // so we're duck checking it
- return input;
- } else {
- return new InvalidZone(input);
- }
-}
-
-var numberingSystems = {
- arab: "[\u0660-\u0669]",
- arabext: "[\u06F0-\u06F9]",
- bali: "[\u1B50-\u1B59]",
- beng: "[\u09E6-\u09EF]",
- deva: "[\u0966-\u096F]",
- fullwide: "[\uFF10-\uFF19]",
- gujr: "[\u0AE6-\u0AEF]",
- hanidec: "[〇|一|二|三|四|五|六|七|八|九]",
- khmr: "[\u17E0-\u17E9]",
- knda: "[\u0CE6-\u0CEF]",
- laoo: "[\u0ED0-\u0ED9]",
- limb: "[\u1946-\u194F]",
- mlym: "[\u0D66-\u0D6F]",
- mong: "[\u1810-\u1819]",
- mymr: "[\u1040-\u1049]",
- orya: "[\u0B66-\u0B6F]",
- tamldec: "[\u0BE6-\u0BEF]",
- telu: "[\u0C66-\u0C6F]",
- thai: "[\u0E50-\u0E59]",
- tibt: "[\u0F20-\u0F29]",
- latn: "\\d"
-};
-var numberingSystemsUTF16 = {
- arab: [1632, 1641],
- arabext: [1776, 1785],
- bali: [6992, 7001],
- beng: [2534, 2543],
- deva: [2406, 2415],
- fullwide: [65296, 65303],
- gujr: [2790, 2799],
- khmr: [6112, 6121],
- knda: [3302, 3311],
- laoo: [3792, 3801],
- limb: [6470, 6479],
- mlym: [3430, 3439],
- mong: [6160, 6169],
- mymr: [4160, 4169],
- orya: [2918, 2927],
- tamldec: [3046, 3055],
- telu: [3174, 3183],
- thai: [3664, 3673],
- tibt: [3872, 3881]
-};
-var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
-function parseDigits(str) {
- var value = parseInt(str, 10);
- if (isNaN(value)) {
- value = "";
- for (var i = 0; i < str.length; i++) {
- var code = str.charCodeAt(i);
- if (str[i].search(numberingSystems.hanidec) !== -1) {
- value += hanidecChars.indexOf(str[i]);
- } else {
- for (var key in numberingSystemsUTF16) {
- var _numberingSystemsUTF = numberingSystemsUTF16[key],
- min = _numberingSystemsUTF[0],
- max = _numberingSystemsUTF[1];
- if (code >= min && code <= max) {
- value += code - min;
- }
- }
- }
- }
- return parseInt(value, 10);
- } else {
- return value;
- }
-}
-
-// cache of {numberingSystem: {append: regex}}
-var digitRegexCache = new Map();
-function resetDigitRegexCache() {
- digitRegexCache.clear();
-}
-function digitRegex(_ref, append) {
- var numberingSystem = _ref.numberingSystem;
- if (append === void 0) {
- append = "";
- }
- var ns = numberingSystem || "latn";
- var appendCache = digitRegexCache.get(ns);
- if (appendCache === undefined) {
- appendCache = new Map();
- digitRegexCache.set(ns, appendCache);
- }
- var regex = appendCache.get(append);
- if (regex === undefined) {
- regex = new RegExp("" + numberingSystems[ns] + append);
- appendCache.set(append, regex);
- }
- return regex;
-}
-
-var now = function now() {
- return Date.now();
- },
- defaultZone = "system",
- defaultLocale = null,
- defaultNumberingSystem = null,
- defaultOutputCalendar = null,
- twoDigitCutoffYear = 60,
- throwOnInvalid,
- defaultWeekSettings = null;
-
-/**
- * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.
- */
-var Settings = /*#__PURE__*/function () {
- function Settings() {}
- /**
- * Reset Luxon's global caches. Should only be necessary in testing scenarios.
- * @return {void}
- */
- Settings.resetCaches = function resetCaches() {
- Locale.resetCache();
- IANAZone.resetCache();
- DateTime.resetCache();
- resetDigitRegexCache();
- };
- _createClass(Settings, null, [{
- key: "now",
- get:
- /**
- * Get the callback for returning the current timestamp.
- * @type {function}
- */
- function get() {
- return now;
- }
-
- /**
- * Set the callback for returning the current timestamp.
- * The function should return a number, which will be interpreted as an Epoch millisecond count
- * @type {function}
- * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
- * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
- */,
- set: function set(n) {
- now = n;
- }
-
- /**
- * Set the default time zone to create DateTimes in. Does not affect existing instances.
- * Use the value "system" to reset this value to the system's time zone.
- * @type {string}
- */
- }, {
- key: "defaultZone",
- get:
- /**
- * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
- * The default value is the system's time zone (the one set on the machine that runs this code).
- * @type {Zone}
- */
- function get() {
- return normalizeZone(defaultZone, SystemZone.instance);
- }
-
- /**
- * Get the default locale to create DateTimes with. Does not affect existing instances.
- * @type {string}
- */,
- set: function set(zone) {
- defaultZone = zone;
- }
- }, {
- key: "defaultLocale",
- get: function get() {
- return defaultLocale;
- }
-
- /**
- * Set the default locale to create DateTimes with. Does not affect existing instances.
- * @type {string}
- */,
- set: function set(locale) {
- defaultLocale = locale;
- }
-
- /**
- * Get the default numbering system to create DateTimes with. Does not affect existing instances.
- * @type {string}
- */
- }, {
- key: "defaultNumberingSystem",
- get: function get() {
- return defaultNumberingSystem;
- }
-
- /**
- * Set the default numbering system to create DateTimes with. Does not affect existing instances.
- * @type {string}
- */,
- set: function set(numberingSystem) {
- defaultNumberingSystem = numberingSystem;
- }
-
- /**
- * Get the default output calendar to create DateTimes with. Does not affect existing instances.
- * @type {string}
- */
- }, {
- key: "defaultOutputCalendar",
- get: function get() {
- return defaultOutputCalendar;
- }
-
- /**
- * Set the default output calendar to create DateTimes with. Does not affect existing instances.
- * @type {string}
- */,
- set: function set(outputCalendar) {
- defaultOutputCalendar = outputCalendar;
- }
-
- /**
- * @typedef {Object} WeekSettings
- * @property {number} firstDay
- * @property {number} minimalDays
- * @property {number[]} weekend
- */
-
- /**
- * @return {WeekSettings|null}
- */
- }, {
- key: "defaultWeekSettings",
- get: function get() {
- return defaultWeekSettings;
- }
-
- /**
- * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and
- * how many days are required in the first week of a year.
- * Does not affect existing instances.
- *
- * @param {WeekSettings|null} weekSettings
- */,
- set: function set(weekSettings) {
- defaultWeekSettings = validateWeekSettings(weekSettings);
- }
-
- /**
- * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.
- * @type {number}
- */
- }, {
- key: "twoDigitCutoffYear",
- get: function get() {
- return twoDigitCutoffYear;
- }
-
- /**
- * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.
- * @type {number}
- * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century
- * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century
- * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950
- * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50
- * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50
- */,
- set: function set(cutoffYear) {
- twoDigitCutoffYear = cutoffYear % 100;
- }
-
- /**
- * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
- * @type {boolean}
- */
- }, {
- key: "throwOnInvalid",
- get: function get() {
- return throwOnInvalid;
- }
-
- /**
- * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
- * @type {boolean}
- */,
- set: function set(t) {
- throwOnInvalid = t;
- }
- }]);
- return Settings;
-}();
-
-var Invalid = /*#__PURE__*/function () {
- function Invalid(reason, explanation) {
- this.reason = reason;
- this.explanation = explanation;
- }
- var _proto = Invalid.prototype;
- _proto.toMessage = function toMessage() {
- if (this.explanation) {
- return this.reason + ": " + this.explanation;
- } else {
- return this.reason;
- }
- };
- return Invalid;
-}();
-
-var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
- leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
-function unitOutOfRange(unit, value) {
- return new Invalid("unit out of range", "you specified " + value + " (of type " + typeof value + ") as a " + unit + ", which is invalid");
-}
-function dayOfWeek(year, month, day) {
- var d = new Date(Date.UTC(year, month - 1, day));
- if (year < 100 && year >= 0) {
- d.setUTCFullYear(d.getUTCFullYear() - 1900);
- }
- var js = d.getUTCDay();
- return js === 0 ? 7 : js;
-}
-function computeOrdinal(year, month, day) {
- return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
-}
-function uncomputeOrdinal(year, ordinal) {
- var table = isLeapYear(year) ? leapLadder : nonLeapLadder,
- month0 = table.findIndex(function (i) {
- return i < ordinal;
- }),
- day = ordinal - table[month0];
- return {
- month: month0 + 1,
- day: day
- };
-}
-function isoWeekdayToLocal(isoWeekday, startOfWeek) {
- return (isoWeekday - startOfWeek + 7) % 7 + 1;
-}
-
-/**
- * @private
- */
-
-function gregorianToWeek(gregObj, minDaysInFirstWeek, startOfWeek) {
- if (minDaysInFirstWeek === void 0) {
- minDaysInFirstWeek = 4;
- }
- if (startOfWeek === void 0) {
- startOfWeek = 1;
- }
- var year = gregObj.year,
- month = gregObj.month,
- day = gregObj.day,
- ordinal = computeOrdinal(year, month, day),
- weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek);
- var weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7),
- weekYear;
- if (weekNumber < 1) {
- weekYear = year - 1;
- weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek);
- } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) {
- weekYear = year + 1;
- weekNumber = 1;
- } else {
- weekYear = year;
- }
- return _extends({
- weekYear: weekYear,
- weekNumber: weekNumber,
- weekday: weekday
- }, timeObject(gregObj));
-}
-function weekToGregorian(weekData, minDaysInFirstWeek, startOfWeek) {
- if (minDaysInFirstWeek === void 0) {
- minDaysInFirstWeek = 4;
- }
- if (startOfWeek === void 0) {
- startOfWeek = 1;
- }
- var weekYear = weekData.weekYear,
- weekNumber = weekData.weekNumber,
- weekday = weekData.weekday,
- weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek),
- yearInDays = daysInYear(weekYear);
- var ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek,
- year;
- if (ordinal < 1) {
- year = weekYear - 1;
- ordinal += daysInYear(year);
- } else if (ordinal > yearInDays) {
- year = weekYear + 1;
- ordinal -= daysInYear(weekYear);
- } else {
- year = weekYear;
- }
- var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal),
- month = _uncomputeOrdinal.month,
- day = _uncomputeOrdinal.day;
- return _extends({
- year: year,
- month: month,
- day: day
- }, timeObject(weekData));
-}
-function gregorianToOrdinal(gregData) {
- var year = gregData.year,
- month = gregData.month,
- day = gregData.day;
- var ordinal = computeOrdinal(year, month, day);
- return _extends({
- year: year,
- ordinal: ordinal
- }, timeObject(gregData));
-}
-function ordinalToGregorian(ordinalData) {
- var year = ordinalData.year,
- ordinal = ordinalData.ordinal;
- var _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal),
- month = _uncomputeOrdinal2.month,
- day = _uncomputeOrdinal2.day;
- return _extends({
- year: year,
- month: month,
- day: day
- }, timeObject(ordinalData));
-}
-
-/**
- * Check if local week units like localWeekday are used in obj.
- * If so, validates that they are not mixed with ISO week units and then copies them to the normal week unit properties.
- * Modifies obj in-place!
- * @param obj the object values
- */
-function usesLocalWeekValues(obj, loc) {
- var hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear);
- if (hasLocaleWeekData) {
- var hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear);
- if (hasIsoWeekData) {
- throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields");
- }
- if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday;
- if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber;
- if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear;
- delete obj.localWeekday;
- delete obj.localWeekNumber;
- delete obj.localWeekYear;
- return {
- minDaysInFirstWeek: loc.getMinDaysInFirstWeek(),
- startOfWeek: loc.getStartOfWeek()
- };
- } else {
- return {
- minDaysInFirstWeek: 4,
- startOfWeek: 1
- };
- }
-}
-function hasInvalidWeekData(obj, minDaysInFirstWeek, startOfWeek) {
- if (minDaysInFirstWeek === void 0) {
- minDaysInFirstWeek = 4;
- }
- if (startOfWeek === void 0) {
- startOfWeek = 1;
- }
- var validYear = isInteger(obj.weekYear),
- validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)),
- validWeekday = integerBetween(obj.weekday, 1, 7);
- if (!validYear) {
- return unitOutOfRange("weekYear", obj.weekYear);
- } else if (!validWeek) {
- return unitOutOfRange("week", obj.weekNumber);
- } else if (!validWeekday) {
- return unitOutOfRange("weekday", obj.weekday);
- } else return false;
-}
-function hasInvalidOrdinalData(obj) {
- var validYear = isInteger(obj.year),
- validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
- if (!validYear) {
- return unitOutOfRange("year", obj.year);
- } else if (!validOrdinal) {
- return unitOutOfRange("ordinal", obj.ordinal);
- } else return false;
-}
-function hasInvalidGregorianData(obj) {
- var validYear = isInteger(obj.year),
- validMonth = integerBetween(obj.month, 1, 12),
- validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
- if (!validYear) {
- return unitOutOfRange("year", obj.year);
- } else if (!validMonth) {
- return unitOutOfRange("month", obj.month);
- } else if (!validDay) {
- return unitOutOfRange("day", obj.day);
- } else return false;
-}
-function hasInvalidTimeData(obj) {
- var hour = obj.hour,
- minute = obj.minute,
- second = obj.second,
- millisecond = obj.millisecond;
- var validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0,
- validMinute = integerBetween(minute, 0, 59),
- validSecond = integerBetween(second, 0, 59),
- validMillisecond = integerBetween(millisecond, 0, 999);
- if (!validHour) {
- return unitOutOfRange("hour", hour);
- } else if (!validMinute) {
- return unitOutOfRange("minute", minute);
- } else if (!validSecond) {
- return unitOutOfRange("second", second);
- } else if (!validMillisecond) {
- return unitOutOfRange("millisecond", millisecond);
- } else return false;
-}
-
-/**
- * @private
- */
-
-// TYPES
-
-function isUndefined(o) {
- return typeof o === "undefined";
-}
-function isNumber(o) {
- return typeof o === "number";
-}
-function isInteger(o) {
- return typeof o === "number" && o % 1 === 0;
-}
-function isString(o) {
- return typeof o === "string";
-}
-function isDate(o) {
- return Object.prototype.toString.call(o) === "[object Date]";
-}
-
-// CAPABILITIES
-
-function hasRelative() {
- try {
- return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
- } catch (e) {
- return false;
- }
-}
-function hasLocaleWeekInfo() {
- try {
- return typeof Intl !== "undefined" && !!Intl.Locale && ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype);
- } catch (e) {
- return false;
- }
-}
-
-// OBJECTS AND ARRAYS
-
-function maybeArray(thing) {
- return Array.isArray(thing) ? thing : [thing];
-}
-function bestBy(arr, by, compare) {
- if (arr.length === 0) {
- return undefined;
- }
- return arr.reduce(function (best, next) {
- var pair = [by(next), next];
- if (!best) {
- return pair;
- } else if (compare(best[0], pair[0]) === best[0]) {
- return best;
- } else {
- return pair;
- }
- }, null)[1];
-}
-function pick(obj, keys) {
- return keys.reduce(function (a, k) {
- a[k] = obj[k];
- return a;
- }, {});
-}
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-function validateWeekSettings(settings) {
- if (settings == null) {
- return null;
- } else if (typeof settings !== "object") {
- throw new InvalidArgumentError("Week settings must be an object");
- } else {
- if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some(function (v) {
- return !integerBetween(v, 1, 7);
- })) {
- throw new InvalidArgumentError("Invalid week settings");
- }
- return {
- firstDay: settings.firstDay,
- minimalDays: settings.minimalDays,
- weekend: Array.from(settings.weekend)
- };
- }
-}
-
-// NUMBERS AND STRINGS
-
-function integerBetween(thing, bottom, top) {
- return isInteger(thing) && thing >= bottom && thing <= top;
-}
-
-// x % n but takes the sign of n instead of x
-function floorMod(x, n) {
- return x - n * Math.floor(x / n);
-}
-function padStart(input, n) {
- if (n === void 0) {
- n = 2;
- }
- var isNeg = input < 0;
- var padded;
- if (isNeg) {
- padded = "-" + ("" + -input).padStart(n, "0");
- } else {
- padded = ("" + input).padStart(n, "0");
- }
- return padded;
-}
-function parseInteger(string) {
- if (isUndefined(string) || string === null || string === "") {
- return undefined;
- } else {
- return parseInt(string, 10);
- }
-}
-function parseFloating(string) {
- if (isUndefined(string) || string === null || string === "") {
- return undefined;
- } else {
- return parseFloat(string);
- }
-}
-function parseMillis(fraction) {
- // Return undefined (instead of 0) in these cases, where fraction is not set
- if (isUndefined(fraction) || fraction === null || fraction === "") {
- return undefined;
- } else {
- var f = parseFloat("0." + fraction) * 1000;
- return Math.floor(f);
- }
-}
-function roundTo(number, digits, rounding) {
- if (rounding === void 0) {
- rounding = "round";
- }
- var factor = Math.pow(10, digits);
- switch (rounding) {
- case "expand":
- return number > 0 ? Math.ceil(number * factor) / factor : Math.floor(number * factor) / factor;
- case "trunc":
- return Math.trunc(number * factor) / factor;
- case "round":
- return Math.round(number * factor) / factor;
- case "floor":
- return Math.floor(number * factor) / factor;
- case "ceil":
- return Math.ceil(number * factor) / factor;
- default:
- throw new RangeError("Value rounding " + rounding + " is out of range");
- }
-}
-
-// DATE BASICS
-
-function isLeapYear(year) {
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
-}
-function daysInYear(year) {
- return isLeapYear(year) ? 366 : 365;
-}
-function daysInMonth(year, month) {
- var modMonth = floorMod(month - 1, 12) + 1,
- modYear = year + (month - modMonth) / 12;
- if (modMonth === 2) {
- return isLeapYear(modYear) ? 29 : 28;
- } else {
- return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
- }
-}
-
-// convert a calendar object to a local timestamp (epoch, but with the offset baked in)
-function objToLocalTS(obj) {
- var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond);
-
- // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that
- if (obj.year < 100 && obj.year >= 0) {
- d = new Date(d);
- // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not
- // so if obj.year is in 99, but obj.day makes it roll over into year 100,
- // the calculations done by Date.UTC are using year 2000 - which is incorrect
- d.setUTCFullYear(obj.year, obj.month - 1, obj.day);
- }
- return +d;
-}
-
-// adapted from moment.js: https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/src/lib/units/week-calendar-utils.js
-function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) {
- var fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek);
- return -fwdlw + minDaysInFirstWeek - 1;
-}
-function weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek) {
- if (minDaysInFirstWeek === void 0) {
- minDaysInFirstWeek = 4;
- }
- if (startOfWeek === void 0) {
- startOfWeek = 1;
- }
- var weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek);
- var weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek);
- return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7;
-}
-function untruncateYear(year) {
- if (year > 99) {
- return year;
- } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year;
-}
-
-// PARSING
-
-function parseZoneInfo(ts, offsetFormat, locale, timeZone) {
- if (timeZone === void 0) {
- timeZone = null;
- }
- var date = new Date(ts),
- intlOpts = {
- hourCycle: "h23",
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit"
- };
- if (timeZone) {
- intlOpts.timeZone = timeZone;
- }
- var modified = _extends({
- timeZoneName: offsetFormat
- }, intlOpts);
- var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) {
- return m.type.toLowerCase() === "timezonename";
- });
- return parsed ? parsed.value : null;
-}
-
-// signedOffset('-5', '30') -> -330
-function signedOffset(offHourStr, offMinuteStr) {
- var offHour = parseInt(offHourStr, 10);
-
- // don't || this because we want to preserve -0
- if (Number.isNaN(offHour)) {
- offHour = 0;
- }
- var offMin = parseInt(offMinuteStr, 10) || 0,
- offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
- return offHour * 60 + offMinSigned;
-}
-
-// COERCION
-
-function asNumber(value) {
- var numericValue = Number(value);
- if (typeof value === "boolean" || value === "" || !Number.isFinite(numericValue)) throw new InvalidArgumentError("Invalid unit value " + value);
- return numericValue;
-}
-function normalizeObject(obj, normalizer) {
- var normalized = {};
- for (var u in obj) {
- if (hasOwnProperty(obj, u)) {
- var v = obj[u];
- if (v === undefined || v === null) continue;
- normalized[normalizer(u)] = asNumber(v);
- }
- }
- return normalized;
-}
-
-/**
- * Returns the offset's value as a string
- * @param {number} ts - Epoch milliseconds for which to get the offset
- * @param {string} format - What style of offset to return.
- * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
- * @return {string}
- */
-function formatOffset(offset, format) {
- var hours = Math.trunc(Math.abs(offset / 60)),
- minutes = Math.trunc(Math.abs(offset % 60)),
- sign = offset >= 0 ? "+" : "-";
- switch (format) {
- case "short":
- return "" + sign + padStart(hours, 2) + ":" + padStart(minutes, 2);
- case "narrow":
- return "" + sign + hours + (minutes > 0 ? ":" + minutes : "");
- case "techie":
- return "" + sign + padStart(hours, 2) + padStart(minutes, 2);
- default:
- throw new RangeError("Value format " + format + " is out of range for property format");
- }
-}
-function timeObject(obj) {
- return pick(obj, ["hour", "minute", "second", "millisecond"]);
-}
-
-/**
- * @private
- */
-
-var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
-var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
-var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
-function months(length) {
- switch (length) {
- case "narrow":
- return [].concat(monthsNarrow);
- case "short":
- return [].concat(monthsShort);
- case "long":
- return [].concat(monthsLong);
- case "numeric":
- return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
- case "2-digit":
- return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
- default:
- return null;
- }
-}
-var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
-var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
-var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
-function weekdays(length) {
- switch (length) {
- case "narrow":
- return [].concat(weekdaysNarrow);
- case "short":
- return [].concat(weekdaysShort);
- case "long":
- return [].concat(weekdaysLong);
- case "numeric":
- return ["1", "2", "3", "4", "5", "6", "7"];
- default:
- return null;
- }
-}
-var meridiems = ["AM", "PM"];
-var erasLong = ["Before Christ", "Anno Domini"];
-var erasShort = ["BC", "AD"];
-var erasNarrow = ["B", "A"];
-function eras(length) {
- switch (length) {
- case "narrow":
- return [].concat(erasNarrow);
- case "short":
- return [].concat(erasShort);
- case "long":
- return [].concat(erasLong);
- default:
- return null;
- }
-}
-function meridiemForDateTime(dt) {
- return meridiems[dt.hour < 12 ? 0 : 1];
-}
-function weekdayForDateTime(dt, length) {
- return weekdays(length)[dt.weekday - 1];
-}
-function monthForDateTime(dt, length) {
- return months(length)[dt.month - 1];
-}
-function eraForDateTime(dt, length) {
- return eras(length)[dt.year < 0 ? 0 : 1];
-}
-function formatRelativeTime(unit, count, numeric, narrow) {
- if (numeric === void 0) {
- numeric = "always";
- }
- if (narrow === void 0) {
- narrow = false;
- }
- var units = {
- years: ["year", "yr."],
- quarters: ["quarter", "qtr."],
- months: ["month", "mo."],
- weeks: ["week", "wk."],
- days: ["day", "day", "days"],
- hours: ["hour", "hr."],
- minutes: ["minute", "min."],
- seconds: ["second", "sec."]
- };
- var lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
- if (numeric === "auto" && lastable) {
- var isDay = unit === "days";
- switch (count) {
- case 1:
- return isDay ? "tomorrow" : "next " + units[unit][0];
- case -1:
- return isDay ? "yesterday" : "last " + units[unit][0];
- case 0:
- return isDay ? "today" : "this " + units[unit][0];
- }
- }
-
- var isInPast = Object.is(count, -0) || count < 0,
- fmtValue = Math.abs(count),
- singular = fmtValue === 1,
- lilUnits = units[unit],
- fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
- return isInPast ? fmtValue + " " + fmtUnit + " ago" : "in " + fmtValue + " " + fmtUnit;
-}
-
-function stringifyTokens(splits, tokenToString) {
- var s = "";
- for (var _iterator = _createForOfIteratorHelperLoose(splits), _step; !(_step = _iterator()).done;) {
- var token = _step.value;
- if (token.literal) {
- s += token.val;
- } else {
- s += tokenToString(token.val);
- }
- }
- return s;
-}
-var _macroTokenToFormatOpts = {
- D: DATE_SHORT,
- DD: DATE_MED,
- DDD: DATE_FULL,
- DDDD: DATE_HUGE,
- t: TIME_SIMPLE,
- tt: TIME_WITH_SECONDS,
- ttt: TIME_WITH_SHORT_OFFSET,
- tttt: TIME_WITH_LONG_OFFSET,
- T: TIME_24_SIMPLE,
- TT: TIME_24_WITH_SECONDS,
- TTT: TIME_24_WITH_SHORT_OFFSET,
- TTTT: TIME_24_WITH_LONG_OFFSET,
- f: DATETIME_SHORT,
- ff: DATETIME_MED,
- fff: DATETIME_FULL,
- ffff: DATETIME_HUGE,
- F: DATETIME_SHORT_WITH_SECONDS,
- FF: DATETIME_MED_WITH_SECONDS,
- FFF: DATETIME_FULL_WITH_SECONDS,
- FFFF: DATETIME_HUGE_WITH_SECONDS
-};
-
-/**
- * @private
- */
-var Formatter = /*#__PURE__*/function () {
- Formatter.create = function create(locale, opts) {
- if (opts === void 0) {
- opts = {};
- }
- return new Formatter(locale, opts);
- };
- Formatter.parseFormat = function parseFormat(fmt) {
- // white-space is always considered a literal in user-provided formats
- // the " " token has a special meaning (see unitForToken)
-
- var current = null,
- currentFull = "",
- bracketed = false;
- var splits = [];
- for (var i = 0; i < fmt.length; i++) {
- var c = fmt.charAt(i);
- if (c === "'") {
- // turn '' into a literal signal quote instead of just skipping the empty literal
- if (currentFull.length > 0 || bracketed) {
- splits.push({
- literal: bracketed || /^\s+$/.test(currentFull),
- val: currentFull === "" ? "'" : currentFull
- });
- }
- current = null;
- currentFull = "";
- bracketed = !bracketed;
- } else if (bracketed) {
- currentFull += c;
- } else if (c === current) {
- currentFull += c;
- } else {
- if (currentFull.length > 0) {
- splits.push({
- literal: /^\s+$/.test(currentFull),
- val: currentFull
- });
- }
- currentFull = c;
- current = c;
- }
- }
- if (currentFull.length > 0) {
- splits.push({
- literal: bracketed || /^\s+$/.test(currentFull),
- val: currentFull
- });
- }
- return splits;
- };
- Formatter.macroTokenToFormatOpts = function macroTokenToFormatOpts(token) {
- return _macroTokenToFormatOpts[token];
- };
- function Formatter(locale, formatOpts) {
- this.opts = formatOpts;
- this.loc = locale;
- this.systemLoc = null;
- }
- var _proto = Formatter.prototype;
- _proto.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) {
- if (this.systemLoc === null) {
- this.systemLoc = this.loc.redefaultToSystem();
- }
- var df = this.systemLoc.dtFormatter(dt, _extends({}, this.opts, opts));
- return df.format();
- };
- _proto.dtFormatter = function dtFormatter(dt, opts) {
- if (opts === void 0) {
- opts = {};
- }
- return this.loc.dtFormatter(dt, _extends({}, this.opts, opts));
- };
- _proto.formatDateTime = function formatDateTime(dt, opts) {
- return this.dtFormatter(dt, opts).format();
- };
- _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) {
- return this.dtFormatter(dt, opts).formatToParts();
- };
- _proto.formatInterval = function formatInterval(interval, opts) {
- var df = this.dtFormatter(interval.start, opts);
- return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());
- };
- _proto.resolvedOptions = function resolvedOptions(dt, opts) {
- return this.dtFormatter(dt, opts).resolvedOptions();
- };
- _proto.num = function num(n, p, signDisplay) {
- if (p === void 0) {
- p = 0;
- }
- if (signDisplay === void 0) {
- signDisplay = undefined;
- }
- // we get some perf out of doing this here, annoyingly
- if (this.opts.forceSimple) {
- return padStart(n, p);
- }
- var opts = _extends({}, this.opts);
- if (p > 0) {
- opts.padTo = p;
- }
- if (signDisplay) {
- opts.signDisplay = signDisplay;
- }
- return this.loc.numberFormatter(opts).format(n);
- };
- _proto.formatDateTimeFromString = function formatDateTimeFromString(dt, fmt) {
- var _this = this;
- var knownEnglish = this.loc.listingMode() === "en",
- useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory",
- string = function string(opts, extract) {
- return _this.loc.extract(dt, opts, extract);
- },
- formatOffset = function formatOffset(opts) {
- if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
- return "Z";
- }
- return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
- },
- meridiem = function meridiem() {
- return knownEnglish ? meridiemForDateTime(dt) : string({
- hour: "numeric",
- hourCycle: "h12"
- }, "dayperiod");
- },
- month = function month(length, standalone) {
- return knownEnglish ? monthForDateTime(dt, length) : string(standalone ? {
- month: length
- } : {
- month: length,
- day: "numeric"
- }, "month");
- },
- weekday = function weekday(length, standalone) {
- return knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? {
- weekday: length
- } : {
- weekday: length,
- month: "long",
- day: "numeric"
- }, "weekday");
- },
- maybeMacro = function maybeMacro(token) {
- var formatOpts = Formatter.macroTokenToFormatOpts(token);
- if (formatOpts) {
- return _this.formatWithSystemDefault(dt, formatOpts);
- } else {
- return token;
- }
- },
- era = function era(length) {
- return knownEnglish ? eraForDateTime(dt, length) : string({
- era: length
- }, "era");
- },
- tokenToString = function tokenToString(token) {
- // Where possible: https://cldr.unicode.org/translation/date-time/date-time-symbols
- switch (token) {
- // ms
- case "S":
- return _this.num(dt.millisecond);
- case "u":
- // falls through
- case "SSS":
- return _this.num(dt.millisecond, 3);
- // seconds
- case "s":
- return _this.num(dt.second);
- case "ss":
- return _this.num(dt.second, 2);
- // fractional seconds
- case "uu":
- return _this.num(Math.floor(dt.millisecond / 10), 2);
- case "uuu":
- return _this.num(Math.floor(dt.millisecond / 100));
- // minutes
- case "m":
- return _this.num(dt.minute);
- case "mm":
- return _this.num(dt.minute, 2);
- // hours
- case "h":
- return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
- case "hh":
- return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
- case "H":
- return _this.num(dt.hour);
- case "HH":
- return _this.num(dt.hour, 2);
- // offset
- case "Z":
- // like +6
- return formatOffset({
- format: "narrow",
- allowZ: _this.opts.allowZ
- });
- case "ZZ":
- // like +06:00
- return formatOffset({
- format: "short",
- allowZ: _this.opts.allowZ
- });
- case "ZZZ":
- // like +0600
- return formatOffset({
- format: "techie",
- allowZ: _this.opts.allowZ
- });
- case "ZZZZ":
- // like EST
- return dt.zone.offsetName(dt.ts, {
- format: "short",
- locale: _this.loc.locale
- });
- case "ZZZZZ":
- // like Eastern Standard Time
- return dt.zone.offsetName(dt.ts, {
- format: "long",
- locale: _this.loc.locale
- });
- // zone
- case "z":
- // like America/New_York
- return dt.zoneName;
- // meridiems
- case "a":
- return meridiem();
- // dates
- case "d":
- return useDateTimeFormatter ? string({
- day: "numeric"
- }, "day") : _this.num(dt.day);
- case "dd":
- return useDateTimeFormatter ? string({
- day: "2-digit"
- }, "day") : _this.num(dt.day, 2);
- // weekdays - standalone
- case "c":
- // like 1
- return _this.num(dt.weekday);
- case "ccc":
- // like 'Tues'
- return weekday("short", true);
- case "cccc":
- // like 'Tuesday'
- return weekday("long", true);
- case "ccccc":
- // like 'T'
- return weekday("narrow", true);
- // weekdays - format
- case "E":
- // like 1
- return _this.num(dt.weekday);
- case "EEE":
- // like 'Tues'
- return weekday("short", false);
- case "EEEE":
- // like 'Tuesday'
- return weekday("long", false);
- case "EEEEE":
- // like 'T'
- return weekday("narrow", false);
- // months - standalone
- case "L":
- // like 1
- return useDateTimeFormatter ? string({
- month: "numeric",
- day: "numeric"
- }, "month") : _this.num(dt.month);
- case "LL":
- // like 01, doesn't seem to work
- return useDateTimeFormatter ? string({
- month: "2-digit",
- day: "numeric"
- }, "month") : _this.num(dt.month, 2);
- case "LLL":
- // like Jan
- return month("short", true);
- case "LLLL":
- // like January
- return month("long", true);
- case "LLLLL":
- // like J
- return month("narrow", true);
- // months - format
- case "M":
- // like 1
- return useDateTimeFormatter ? string({
- month: "numeric"
- }, "month") : _this.num(dt.month);
- case "MM":
- // like 01
- return useDateTimeFormatter ? string({
- month: "2-digit"
- }, "month") : _this.num(dt.month, 2);
- case "MMM":
- // like Jan
- return month("short", false);
- case "MMMM":
- // like January
- return month("long", false);
- case "MMMMM":
- // like J
- return month("narrow", false);
- // years
- case "y":
- // like 2014
- return useDateTimeFormatter ? string({
- year: "numeric"
- }, "year") : _this.num(dt.year);
- case "yy":
- // like 14
- return useDateTimeFormatter ? string({
- year: "2-digit"
- }, "year") : _this.num(dt.year.toString().slice(-2), 2);
- case "yyyy":
- // like 0012
- return useDateTimeFormatter ? string({
- year: "numeric"
- }, "year") : _this.num(dt.year, 4);
- case "yyyyyy":
- // like 000012
- return useDateTimeFormatter ? string({
- year: "numeric"
- }, "year") : _this.num(dt.year, 6);
- // eras
- case "G":
- // like AD
- return era("short");
- case "GG":
- // like Anno Domini
- return era("long");
- case "GGGGG":
- return era("narrow");
- case "kk":
- return _this.num(dt.weekYear.toString().slice(-2), 2);
- case "kkkk":
- return _this.num(dt.weekYear, 4);
- case "W":
- return _this.num(dt.weekNumber);
- case "WW":
- return _this.num(dt.weekNumber, 2);
- case "n":
- return _this.num(dt.localWeekNumber);
- case "nn":
- return _this.num(dt.localWeekNumber, 2);
- case "ii":
- return _this.num(dt.localWeekYear.toString().slice(-2), 2);
- case "iiii":
- return _this.num(dt.localWeekYear, 4);
- case "o":
- return _this.num(dt.ordinal);
- case "ooo":
- return _this.num(dt.ordinal, 3);
- case "q":
- // like 1
- return _this.num(dt.quarter);
- case "qq":
- // like 01
- return _this.num(dt.quarter, 2);
- case "X":
- return _this.num(Math.floor(dt.ts / 1000));
- case "x":
- return _this.num(dt.ts);
- default:
- return maybeMacro(token);
- }
- };
- return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);
- };
- _proto.formatDurationFromString = function formatDurationFromString(dur, fmt) {
- var _this2 = this;
- var invertLargest = this.opts.signMode === "negativeLargestOnly" ? -1 : 1;
- var tokenToField = function tokenToField(token) {
- switch (token[0]) {
- case "S":
- return "milliseconds";
- case "s":
- return "seconds";
- case "m":
- return "minutes";
- case "h":
- return "hours";
- case "d":
- return "days";
- case "w":
- return "weeks";
- case "M":
- return "months";
- case "y":
- return "years";
- default:
- return null;
- }
- },
- tokenToString = function tokenToString(lildur, info) {
- return function (token) {
- var mapped = tokenToField(token);
- if (mapped) {
- var inversionFactor = info.isNegativeDuration && mapped !== info.largestUnit ? invertLargest : 1;
- var signDisplay;
- if (_this2.opts.signMode === "negativeLargestOnly" && mapped !== info.largestUnit) {
- signDisplay = "never";
- } else if (_this2.opts.signMode === "all") {
- signDisplay = "always";
- } else {
- // "auto" and "negative" are the same, but "auto" has better support
- signDisplay = "auto";
- }
- return _this2.num(lildur.get(mapped) * inversionFactor, token.length, signDisplay);
- } else {
- return token;
- }
- };
- },
- tokens = Formatter.parseFormat(fmt),
- realTokens = tokens.reduce(function (found, _ref) {
- var literal = _ref.literal,
- val = _ref.val;
- return literal ? found : found.concat(val);
- }, []),
- collapsed = dur.shiftTo.apply(dur, realTokens.map(tokenToField).filter(function (t) {
- return t;
- })),
- durationInfo = {
- isNegativeDuration: collapsed < 0,
- // this relies on "collapsed" being based on "shiftTo", which builds up the object
- // in order
- largestUnit: Object.keys(collapsed.values)[0]
- };
- return stringifyTokens(tokens, tokenToString(collapsed, durationInfo));
- };
- return Formatter;
-}();
-
-/*
- * This file handles parsing for well-specified formats. Here's how it works:
- * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.
- * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object
- * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.
- * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors.
- * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.
- * Some extractions are super dumb and simpleParse and fromStrings help DRY them.
- */
-
-var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;
-function combineRegexes() {
- for (var _len = arguments.length, regexes = new Array(_len), _key = 0; _key < _len; _key++) {
- regexes[_key] = arguments[_key];
- }
- var full = regexes.reduce(function (f, r) {
- return f + r.source;
- }, "");
- return RegExp("^" + full + "$");
-}
-function combineExtractors() {
- for (var _len2 = arguments.length, extractors = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- extractors[_key2] = arguments[_key2];
- }
- return function (m) {
- return extractors.reduce(function (_ref, ex) {
- var mergedVals = _ref[0],
- mergedZone = _ref[1],
- cursor = _ref[2];
- var _ex = ex(m, cursor),
- val = _ex[0],
- zone = _ex[1],
- next = _ex[2];
- return [_extends({}, mergedVals, val), zone || mergedZone, next];
- }, [{}, null, 1]).slice(0, 2);
- };
-}
-function parse(s) {
- if (s == null) {
- return [null, null];
- }
- for (var _len3 = arguments.length, patterns = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
- patterns[_key3 - 1] = arguments[_key3];
- }
- for (var _i = 0, _patterns = patterns; _i < _patterns.length; _i++) {
- var _patterns$_i = _patterns[_i],
- regex = _patterns$_i[0],
- extractor = _patterns$_i[1];
- var m = regex.exec(s);
- if (m) {
- return extractor(m);
- }
- }
- return [null, null];
-}
-function simpleParse() {
- for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
- keys[_key4] = arguments[_key4];
- }
- return function (match, cursor) {
- var ret = {};
- var i;
- for (i = 0; i < keys.length; i++) {
- ret[keys[i]] = parseInteger(match[cursor + i]);
- }
- return [ret, null, cursor + i];
- };
-}
-
-// ISO and SQL parsing
-var offsetRegex = /(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/;
-var isoExtendedZone = "(?:" + offsetRegex.source + "?(?:\\[(" + ianaRegex.source + ")\\])?)?";
-var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
-var isoTimeRegex = RegExp("" + isoTimeBaseRegex.source + isoExtendedZone);
-var isoTimeExtensionRegex = RegExp("(?:[Tt]" + isoTimeRegex.source + ")?");
-var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
-var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
-var isoOrdinalRegex = /(\d{4})-?(\d{3})/;
-var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay");
-var extractISOOrdinalData = simpleParse("year", "ordinal");
-var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; // dumbed-down version of the ISO one
-var sqlTimeRegex = RegExp(isoTimeBaseRegex.source + " ?(?:" + offsetRegex.source + "|(" + ianaRegex.source + "))?");
-var sqlTimeExtensionRegex = RegExp("(?: " + sqlTimeRegex.source + ")?");
-function int(match, pos, fallback) {
- var m = match[pos];
- return isUndefined(m) ? fallback : parseInteger(m);
-}
-function extractISOYmd(match, cursor) {
- var item = {
- year: int(match, cursor),
- month: int(match, cursor + 1, 1),
- day: int(match, cursor + 2, 1)
- };
- return [item, null, cursor + 3];
-}
-function extractISOTime(match, cursor) {
- var item = {
- hours: int(match, cursor, 0),
- minutes: int(match, cursor + 1, 0),
- seconds: int(match, cursor + 2, 0),
- milliseconds: parseMillis(match[cursor + 3])
- };
- return [item, null, cursor + 4];
-}
-function extractISOOffset(match, cursor) {
- var local = !match[cursor] && !match[cursor + 1],
- fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),
- zone = local ? null : FixedOffsetZone.instance(fullOffset);
- return [{}, zone, cursor + 3];
-}
-function extractIANAZone(match, cursor) {
- var zone = match[cursor] ? IANAZone.create(match[cursor]) : null;
- return [{}, zone, cursor + 1];
-}
-
-// ISO time parsing
-
-var isoTimeOnly = RegExp("^T?" + isoTimeBaseRegex.source + "$");
-
-// ISO duration parsing
-
-var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
-function extractISODuration(match) {
- var s = match[0],
- yearStr = match[1],
- monthStr = match[2],
- weekStr = match[3],
- dayStr = match[4],
- hourStr = match[5],
- minuteStr = match[6],
- secondStr = match[7],
- millisecondsStr = match[8];
- var hasNegativePrefix = s[0] === "-";
- var negativeSeconds = secondStr && secondStr[0] === "-";
- var maybeNegate = function maybeNegate(num, force) {
- if (force === void 0) {
- force = false;
- }
- return num !== undefined && (force || num && hasNegativePrefix) ? -num : num;
- };
- return [{
- years: maybeNegate(parseFloating(yearStr)),
- months: maybeNegate(parseFloating(monthStr)),
- weeks: maybeNegate(parseFloating(weekStr)),
- days: maybeNegate(parseFloating(dayStr)),
- hours: maybeNegate(parseFloating(hourStr)),
- minutes: maybeNegate(parseFloating(minuteStr)),
- seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"),
- milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
- }];
-}
-
-// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York
-// and not just that we're in -240 *right now*. But since I don't think these are used that often
-// I'm just going to ignore that
-var obsOffsets = {
- GMT: 0,
- EDT: -4 * 60,
- EST: -5 * 60,
- CDT: -5 * 60,
- CST: -6 * 60,
- MDT: -6 * 60,
- MST: -7 * 60,
- PDT: -7 * 60,
- PST: -8 * 60
-};
-function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
- var result = {
- year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
- month: monthsShort.indexOf(monthStr) + 1,
- day: parseInteger(dayStr),
- hour: parseInteger(hourStr),
- minute: parseInteger(minuteStr)
- };
- if (secondStr) result.second = parseInteger(secondStr);
- if (weekdayStr) {
- result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
- }
- return result;
-}
-
-// RFC 2822/5322
-var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
-function extractRFC2822(match) {
- var weekdayStr = match[1],
- dayStr = match[2],
- monthStr = match[3],
- yearStr = match[4],
- hourStr = match[5],
- minuteStr = match[6],
- secondStr = match[7],
- obsOffset = match[8],
- milOffset = match[9],
- offHourStr = match[10],
- offMinuteStr = match[11],
- result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
- var offset;
- if (obsOffset) {
- offset = obsOffsets[obsOffset];
- } else if (milOffset) {
- offset = 0;
- } else {
- offset = signedOffset(offHourStr, offMinuteStr);
- }
- return [result, new FixedOffsetZone(offset)];
-}
-function preprocessRFC2822(s) {
- // Remove comments and folding whitespace and replace multiple-spaces with a single space
- return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
-}
-
-// http date
-
-var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,
- rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,
- ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
-function extractRFC1123Or850(match) {
- var weekdayStr = match[1],
- dayStr = match[2],
- monthStr = match[3],
- yearStr = match[4],
- hourStr = match[5],
- minuteStr = match[6],
- secondStr = match[7],
- result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
- return [result, FixedOffsetZone.utcInstance];
-}
-function extractASCII(match) {
- var weekdayStr = match[1],
- monthStr = match[2],
- dayStr = match[3],
- hourStr = match[4],
- minuteStr = match[5],
- secondStr = match[6],
- yearStr = match[7],
- result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
- return [result, FixedOffsetZone.utcInstance];
-}
-var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
-var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
-var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
-var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
-var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone);
-var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone);
-var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone);
-var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
-
-/*
- * @private
- */
-
-function parseISODate(s) {
- return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
-}
-function parseRFC2822Date(s) {
- return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);
-}
-function parseHTTPDate(s) {
- return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]);
-}
-function parseISODuration(s) {
- return parse(s, [isoDuration, extractISODuration]);
-}
-var extractISOTimeOnly = combineExtractors(extractISOTime);
-function parseISOTimeOnly(s) {
- return parse(s, [isoTimeOnly, extractISOTimeOnly]);
-}
-var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
-var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
-var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
-function parseSQL(s) {
- return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]);
-}
-
-var INVALID$2 = "Invalid Duration";
-
-// unit conversion constants
-var lowOrderMatrix = {
- weeks: {
- days: 7,
- hours: 7 * 24,
- minutes: 7 * 24 * 60,
- seconds: 7 * 24 * 60 * 60,
- milliseconds: 7 * 24 * 60 * 60 * 1000
- },
- days: {
- hours: 24,
- minutes: 24 * 60,
- seconds: 24 * 60 * 60,
- milliseconds: 24 * 60 * 60 * 1000
- },
- hours: {
- minutes: 60,
- seconds: 60 * 60,
- milliseconds: 60 * 60 * 1000
- },
- minutes: {
- seconds: 60,
- milliseconds: 60 * 1000
- },
- seconds: {
- milliseconds: 1000
- }
- },
- casualMatrix = _extends({
- years: {
- quarters: 4,
- months: 12,
- weeks: 52,
- days: 365,
- hours: 365 * 24,
- minutes: 365 * 24 * 60,
- seconds: 365 * 24 * 60 * 60,
- milliseconds: 365 * 24 * 60 * 60 * 1000
- },
- quarters: {
- months: 3,
- weeks: 13,
- days: 91,
- hours: 91 * 24,
- minutes: 91 * 24 * 60,
- seconds: 91 * 24 * 60 * 60,
- milliseconds: 91 * 24 * 60 * 60 * 1000
- },
- months: {
- weeks: 4,
- days: 30,
- hours: 30 * 24,
- minutes: 30 * 24 * 60,
- seconds: 30 * 24 * 60 * 60,
- milliseconds: 30 * 24 * 60 * 60 * 1000
- }
- }, lowOrderMatrix),
- daysInYearAccurate = 146097.0 / 400,
- daysInMonthAccurate = 146097.0 / 4800,
- accurateMatrix = _extends({
- years: {
- quarters: 4,
- months: 12,
- weeks: daysInYearAccurate / 7,
- days: daysInYearAccurate,
- hours: daysInYearAccurate * 24,
- minutes: daysInYearAccurate * 24 * 60,
- seconds: daysInYearAccurate * 24 * 60 * 60,
- milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000
- },
- quarters: {
- months: 3,
- weeks: daysInYearAccurate / 28,
- days: daysInYearAccurate / 4,
- hours: daysInYearAccurate * 24 / 4,
- minutes: daysInYearAccurate * 24 * 60 / 4,
- seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
- milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4
- },
- months: {
- weeks: daysInMonthAccurate / 7,
- days: daysInMonthAccurate,
- hours: daysInMonthAccurate * 24,
- minutes: daysInMonthAccurate * 24 * 60,
- seconds: daysInMonthAccurate * 24 * 60 * 60,
- milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000
- }
- }, lowOrderMatrix);
-
-// units ordered by size
-var orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"];
-var reverseUnits = orderedUnits$1.slice(0).reverse();
-
-// clone really means "create another instance just like this one, but with these changes"
-function clone$1(dur, alts, clear) {
- if (clear === void 0) {
- clear = false;
- }
- // deep merge for vals
- var conf = {
- values: clear ? alts.values : _extends({}, dur.values, alts.values || {}),
- loc: dur.loc.clone(alts.loc),
- conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
- matrix: alts.matrix || dur.matrix
- };
- return new Duration(conf);
-}
-function durationToMillis(matrix, vals) {
- var _vals$milliseconds;
- var sum = (_vals$milliseconds = vals.milliseconds) != null ? _vals$milliseconds : 0;
- for (var _iterator = _createForOfIteratorHelperLoose(reverseUnits.slice(1)), _step; !(_step = _iterator()).done;) {
- var unit = _step.value;
- if (vals[unit]) {
- sum += vals[unit] * matrix[unit]["milliseconds"];
- }
- }
- return sum;
-}
-
-// NB: mutates parameters
-function normalizeValues(matrix, vals) {
- // the logic below assumes the overall value of the duration is positive
- // if this is not the case, factor is used to make it so
- var factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;
- orderedUnits$1.reduceRight(function (previous, current) {
- if (!isUndefined(vals[current])) {
- if (previous) {
- var previousVal = vals[previous] * factor;
- var conv = matrix[current][previous];
-
- // if (previousVal < 0):
- // lower order unit is negative (e.g. { years: 2, days: -2 })
- // normalize this by reducing the higher order unit by the appropriate amount
- // and increasing the lower order unit
- // this can never make the higher order unit negative, because this function only operates
- // on positive durations, so the amount of time represented by the lower order unit cannot
- // be larger than the higher order unit
- // else:
- // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 })
- // in this case we attempt to convert as much as possible from the lower order unit into
- // the higher order one
- //
- // Math.floor takes care of both of these cases, rounding away from 0
- // if previousVal < 0 it makes the absolute value larger
- // if previousVal >= it makes the absolute value smaller
- var rollUp = Math.floor(previousVal / conv);
- vals[current] += rollUp * factor;
- vals[previous] -= rollUp * conv * factor;
- }
- return current;
- } else {
- return previous;
- }
- }, null);
-
- // try to convert any decimals into smaller units if possible
- // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 }
- orderedUnits$1.reduce(function (previous, current) {
- if (!isUndefined(vals[current])) {
- if (previous) {
- var fraction = vals[previous] % 1;
- vals[previous] -= fraction;
- vals[current] += fraction * matrix[previous][current];
- }
- return current;
- } else {
- return previous;
- }
- }, null);
-}
-
-// Remove all properties with a value of 0 from an object
-function removeZeroes(vals) {
- var newVals = {};
- for (var _i = 0, _Object$entries = Object.entries(vals); _i < _Object$entries.length; _i++) {
- var _Object$entries$_i = _Object$entries[_i],
- key = _Object$entries$_i[0],
- value = _Object$entries$_i[1];
- if (value !== 0) {
- newVals[key] = value;
- }
- }
- return newVals;
-}
-
-/**
- * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.
- *
- * Here is a brief overview of commonly used methods and getters in Duration:
- *
- * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.
- * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.
- * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.
- * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.
- * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}
- *
- * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.
- */
-var Duration = /*#__PURE__*/function (_Symbol$for) {
- /**
- * @private
- */
- function Duration(config) {
- var accurate = config.conversionAccuracy === "longterm" || false;
- var matrix = accurate ? accurateMatrix : casualMatrix;
- if (config.matrix) {
- matrix = config.matrix;
- }
-
- /**
- * @access private
- */
- this.values = config.values;
- /**
- * @access private
- */
- this.loc = config.loc || Locale.create();
- /**
- * @access private
- */
- this.conversionAccuracy = accurate ? "longterm" : "casual";
- /**
- * @access private
- */
- this.invalid = config.invalid || null;
- /**
- * @access private
- */
- this.matrix = matrix;
- /**
- * @access private
- */
- this.isLuxonDuration = true;
- }
-
- /**
- * Create Duration from a number of milliseconds.
- * @param {number} count of milliseconds
- * @param {Object} opts - options for parsing
- * @param {string} [opts.locale='en-US'] - the locale to use
- * @param {string} opts.numberingSystem - the numbering system to use
- * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
- * @return {Duration}
- */
- Duration.fromMillis = function fromMillis(count, opts) {
- return Duration.fromObject({
- milliseconds: count
- }, opts);
- }
-
- /**
- * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
- * If this object is empty then a zero milliseconds duration is returned.
- * @param {Object} obj - the object to create the DateTime from
- * @param {number} obj.years
- * @param {number} obj.quarters
- * @param {number} obj.months
- * @param {number} obj.weeks
- * @param {number} obj.days
- * @param {number} obj.hours
- * @param {number} obj.minutes
- * @param {number} obj.seconds
- * @param {number} obj.milliseconds
- * @param {Object} [opts=[]] - options for creating this Duration
- * @param {string} [opts.locale='en-US'] - the locale to use
- * @param {string} opts.numberingSystem - the numbering system to use
- * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
- * @param {string} [opts.matrix=Object] - the custom conversion system to use
- * @return {Duration}
- */;
- Duration.fromObject = function fromObject(obj, opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (obj == null || typeof obj !== "object") {
- throw new InvalidArgumentError("Duration.fromObject: argument expected to be an object, got " + (obj === null ? "null" : typeof obj));
- }
- return new Duration({
- values: normalizeObject(obj, Duration.normalizeUnit),
- loc: Locale.fromObject(opts),
- conversionAccuracy: opts.conversionAccuracy,
- matrix: opts.matrix
- });
- }
-
- /**
- * Create a Duration from DurationLike.
- *
- * @param {Object | number | Duration} durationLike
- * One of:
- * - object with keys like 'years' and 'hours'.
- * - number representing milliseconds
- * - Duration instance
- * @return {Duration}
- */;
- Duration.fromDurationLike = function fromDurationLike(durationLike) {
- if (isNumber(durationLike)) {
- return Duration.fromMillis(durationLike);
- } else if (Duration.isDuration(durationLike)) {
- return durationLike;
- } else if (typeof durationLike === "object") {
- return Duration.fromObject(durationLike);
- } else {
- throw new InvalidArgumentError("Unknown duration argument " + durationLike + " of type " + typeof durationLike);
- }
- }
-
- /**
- * Create a Duration from an ISO 8601 duration string.
- * @param {string} text - text to parse
- * @param {Object} opts - options for parsing
- * @param {string} [opts.locale='en-US'] - the locale to use
- * @param {string} opts.numberingSystem - the numbering system to use
- * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
- * @param {string} [opts.matrix=Object] - the preset conversion system to use
- * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
- * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
- * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
- * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
- * @return {Duration}
- */;
- Duration.fromISO = function fromISO(text, opts) {
- var _parseISODuration = parseISODuration(text),
- parsed = _parseISODuration[0];
- if (parsed) {
- return Duration.fromObject(parsed, opts);
- } else {
- return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601");
- }
- }
-
- /**
- * Create a Duration from an ISO 8601 time string.
- * @param {string} text - text to parse
- * @param {Object} opts - options for parsing
- * @param {string} [opts.locale='en-US'] - the locale to use
- * @param {string} opts.numberingSystem - the numbering system to use
- * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
- * @param {string} [opts.matrix=Object] - the conversion system to use
- * @see https://en.wikipedia.org/wiki/ISO_8601#Times
- * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
- * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
- * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
- * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
- * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
- * @return {Duration}
- */;
- Duration.fromISOTime = function fromISOTime(text, opts) {
- var _parseISOTimeOnly = parseISOTimeOnly(text),
- parsed = _parseISOTimeOnly[0];
- if (parsed) {
- return Duration.fromObject(parsed, opts);
- } else {
- return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601");
- }
- }
-
- /**
- * Create an invalid Duration.
- * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
- * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
- * @return {Duration}
- */;
- Duration.invalid = function invalid(reason, explanation) {
- if (explanation === void 0) {
- explanation = null;
- }
- if (!reason) {
- throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
- }
- var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
- if (Settings.throwOnInvalid) {
- throw new InvalidDurationError(invalid);
- } else {
- return new Duration({
- invalid: invalid
- });
- }
- }
-
- /**
- * @private
- */;
- Duration.normalizeUnit = function normalizeUnit(unit) {
- var normalized = {
- year: "years",
- years: "years",
- quarter: "quarters",
- quarters: "quarters",
- month: "months",
- months: "months",
- week: "weeks",
- weeks: "weeks",
- day: "days",
- days: "days",
- hour: "hours",
- hours: "hours",
- minute: "minutes",
- minutes: "minutes",
- second: "seconds",
- seconds: "seconds",
- millisecond: "milliseconds",
- milliseconds: "milliseconds"
- }[unit ? unit.toLowerCase() : unit];
- if (!normalized) throw new InvalidUnitError(unit);
- return normalized;
- }
-
- /**
- * Check if an object is a Duration. Works across context boundaries
- * @param {object} o
- * @return {boolean}
- */;
- Duration.isDuration = function isDuration(o) {
- return o && o.isLuxonDuration || false;
- }
-
- /**
- * Get the locale of a Duration, such 'en-GB'
- * @type {string}
- */;
- var _proto = Duration.prototype;
- /**
- * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
- * * `S` for milliseconds
- * * `s` for seconds
- * * `m` for minutes
- * * `h` for hours
- * * `d` for days
- * * `w` for weeks
- * * `M` for months
- * * `y` for years
- * Notes:
- * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
- * * Tokens can be escaped by wrapping with single quotes.
- * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
- * @param {string} fmt - the format string
- * @param {Object} opts - options
- * @param {boolean} [opts.floor=true] - floor numerical values
- * @param {'negative'|'all'|'negativeLargestOnly'} [opts.signMode=negative] - How to handle signs
- * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
- * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
- * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
- * @example Duration.fromObject({ days: 6, seconds: 2 }).toFormat("d s", { signMode: "all" }) //=> "+6 +2"
- * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat("d s", { signMode: "all" }) //=> "-6 -2"
- * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat("d s", { signMode: "negativeLargestOnly" }) //=> "-6 2"
- * @return {string}
- */
- _proto.toFormat = function toFormat(fmt, opts) {
- if (opts === void 0) {
- opts = {};
- }
- // reverse-compat since 1.2; we always round down now, never up, and we do it by default
- var fmtOpts = _extends({}, opts, {
- floor: opts.round !== false && opts.floor !== false
- });
- return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2;
- }
-
- /**
- * Returns a string representation of a Duration with all units included.
- * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
- * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.
- * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.
- * @param {boolean} [opts.showZeros=true] - Show all units previously used by the duration even if they are zero
- * @example
- * ```js
- * var dur = Duration.fromObject({ months: 1, weeks: 0, hours: 5, minutes: 6 })
- * dur.toHuman() //=> '1 month, 0 weeks, 5 hours, 6 minutes'
- * dur.toHuman({ listStyle: "long" }) //=> '1 month, 0 weeks, 5 hours, and 6 minutes'
- * dur.toHuman({ unitDisplay: "short" }) //=> '1 mth, 0 wks, 5 hr, 6 min'
- * dur.toHuman({ showZeros: false }) //=> '1 month, 5 hours, 6 minutes'
- * ```
- */;
- _proto.toHuman = function toHuman(opts) {
- var _this = this;
- if (opts === void 0) {
- opts = {};
- }
- if (!this.isValid) return INVALID$2;
- var showZeros = opts.showZeros !== false;
- var l = orderedUnits$1.map(function (unit) {
- var val = _this.values[unit];
- if (isUndefined(val) || val === 0 && !showZeros) {
- return null;
- }
- return _this.loc.numberFormatter(_extends({
- style: "unit",
- unitDisplay: "long"
- }, opts, {
- unit: unit.slice(0, -1)
- })).format(val);
- }).filter(function (n) {
- return n;
- });
- return this.loc.listFormatter(_extends({
- type: "conjunction",
- style: opts.listStyle || "narrow"
- }, opts)).format(l);
- }
-
- /**
- * Returns a JavaScript object with this Duration's values.
- * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
- * @return {Object}
- */;
- _proto.toObject = function toObject() {
- if (!this.isValid) return {};
- return _extends({}, this.values);
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this Duration.
- * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
- * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
- * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
- * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
- * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
- * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
- * @return {string}
- */;
- _proto.toISO = function toISO() {
- // we could use the formatter, but this is an easier way to get the minimum string
- if (!this.isValid) return null;
- var s = "P";
- if (this.years !== 0) s += this.years + "Y";
- if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M";
- if (this.weeks !== 0) s += this.weeks + "W";
- if (this.days !== 0) s += this.days + "D";
- if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T";
- if (this.hours !== 0) s += this.hours + "H";
- if (this.minutes !== 0) s += this.minutes + "M";
- if (this.seconds !== 0 || this.milliseconds !== 0)
- // this will handle "floating point madness" by removing extra decimal places
- // https://stackoverflow.com/questions/588004/is-floating-point-math-broken
- s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S";
- if (s === "P") s += "T0S";
- return s;
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
- * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
- * @see https://en.wikipedia.org/wiki/ISO_8601#Times
- * @param {Object} opts - options
- * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
- * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
- * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
- * @param {string} [opts.format='extended'] - choose between the basic and extended format
- * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
- * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
- * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
- * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
- * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
- * @return {string}
- */;
- _proto.toISOTime = function toISOTime(opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (!this.isValid) return null;
- var millis = this.toMillis();
- if (millis < 0 || millis >= 86400000) return null;
- opts = _extends({
- suppressMilliseconds: false,
- suppressSeconds: false,
- includePrefix: false,
- format: "extended"
- }, opts, {
- includeOffset: false
- });
- var dateTime = DateTime.fromMillis(millis, {
- zone: "UTC"
- });
- return dateTime.toISOTime(opts);
- }
-
- /**
- * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
- * @return {string}
- */;
- _proto.toJSON = function toJSON() {
- return this.toISO();
- }
-
- /**
- * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
- * @return {string}
- */;
- _proto.toString = function toString() {
- return this.toISO();
- }
-
- /**
- * Returns a string representation of this Duration appropriate for the REPL.
- * @return {string}
- */;
- _proto[_Symbol$for] = function () {
- if (this.isValid) {
- return "Duration { values: " + JSON.stringify(this.values) + " }";
- } else {
- return "Duration { Invalid, reason: " + this.invalidReason + " }";
- }
- }
-
- /**
- * Returns an milliseconds value of this Duration.
- * @return {number}
- */;
- _proto.toMillis = function toMillis() {
- if (!this.isValid) return NaN;
- return durationToMillis(this.matrix, this.values);
- }
-
- /**
- * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
- * @return {number}
- */;
- _proto.valueOf = function valueOf() {
- return this.toMillis();
- }
-
- /**
- * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
- * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
- * @return {Duration}
- */;
- _proto.plus = function plus(duration) {
- if (!this.isValid) return this;
- var dur = Duration.fromDurationLike(duration),
- result = {};
- for (var _i2 = 0, _orderedUnits = orderedUnits$1; _i2 < _orderedUnits.length; _i2++) {
- var k = _orderedUnits[_i2];
- if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
- result[k] = dur.get(k) + this.get(k);
- }
- }
- return clone$1(this, {
- values: result
- }, true);
- }
-
- /**
- * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
- * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
- * @return {Duration}
- */;
- _proto.minus = function minus(duration) {
- if (!this.isValid) return this;
- var dur = Duration.fromDurationLike(duration);
- return this.plus(dur.negate());
- }
-
- /**
- * Scale this Duration by the specified amount. Return a newly-constructed Duration.
- * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
- * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
- * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
- * @return {Duration}
- */;
- _proto.mapUnits = function mapUnits(fn) {
- if (!this.isValid) return this;
- var result = {};
- for (var _i3 = 0, _Object$keys = Object.keys(this.values); _i3 < _Object$keys.length; _i3++) {
- var k = _Object$keys[_i3];
- result[k] = asNumber(fn(this.values[k], k));
- }
- return clone$1(this, {
- values: result
- }, true);
- }
-
- /**
- * Get the value of unit.
- * @param {string} unit - a unit such as 'minute' or 'day'
- * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
- * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
- * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
- * @return {number}
- */;
- _proto.get = function get(unit) {
- return this[Duration.normalizeUnit(unit)];
- }
-
- /**
- * "Set" the values of specified units. Return a newly-constructed Duration.
- * @param {Object} values - a mapping of units to numbers
- * @example dur.set({ years: 2017 })
- * @example dur.set({ hours: 8, minutes: 30 })
- * @return {Duration}
- */;
- _proto.set = function set(values) {
- if (!this.isValid) return this;
- var mixed = _extends({}, this.values, normalizeObject(values, Duration.normalizeUnit));
- return clone$1(this, {
- values: mixed
- });
- }
-
- /**
- * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
- * @example dur.reconfigure({ locale: 'en-GB' })
- * @return {Duration}
- */;
- _proto.reconfigure = function reconfigure(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- locale = _ref.locale,
- numberingSystem = _ref.numberingSystem,
- conversionAccuracy = _ref.conversionAccuracy,
- matrix = _ref.matrix;
- var loc = this.loc.clone({
- locale: locale,
- numberingSystem: numberingSystem
- });
- var opts = {
- loc: loc,
- matrix: matrix,
- conversionAccuracy: conversionAccuracy
- };
- return clone$1(this, opts);
- }
-
- /**
- * Return the length of the duration in the specified unit.
- * @param {string} unit - a unit such as 'minutes' or 'days'
- * @example Duration.fromObject({years: 1}).as('days') //=> 365
- * @example Duration.fromObject({years: 1}).as('months') //=> 12
- * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
- * @return {number}
- */;
- _proto.as = function as(unit) {
- return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
- }
-
- /**
- * Reduce this Duration to its canonical representation in its current units.
- * Assuming the overall value of the Duration is positive, this means:
- * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)
- * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise
- * the overall value would be negative, see third example)
- * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)
- *
- * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.
- * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
- * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }
- * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
- * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }
- * @return {Duration}
- */;
- _proto.normalize = function normalize() {
- if (!this.isValid) return this;
- var vals = this.toObject();
- normalizeValues(this.matrix, vals);
- return clone$1(this, {
- values: vals
- }, true);
- }
-
- /**
- * Rescale units to its largest representation
- * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
- * @return {Duration}
- */;
- _proto.rescale = function rescale() {
- if (!this.isValid) return this;
- var vals = removeZeroes(this.normalize().shiftToAll().toObject());
- return clone$1(this, {
- values: vals
- }, true);
- }
-
- /**
- * Convert this Duration into its representation in a different set of units.
- * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
- * @return {Duration}
- */;
- _proto.shiftTo = function shiftTo() {
- for (var _len = arguments.length, units = new Array(_len), _key = 0; _key < _len; _key++) {
- units[_key] = arguments[_key];
- }
- if (!this.isValid) return this;
- if (units.length === 0) {
- return this;
- }
- units = units.map(function (u) {
- return Duration.normalizeUnit(u);
- });
- var built = {},
- accumulated = {},
- vals = this.toObject();
- var lastUnit;
- for (var _i4 = 0, _orderedUnits2 = orderedUnits$1; _i4 < _orderedUnits2.length; _i4++) {
- var k = _orderedUnits2[_i4];
- if (units.indexOf(k) >= 0) {
- lastUnit = k;
- var own = 0;
-
- // anything we haven't boiled down yet should get boiled to this unit
- for (var ak in accumulated) {
- own += this.matrix[ak][k] * accumulated[ak];
- accumulated[ak] = 0;
- }
-
- // plus anything that's already in this unit
- if (isNumber(vals[k])) {
- own += vals[k];
- }
-
- // only keep the integer part for now in the hopes of putting any decimal part
- // into a smaller unit later
- var i = Math.trunc(own);
- built[k] = i;
- accumulated[k] = (own * 1000 - i * 1000) / 1000;
-
- // otherwise, keep it in the wings to boil it later
- } else if (isNumber(vals[k])) {
- accumulated[k] = vals[k];
- }
- }
-
- // anything leftover becomes the decimal for the last unit
- // lastUnit must be defined since units is not empty
- for (var key in accumulated) {
- if (accumulated[key] !== 0) {
- built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
- }
- }
- normalizeValues(this.matrix, built);
- return clone$1(this, {
- values: built
- }, true);
- }
-
- /**
- * Shift this Duration to all available units.
- * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
- * @return {Duration}
- */;
- _proto.shiftToAll = function shiftToAll() {
- if (!this.isValid) return this;
- return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds");
- }
-
- /**
- * Return the negative of this Duration.
- * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
- * @return {Duration}
- */;
- _proto.negate = function negate() {
- if (!this.isValid) return this;
- var negated = {};
- for (var _i5 = 0, _Object$keys2 = Object.keys(this.values); _i5 < _Object$keys2.length; _i5++) {
- var k = _Object$keys2[_i5];
- negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
- }
- return clone$1(this, {
- values: negated
- }, true);
- }
-
- /**
- * Removes all units with values equal to 0 from this Duration.
- * @example Duration.fromObject({ years: 2, days: 0, hours: 0, minutes: 0 }).removeZeros().toObject() //=> { years: 2 }
- * @return {Duration}
- */;
- _proto.removeZeros = function removeZeros() {
- if (!this.isValid) return this;
- var vals = removeZeroes(this.values);
- return clone$1(this, {
- values: vals
- }, true);
- }
-
- /**
- * Get the years.
- * @type {number}
- */;
- /**
- * Equality check
- * Two Durations are equal iff they have the same units and the same values for each unit.
- * @param {Duration} other
- * @return {boolean}
- */
- _proto.equals = function equals(other) {
- if (!this.isValid || !other.isValid) {
- return false;
- }
- if (!this.loc.equals(other.loc)) {
- return false;
- }
- function eq(v1, v2) {
- // Consider 0 and undefined as equal
- if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;
- return v1 === v2;
- }
- for (var _i6 = 0, _orderedUnits3 = orderedUnits$1; _i6 < _orderedUnits3.length; _i6++) {
- var u = _orderedUnits3[_i6];
- if (!eq(this.values[u], other.values[u])) {
- return false;
- }
- }
- return true;
- };
- _createClass(Duration, [{
- key: "locale",
- get: function get() {
- return this.isValid ? this.loc.locale : null;
- }
-
- /**
- * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
- *
- * @type {string}
- */
- }, {
- key: "numberingSystem",
- get: function get() {
- return this.isValid ? this.loc.numberingSystem : null;
- }
- }, {
- key: "years",
- get: function get() {
- return this.isValid ? this.values.years || 0 : NaN;
- }
-
- /**
- * Get the quarters.
- * @type {number}
- */
- }, {
- key: "quarters",
- get: function get() {
- return this.isValid ? this.values.quarters || 0 : NaN;
- }
-
- /**
- * Get the months.
- * @type {number}
- */
- }, {
- key: "months",
- get: function get() {
- return this.isValid ? this.values.months || 0 : NaN;
- }
-
- /**
- * Get the weeks
- * @type {number}
- */
- }, {
- key: "weeks",
- get: function get() {
- return this.isValid ? this.values.weeks || 0 : NaN;
- }
-
- /**
- * Get the days.
- * @type {number}
- */
- }, {
- key: "days",
- get: function get() {
- return this.isValid ? this.values.days || 0 : NaN;
- }
-
- /**
- * Get the hours.
- * @type {number}
- */
- }, {
- key: "hours",
- get: function get() {
- return this.isValid ? this.values.hours || 0 : NaN;
- }
-
- /**
- * Get the minutes.
- * @type {number}
- */
- }, {
- key: "minutes",
- get: function get() {
- return this.isValid ? this.values.minutes || 0 : NaN;
- }
-
- /**
- * Get the seconds.
- * @return {number}
- */
- }, {
- key: "seconds",
- get: function get() {
- return this.isValid ? this.values.seconds || 0 : NaN;
- }
-
- /**
- * Get the milliseconds.
- * @return {number}
- */
- }, {
- key: "milliseconds",
- get: function get() {
- return this.isValid ? this.values.milliseconds || 0 : NaN;
- }
-
- /**
- * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
- * on invalid DateTimes or Intervals.
- * @return {boolean}
- */
- }, {
- key: "isValid",
- get: function get() {
- return this.invalid === null;
- }
-
- /**
- * Returns an error code if this Duration became invalid, or null if the Duration is valid
- * @return {string}
- */
- }, {
- key: "invalidReason",
- get: function get() {
- return this.invalid ? this.invalid.reason : null;
- }
-
- /**
- * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
- * @type {string}
- */
- }, {
- key: "invalidExplanation",
- get: function get() {
- return this.invalid ? this.invalid.explanation : null;
- }
- }]);
- return Duration;
-}(Symbol.for("nodejs.util.inspect.custom"));
-
-var INVALID$1 = "Invalid Interval";
-
-// checks if the start is equal to or before the end
-function validateStartEnd(start, end) {
- if (!start || !start.isValid) {
- return Interval.invalid("missing or invalid start");
- } else if (!end || !end.isValid) {
- return Interval.invalid("missing or invalid end");
- } else if (end < start) {
- return Interval.invalid("end before start", "The end of an interval must be after its start, but you had start=" + start.toISO() + " and end=" + end.toISO());
- } else {
- return null;
- }
-}
-
-/**
- * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.
- *
- * Here is a brief overview of the most commonly used methods and getters in Interval:
- *
- * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}.
- * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.
- * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.
- * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.
- * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}
- * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.
- */
-var Interval = /*#__PURE__*/function (_Symbol$for) {
- /**
- * @private
- */
- function Interval(config) {
- /**
- * @access private
- */
- this.s = config.start;
- /**
- * @access private
- */
- this.e = config.end;
- /**
- * @access private
- */
- this.invalid = config.invalid || null;
- /**
- * @access private
- */
- this.isLuxonInterval = true;
- }
-
- /**
- * Create an invalid Interval.
- * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
- * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
- * @return {Interval}
- */
- Interval.invalid = function invalid(reason, explanation) {
- if (explanation === void 0) {
- explanation = null;
- }
- if (!reason) {
- throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
- }
- var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
- if (Settings.throwOnInvalid) {
- throw new InvalidIntervalError(invalid);
- } else {
- return new Interval({
- invalid: invalid
- });
- }
- }
-
- /**
- * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
- * @param {DateTime|Date|Object} start
- * @param {DateTime|Date|Object} end
- * @return {Interval}
- */;
- Interval.fromDateTimes = function fromDateTimes(start, end) {
- var builtStart = friendlyDateTime(start),
- builtEnd = friendlyDateTime(end);
- var validateError = validateStartEnd(builtStart, builtEnd);
- if (validateError == null) {
- return new Interval({
- start: builtStart,
- end: builtEnd
- });
- } else {
- return validateError;
- }
- }
-
- /**
- * Create an Interval from a start DateTime and a Duration to extend to.
- * @param {DateTime|Date|Object} start
- * @param {Duration|Object|number} duration - the length of the Interval.
- * @return {Interval}
- */;
- Interval.after = function after(start, duration) {
- var dur = Duration.fromDurationLike(duration),
- dt = friendlyDateTime(start);
- return Interval.fromDateTimes(dt, dt.plus(dur));
- }
-
- /**
- * Create an Interval from an end DateTime and a Duration to extend backwards to.
- * @param {DateTime|Date|Object} end
- * @param {Duration|Object|number} duration - the length of the Interval.
- * @return {Interval}
- */;
- Interval.before = function before(end, duration) {
- var dur = Duration.fromDurationLike(duration),
- dt = friendlyDateTime(end);
- return Interval.fromDateTimes(dt.minus(dur), dt);
- }
-
- /**
- * Create an Interval from an ISO 8601 string.
- * Accepts `/`, `/`, and `/` formats.
- * @param {string} text - the ISO string to parse
- * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
- * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
- * @return {Interval}
- */;
- Interval.fromISO = function fromISO(text, opts) {
- var _split = (text || "").split("/", 2),
- s = _split[0],
- e = _split[1];
- if (s && e) {
- var start, startIsValid;
- try {
- start = DateTime.fromISO(s, opts);
- startIsValid = start.isValid;
- } catch (e) {
- startIsValid = false;
- }
- var end, endIsValid;
- try {
- end = DateTime.fromISO(e, opts);
- endIsValid = end.isValid;
- } catch (e) {
- endIsValid = false;
- }
- if (startIsValid && endIsValid) {
- return Interval.fromDateTimes(start, end);
- }
- if (startIsValid) {
- var dur = Duration.fromISO(e, opts);
- if (dur.isValid) {
- return Interval.after(start, dur);
- }
- } else if (endIsValid) {
- var _dur = Duration.fromISO(s, opts);
- if (_dur.isValid) {
- return Interval.before(end, _dur);
- }
- }
- }
- return Interval.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601");
- }
-
- /**
- * Check if an object is an Interval. Works across context boundaries
- * @param {object} o
- * @return {boolean}
- */;
- Interval.isInterval = function isInterval(o) {
- return o && o.isLuxonInterval || false;
- }
-
- /**
- * Returns the start of the Interval
- * @type {DateTime}
- */;
- var _proto = Interval.prototype;
- /**
- * Returns the length of the Interval in the specified unit.
- * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
- * @return {number}
- */
- _proto.length = function length(unit) {
- if (unit === void 0) {
- unit = "milliseconds";
- }
- return this.isValid ? this.toDuration.apply(this, [unit]).get(unit) : NaN;
- }
-
- /**
- * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
- * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
- * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
- * @param {string} [unit='milliseconds'] - the unit of time to count.
- * @param {Object} opts - options
- * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime
- * @return {number}
- */;
- _proto.count = function count(unit, opts) {
- if (unit === void 0) {
- unit = "milliseconds";
- }
- if (!this.isValid) return NaN;
- var start = this.start.startOf(unit, opts);
- var end;
- if (opts != null && opts.useLocaleWeeks) {
- end = this.end.reconfigure({
- locale: start.locale
- });
- } else {
- end = this.end;
- }
- end = end.startOf(unit, opts);
- return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());
- }
-
- /**
- * Returns whether this Interval's start and end are both in the same unit of time
- * @param {string} unit - the unit of time to check sameness on
- * @return {boolean}
- */;
- _proto.hasSame = function hasSame(unit) {
- return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
- }
-
- /**
- * Return whether this Interval has the same start and end DateTimes.
- * @return {boolean}
- */;
- _proto.isEmpty = function isEmpty() {
- return this.s.valueOf() === this.e.valueOf();
- }
-
- /**
- * Return whether this Interval's start is after the specified DateTime.
- * @param {DateTime} dateTime
- * @return {boolean}
- */;
- _proto.isAfter = function isAfter(dateTime) {
- if (!this.isValid) return false;
- return this.s > dateTime;
- }
-
- /**
- * Return whether this Interval's end is before the specified DateTime.
- * @param {DateTime} dateTime
- * @return {boolean}
- */;
- _proto.isBefore = function isBefore(dateTime) {
- if (!this.isValid) return false;
- return this.e <= dateTime;
- }
-
- /**
- * Return whether this Interval contains the specified DateTime.
- * @param {DateTime} dateTime
- * @return {boolean}
- */;
- _proto.contains = function contains(dateTime) {
- if (!this.isValid) return false;
- return this.s <= dateTime && this.e > dateTime;
- }
-
- /**
- * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
- * @param {Object} values - the values to set
- * @param {DateTime} values.start - the starting DateTime
- * @param {DateTime} values.end - the ending DateTime
- * @return {Interval}
- */;
- _proto.set = function set(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- start = _ref.start,
- end = _ref.end;
- if (!this.isValid) return this;
- return Interval.fromDateTimes(start || this.s, end || this.e);
- }
-
- /**
- * Split this Interval at each of the specified DateTimes
- * @param {...DateTime} dateTimes - the unit of time to count.
- * @return {Array}
- */;
- _proto.splitAt = function splitAt() {
- var _this = this;
- if (!this.isValid) return [];
- for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) {
- dateTimes[_key] = arguments[_key];
- }
- var sorted = dateTimes.map(friendlyDateTime).filter(function (d) {
- return _this.contains(d);
- }).sort(function (a, b) {
- return a.toMillis() - b.toMillis();
- }),
- results = [];
- var s = this.s,
- i = 0;
- while (s < this.e) {
- var added = sorted[i] || this.e,
- next = +added > +this.e ? this.e : added;
- results.push(Interval.fromDateTimes(s, next));
- s = next;
- i += 1;
- }
- return results;
- }
-
- /**
- * Split this Interval into smaller Intervals, each of the specified length.
- * Left over time is grouped into a smaller interval
- * @param {Duration|Object|number} duration - The length of each resulting interval.
- * @return {Array}
- */;
- _proto.splitBy = function splitBy(duration) {
- var dur = Duration.fromDurationLike(duration);
- if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
- return [];
- }
- var s = this.s,
- idx = 1,
- next;
- var results = [];
- while (s < this.e) {
- var added = this.start.plus(dur.mapUnits(function (x) {
- return x * idx;
- }));
- next = +added > +this.e ? this.e : added;
- results.push(Interval.fromDateTimes(s, next));
- s = next;
- idx += 1;
- }
- return results;
- }
-
- /**
- * Split this Interval into the specified number of smaller intervals.
- * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
- * @return {Array}
- */;
- _proto.divideEqually = function divideEqually(numberOfParts) {
- if (!this.isValid) return [];
- return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
- }
-
- /**
- * Return whether this Interval overlaps with the specified Interval
- * @param {Interval} other
- * @return {boolean}
- */;
- _proto.overlaps = function overlaps(other) {
- return this.e > other.s && this.s < other.e;
- }
-
- /**
- * Return whether this Interval's end is adjacent to the specified Interval's start.
- * @param {Interval} other
- * @return {boolean}
- */;
- _proto.abutsStart = function abutsStart(other) {
- if (!this.isValid) return false;
- return +this.e === +other.s;
- }
-
- /**
- * Return whether this Interval's start is adjacent to the specified Interval's end.
- * @param {Interval} other
- * @return {boolean}
- */;
- _proto.abutsEnd = function abutsEnd(other) {
- if (!this.isValid) return false;
- return +other.e === +this.s;
- }
-
- /**
- * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise.
- * @param {Interval} other
- * @return {boolean}
- */;
- _proto.engulfs = function engulfs(other) {
- if (!this.isValid) return false;
- return this.s <= other.s && this.e >= other.e;
- }
-
- /**
- * Return whether this Interval has the same start and end as the specified Interval.
- * @param {Interval} other
- * @return {boolean}
- */;
- _proto.equals = function equals(other) {
- if (!this.isValid || !other.isValid) {
- return false;
- }
- return this.s.equals(other.s) && this.e.equals(other.e);
- }
-
- /**
- * Return an Interval representing the intersection of this Interval and the specified Interval.
- * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
- * Returns null if the intersection is empty, meaning, the intervals don't intersect.
- * @param {Interval} other
- * @return {Interval}
- */;
- _proto.intersection = function intersection(other) {
- if (!this.isValid) return this;
- var s = this.s > other.s ? this.s : other.s,
- e = this.e < other.e ? this.e : other.e;
- if (s >= e) {
- return null;
- } else {
- return Interval.fromDateTimes(s, e);
- }
- }
-
- /**
- * Return an Interval representing the union of this Interval and the specified Interval.
- * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
- * @param {Interval} other
- * @return {Interval}
- */;
- _proto.union = function union(other) {
- if (!this.isValid) return this;
- var s = this.s < other.s ? this.s : other.s,
- e = this.e > other.e ? this.e : other.e;
- return Interval.fromDateTimes(s, e);
- }
-
- /**
- * Merge an array of Intervals into an equivalent minimal set of Intervals.
- * Combines overlapping and adjacent Intervals.
- * The resulting array will contain the Intervals in ascending order, that is, starting with the earliest Interval
- * and ending with the latest.
- *
- * @param {Array} intervals
- * @return {Array}
- */;
- Interval.merge = function merge(intervals) {
- var _intervals$sort$reduc = intervals.sort(function (a, b) {
- return a.s - b.s;
- }).reduce(function (_ref2, item) {
- var sofar = _ref2[0],
- current = _ref2[1];
- if (!current) {
- return [sofar, item];
- } else if (current.overlaps(item) || current.abutsStart(item)) {
- return [sofar, current.union(item)];
- } else {
- return [sofar.concat([current]), item];
- }
- }, [[], null]),
- found = _intervals$sort$reduc[0],
- final = _intervals$sort$reduc[1];
- if (final) {
- found.push(final);
- }
- return found;
- }
-
- /**
- * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
- * @param {Array} intervals
- * @return {Array}
- */;
- Interval.xor = function xor(intervals) {
- var _Array$prototype;
- var start = null,
- currentCount = 0;
- var results = [],
- ends = intervals.map(function (i) {
- return [{
- time: i.s,
- type: "s"
- }, {
- time: i.e,
- type: "e"
- }];
- }),
- flattened = (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, ends),
- arr = flattened.sort(function (a, b) {
- return a.time - b.time;
- });
- for (var _iterator = _createForOfIteratorHelperLoose(arr), _step; !(_step = _iterator()).done;) {
- var i = _step.value;
- currentCount += i.type === "s" ? 1 : -1;
- if (currentCount === 1) {
- start = i.time;
- } else {
- if (start && +start !== +i.time) {
- results.push(Interval.fromDateTimes(start, i.time));
- }
- start = null;
- }
- }
- return Interval.merge(results);
- }
-
- /**
- * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
- * @param {...Interval} intervals
- * @return {Array}
- */;
- _proto.difference = function difference() {
- var _this2 = this;
- for (var _len2 = arguments.length, intervals = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- intervals[_key2] = arguments[_key2];
- }
- return Interval.xor([this].concat(intervals)).map(function (i) {
- return _this2.intersection(i);
- }).filter(function (i) {
- return i && !i.isEmpty();
- });
- }
-
- /**
- * Returns a string representation of this Interval appropriate for debugging.
- * @return {string}
- */;
- _proto.toString = function toString() {
- if (!this.isValid) return INVALID$1;
- return "[" + this.s.toISO() + " \u2013 " + this.e.toISO() + ")";
- }
-
- /**
- * Returns a string representation of this Interval appropriate for the REPL.
- * @return {string}
- */;
- _proto[_Symbol$for] = function () {
- if (this.isValid) {
- return "Interval { start: " + this.s.toISO() + ", end: " + this.e.toISO() + " }";
- } else {
- return "Interval { Invalid, reason: " + this.invalidReason + " }";
- }
- }
-
- /**
- * Returns a localized string representing this Interval. Accepts the same options as the
- * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as
- * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method
- * is browser-specific, but in general it will return an appropriate representation of the
- * Interval in the assigned locale. Defaults to the system's locale if no locale has been
- * specified.
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
- * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or
- * Intl.DateTimeFormat constructor options.
- * @param {Object} opts - Options to override the configuration of the start DateTime.
- * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022
- * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022
- * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022
- * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM
- * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p
- * @return {string}
- */;
- _proto.toLocaleString = function toLocaleString(formatOpts, opts) {
- if (formatOpts === void 0) {
- formatOpts = DATE_SHORT;
- }
- if (opts === void 0) {
- opts = {};
- }
- return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1;
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this Interval.
- * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
- * @param {Object} opts - The same options as {@link DateTime#toISO}
- * @return {string}
- */;
- _proto.toISO = function toISO(opts) {
- if (!this.isValid) return INVALID$1;
- return this.s.toISO(opts) + "/" + this.e.toISO(opts);
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of date of this Interval.
- * The time components are ignored.
- * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
- * @return {string}
- */;
- _proto.toISODate = function toISODate() {
- if (!this.isValid) return INVALID$1;
- return this.s.toISODate() + "/" + this.e.toISODate();
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of time of this Interval.
- * The date components are ignored.
- * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
- * @param {Object} opts - The same options as {@link DateTime#toISO}
- * @return {string}
- */;
- _proto.toISOTime = function toISOTime(opts) {
- if (!this.isValid) return INVALID$1;
- return this.s.toISOTime(opts) + "/" + this.e.toISOTime(opts);
- }
-
- /**
- * Returns a string representation of this Interval formatted according to the specified format
- * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible
- * formatting tool.
- * @param {string} dateFormat - The format string. This string formats the start and end time.
- * See {@link DateTime#toFormat} for details.
- * @param {Object} opts - Options.
- * @param {string} [opts.separator = ' – '] - A separator to place between the start and end
- * representations.
- * @return {string}
- */;
- _proto.toFormat = function toFormat(dateFormat, _temp2) {
- var _ref3 = _temp2 === void 0 ? {} : _temp2,
- _ref3$separator = _ref3.separator,
- separator = _ref3$separator === void 0 ? " – " : _ref3$separator;
- if (!this.isValid) return INVALID$1;
- return "" + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat);
- }
-
- /**
- * Return a Duration representing the time spanned by this interval.
- * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
- * @param {Object} opts - options that affect the creation of the Duration
- * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
- * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
- * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
- * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
- * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
- * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
- * @return {Duration}
- */;
- _proto.toDuration = function toDuration(unit, opts) {
- if (!this.isValid) {
- return Duration.invalid(this.invalidReason);
- }
- return this.e.diff(this.s, unit, opts);
- }
-
- /**
- * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
- * @param {function} mapFn
- * @return {Interval}
- * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
- * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
- */;
- _proto.mapEndpoints = function mapEndpoints(mapFn) {
- return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
- };
- _createClass(Interval, [{
- key: "start",
- get: function get() {
- return this.isValid ? this.s : null;
- }
-
- /**
- * Returns the end of the Interval. This is the first instant which is not part of the interval
- * (Interval is half-open).
- * @type {DateTime}
- */
- }, {
- key: "end",
- get: function get() {
- return this.isValid ? this.e : null;
- }
-
- /**
- * Returns the last DateTime included in the interval (since end is not part of the interval)
- * @type {DateTime}
- */
- }, {
- key: "lastDateTime",
- get: function get() {
- return this.isValid ? this.e ? this.e.minus(1) : null : null;
- }
-
- /**
- * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
- * @type {boolean}
- */
- }, {
- key: "isValid",
- get: function get() {
- return this.invalidReason === null;
- }
-
- /**
- * Returns an error code if this Interval is invalid, or null if the Interval is valid
- * @type {string}
- */
- }, {
- key: "invalidReason",
- get: function get() {
- return this.invalid ? this.invalid.reason : null;
- }
-
- /**
- * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
- * @type {string}
- */
- }, {
- key: "invalidExplanation",
- get: function get() {
- return this.invalid ? this.invalid.explanation : null;
- }
- }]);
- return Interval;
-}(Symbol.for("nodejs.util.inspect.custom"));
-
-/**
- * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.
- */
-var Info = /*#__PURE__*/function () {
- function Info() {}
- /**
- * Return whether the specified zone contains a DST.
- * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
- * @return {boolean}
- */
- Info.hasDST = function hasDST(zone) {
- if (zone === void 0) {
- zone = Settings.defaultZone;
- }
- var proto = DateTime.now().setZone(zone).set({
- month: 12
- });
- return !zone.isUniversal && proto.offset !== proto.set({
- month: 6
- }).offset;
- }
-
- /**
- * Return whether the specified zone is a valid IANA specifier.
- * @param {string} zone - Zone to check
- * @return {boolean}
- */;
- Info.isValidIANAZone = function isValidIANAZone(zone) {
- return IANAZone.isValidZone(zone);
- }
-
- /**
- * Converts the input into a {@link Zone} instance.
- *
- * * If `input` is already a Zone instance, it is returned unchanged.
- * * If `input` is a string containing a valid time zone name, a Zone instance
- * with that name is returned.
- * * If `input` is a string that doesn't refer to a known time zone, a Zone
- * instance with {@link Zone#isValid} == false is returned.
- * * If `input is a number, a Zone instance with the specified fixed offset
- * in minutes is returned.
- * * If `input` is `null` or `undefined`, the default zone is returned.
- * @param {string|Zone|number} [input] - the value to be converted
- * @return {Zone}
- */;
- Info.normalizeZone = function normalizeZone$1(input) {
- return normalizeZone(input, Settings.defaultZone);
- }
-
- /**
- * Get the weekday on which the week starts according to the given locale.
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @returns {number} the start of the week, 1 for Monday through 7 for Sunday
- */;
- Info.getStartOfWeek = function getStartOfWeek(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$locale = _ref.locale,
- locale = _ref$locale === void 0 ? null : _ref$locale,
- _ref$locObj = _ref.locObj,
- locObj = _ref$locObj === void 0 ? null : _ref$locObj;
- return (locObj || Locale.create(locale)).getStartOfWeek();
- }
-
- /**
- * Get the minimum number of days necessary in a week before it is considered part of the next year according
- * to the given locale.
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @returns {number}
- */;
- Info.getMinimumDaysInFirstWeek = function getMinimumDaysInFirstWeek(_temp2) {
- var _ref2 = _temp2 === void 0 ? {} : _temp2,
- _ref2$locale = _ref2.locale,
- locale = _ref2$locale === void 0 ? null : _ref2$locale,
- _ref2$locObj = _ref2.locObj,
- locObj = _ref2$locObj === void 0 ? null : _ref2$locObj;
- return (locObj || Locale.create(locale)).getMinDaysInFirstWeek();
- }
-
- /**
- * Get the weekdays, which are considered the weekend according to the given locale
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday
- */;
- Info.getWeekendWeekdays = function getWeekendWeekdays(_temp3) {
- var _ref3 = _temp3 === void 0 ? {} : _temp3,
- _ref3$locale = _ref3.locale,
- locale = _ref3$locale === void 0 ? null : _ref3$locale,
- _ref3$locObj = _ref3.locObj,
- locObj = _ref3$locObj === void 0 ? null : _ref3$locObj;
- // copy the array, because we cache it internally
- return (locObj || Locale.create(locale)).getWeekendDays().slice();
- }
-
- /**
- * Return an array of standalone month names.
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
- * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @param {string} [opts.numberingSystem=null] - the numbering system
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @param {string} [opts.outputCalendar='gregory'] - the calendar
- * @example Info.months()[0] //=> 'January'
- * @example Info.months('short')[0] //=> 'Jan'
- * @example Info.months('numeric')[0] //=> '1'
- * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
- * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
- * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
- * @return {Array}
- */;
- Info.months = function months(length, _temp4) {
- if (length === void 0) {
- length = "long";
- }
- var _ref4 = _temp4 === void 0 ? {} : _temp4,
- _ref4$locale = _ref4.locale,
- locale = _ref4$locale === void 0 ? null : _ref4$locale,
- _ref4$numberingSystem = _ref4.numberingSystem,
- numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem,
- _ref4$locObj = _ref4.locObj,
- locObj = _ref4$locObj === void 0 ? null : _ref4$locObj,
- _ref4$outputCalendar = _ref4.outputCalendar,
- outputCalendar = _ref4$outputCalendar === void 0 ? "gregory" : _ref4$outputCalendar;
- return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
- }
-
- /**
- * Return an array of format month names.
- * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
- * changes the string.
- * See {@link Info#months}
- * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @param {string} [opts.numberingSystem=null] - the numbering system
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @param {string} [opts.outputCalendar='gregory'] - the calendar
- * @return {Array}
- */;
- Info.monthsFormat = function monthsFormat(length, _temp5) {
- if (length === void 0) {
- length = "long";
- }
- var _ref5 = _temp5 === void 0 ? {} : _temp5,
- _ref5$locale = _ref5.locale,
- locale = _ref5$locale === void 0 ? null : _ref5$locale,
- _ref5$numberingSystem = _ref5.numberingSystem,
- numberingSystem = _ref5$numberingSystem === void 0 ? null : _ref5$numberingSystem,
- _ref5$locObj = _ref5.locObj,
- locObj = _ref5$locObj === void 0 ? null : _ref5$locObj,
- _ref5$outputCalendar = _ref5.outputCalendar,
- outputCalendar = _ref5$outputCalendar === void 0 ? "gregory" : _ref5$outputCalendar;
- return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
- }
-
- /**
- * Return an array of standalone week names.
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
- * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @param {string} [opts.numberingSystem=null] - the numbering system
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @example Info.weekdays()[0] //=> 'Monday'
- * @example Info.weekdays('short')[0] //=> 'Mon'
- * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
- * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
- * @return {Array}
- */;
- Info.weekdays = function weekdays(length, _temp6) {
- if (length === void 0) {
- length = "long";
- }
- var _ref6 = _temp6 === void 0 ? {} : _temp6,
- _ref6$locale = _ref6.locale,
- locale = _ref6$locale === void 0 ? null : _ref6$locale,
- _ref6$numberingSystem = _ref6.numberingSystem,
- numberingSystem = _ref6$numberingSystem === void 0 ? null : _ref6$numberingSystem,
- _ref6$locObj = _ref6.locObj,
- locObj = _ref6$locObj === void 0 ? null : _ref6$locObj;
- return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
- }
-
- /**
- * Return an array of format week names.
- * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
- * changes the string.
- * See {@link Info#weekdays}
- * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
- * @param {Object} opts - options
- * @param {string} [opts.locale=null] - the locale code
- * @param {string} [opts.numberingSystem=null] - the numbering system
- * @param {string} [opts.locObj=null] - an existing locale object to use
- * @return {Array}
- */;
- Info.weekdaysFormat = function weekdaysFormat(length, _temp7) {
- if (length === void 0) {
- length = "long";
- }
- var _ref7 = _temp7 === void 0 ? {} : _temp7,
- _ref7$locale = _ref7.locale,
- locale = _ref7$locale === void 0 ? null : _ref7$locale,
- _ref7$numberingSystem = _ref7.numberingSystem,
- numberingSystem = _ref7$numberingSystem === void 0 ? null : _ref7$numberingSystem,
- _ref7$locObj = _ref7.locObj,
- locObj = _ref7$locObj === void 0 ? null : _ref7$locObj;
- return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
- }
-
- /**
- * Return an array of meridiems.
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @example Info.meridiems() //=> [ 'AM', 'PM' ]
- * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
- * @return {Array}
- */;
- Info.meridiems = function meridiems(_temp8) {
- var _ref8 = _temp8 === void 0 ? {} : _temp8,
- _ref8$locale = _ref8.locale,
- locale = _ref8$locale === void 0 ? null : _ref8$locale;
- return Locale.create(locale).meridiems();
- }
-
- /**
- * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
- * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
- * @param {Object} opts - options
- * @param {string} [opts.locale] - the locale code
- * @example Info.eras() //=> [ 'BC', 'AD' ]
- * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
- * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
- * @return {Array}
- */;
- Info.eras = function eras(length, _temp9) {
- if (length === void 0) {
- length = "short";
- }
- var _ref9 = _temp9 === void 0 ? {} : _temp9,
- _ref9$locale = _ref9.locale,
- locale = _ref9$locale === void 0 ? null : _ref9$locale;
- return Locale.create(locale, null, "gregory").eras(length);
- }
-
- /**
- * Return the set of available features in this environment.
- * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
- * Keys:
- * * `relative`: whether this environment supports relative time formatting
- * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale
- * @example Info.features() //=> { relative: false, localeWeek: true }
- * @return {Object}
- */;
- Info.features = function features() {
- return {
- relative: hasRelative(),
- localeWeek: hasLocaleWeekInfo()
- };
- };
- return Info;
-}();
-
-function dayDiff(earlier, later) {
- var utcDayStart = function utcDayStart(dt) {
- return dt.toUTC(0, {
- keepLocalTime: true
- }).startOf("day").valueOf();
- },
- ms = utcDayStart(later) - utcDayStart(earlier);
- return Math.floor(Duration.fromMillis(ms).as("days"));
-}
-function highOrderDiffs(cursor, later, units) {
- var differs = [["years", function (a, b) {
- return b.year - a.year;
- }], ["quarters", function (a, b) {
- return b.quarter - a.quarter + (b.year - a.year) * 4;
- }], ["months", function (a, b) {
- return b.month - a.month + (b.year - a.year) * 12;
- }], ["weeks", function (a, b) {
- var days = dayDiff(a, b);
- return (days - days % 7) / 7;
- }], ["days", dayDiff]];
- var results = {};
- var earlier = cursor;
- var lowestOrder, highWater;
-
- /* This loop tries to diff using larger units first.
- If we overshoot, we backtrack and try the next smaller unit.
- "cursor" starts out at the earlier timestamp and moves closer and closer to "later"
- as we use smaller and smaller units.
- highWater keeps track of where we would be if we added one more of the smallest unit,
- this is used later to potentially convert any difference smaller than the smallest higher order unit
- into a fraction of that smallest higher order unit
- */
- for (var _i = 0, _differs = differs; _i < _differs.length; _i++) {
- var _differs$_i = _differs[_i],
- unit = _differs$_i[0],
- differ = _differs$_i[1];
- if (units.indexOf(unit) >= 0) {
- lowestOrder = unit;
- results[unit] = differ(cursor, later);
- highWater = earlier.plus(results);
- if (highWater > later) {
- // we overshot the end point, backtrack cursor by 1
- results[unit]--;
- cursor = earlier.plus(results);
-
- // if we are still overshooting now, we need to backtrack again
- // this happens in certain situations when diffing times in different zones,
- // because this calculation ignores time zones
- if (cursor > later) {
- // keep the "overshot by 1" around as highWater
- highWater = cursor;
- // backtrack cursor by 1
- results[unit]--;
- cursor = earlier.plus(results);
- }
- } else {
- cursor = highWater;
- }
- }
- }
- return [cursor, results, highWater, lowestOrder];
-}
-function _diff (earlier, later, units, opts) {
- var _highOrderDiffs = highOrderDiffs(earlier, later, units),
- cursor = _highOrderDiffs[0],
- results = _highOrderDiffs[1],
- highWater = _highOrderDiffs[2],
- lowestOrder = _highOrderDiffs[3];
- var remainingMillis = later - cursor;
- var lowerOrderUnits = units.filter(function (u) {
- return ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0;
- });
- if (lowerOrderUnits.length === 0) {
- if (highWater < later) {
- var _cursor$plus;
- highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[lowestOrder] = 1, _cursor$plus));
- }
- if (highWater !== cursor) {
- results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
- }
- }
- var duration = Duration.fromObject(results, opts);
- if (lowerOrderUnits.length > 0) {
- var _Duration$fromMillis;
- return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration);
- } else {
- return duration;
- }
-}
-
-var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
-function intUnit(regex, post) {
- if (post === void 0) {
- post = function post(i) {
- return i;
- };
- }
- return {
- regex: regex,
- deser: function deser(_ref) {
- var s = _ref[0];
- return post(parseDigits(s));
- }
- };
-}
-var NBSP = String.fromCharCode(160);
-var spaceOrNBSP = "[ " + NBSP + "]";
-var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
-function fixListRegex(s) {
- // make dots optional and also make them literal
- // make space and non breakable space characters interchangeable
- return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
-}
-function stripInsensitivities(s) {
- return s.replace(/\./g, "") // ignore dots that were made optional
- .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp
- .toLowerCase();
-}
-function oneOf(strings, startIndex) {
- if (strings === null) {
- return null;
- } else {
- return {
- regex: RegExp(strings.map(fixListRegex).join("|")),
- deser: function deser(_ref2) {
- var s = _ref2[0];
- return strings.findIndex(function (i) {
- return stripInsensitivities(s) === stripInsensitivities(i);
- }) + startIndex;
- }
- };
- }
-}
-function offset(regex, groups) {
- return {
- regex: regex,
- deser: function deser(_ref3) {
- var h = _ref3[1],
- m = _ref3[2];
- return signedOffset(h, m);
- },
- groups: groups
- };
-}
-function simple(regex) {
- return {
- regex: regex,
- deser: function deser(_ref4) {
- var s = _ref4[0];
- return s;
- }
- };
-}
-function escapeToken(value) {
- return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
-}
-
-/**
- * @param token
- * @param {Locale} loc
- */
-function unitForToken(token, loc) {
- var one = digitRegex(loc),
- two = digitRegex(loc, "{2}"),
- three = digitRegex(loc, "{3}"),
- four = digitRegex(loc, "{4}"),
- six = digitRegex(loc, "{6}"),
- oneOrTwo = digitRegex(loc, "{1,2}"),
- oneToThree = digitRegex(loc, "{1,3}"),
- oneToSix = digitRegex(loc, "{1,6}"),
- oneToNine = digitRegex(loc, "{1,9}"),
- twoToFour = digitRegex(loc, "{2,4}"),
- fourToSix = digitRegex(loc, "{4,6}"),
- literal = function literal(t) {
- return {
- regex: RegExp(escapeToken(t.val)),
- deser: function deser(_ref5) {
- var s = _ref5[0];
- return s;
- },
- literal: true
- };
- },
- unitate = function unitate(t) {
- if (token.literal) {
- return literal(t);
- }
- switch (t.val) {
- // era
- case "G":
- return oneOf(loc.eras("short"), 0);
- case "GG":
- return oneOf(loc.eras("long"), 0);
- // years
- case "y":
- return intUnit(oneToSix);
- case "yy":
- return intUnit(twoToFour, untruncateYear);
- case "yyyy":
- return intUnit(four);
- case "yyyyy":
- return intUnit(fourToSix);
- case "yyyyyy":
- return intUnit(six);
- // months
- case "M":
- return intUnit(oneOrTwo);
- case "MM":
- return intUnit(two);
- case "MMM":
- return oneOf(loc.months("short", true), 1);
- case "MMMM":
- return oneOf(loc.months("long", true), 1);
- case "L":
- return intUnit(oneOrTwo);
- case "LL":
- return intUnit(two);
- case "LLL":
- return oneOf(loc.months("short", false), 1);
- case "LLLL":
- return oneOf(loc.months("long", false), 1);
- // dates
- case "d":
- return intUnit(oneOrTwo);
- case "dd":
- return intUnit(two);
- // ordinals
- case "o":
- return intUnit(oneToThree);
- case "ooo":
- return intUnit(three);
- // time
- case "HH":
- return intUnit(two);
- case "H":
- return intUnit(oneOrTwo);
- case "hh":
- return intUnit(two);
- case "h":
- return intUnit(oneOrTwo);
- case "mm":
- return intUnit(two);
- case "m":
- return intUnit(oneOrTwo);
- case "q":
- return intUnit(oneOrTwo);
- case "qq":
- return intUnit(two);
- case "s":
- return intUnit(oneOrTwo);
- case "ss":
- return intUnit(two);
- case "S":
- return intUnit(oneToThree);
- case "SSS":
- return intUnit(three);
- case "u":
- return simple(oneToNine);
- case "uu":
- return simple(oneOrTwo);
- case "uuu":
- return intUnit(one);
- // meridiem
- case "a":
- return oneOf(loc.meridiems(), 0);
- // weekYear (k)
- case "kkkk":
- return intUnit(four);
- case "kk":
- return intUnit(twoToFour, untruncateYear);
- // weekNumber (W)
- case "W":
- return intUnit(oneOrTwo);
- case "WW":
- return intUnit(two);
- // weekdays
- case "E":
- case "c":
- return intUnit(one);
- case "EEE":
- return oneOf(loc.weekdays("short", false), 1);
- case "EEEE":
- return oneOf(loc.weekdays("long", false), 1);
- case "ccc":
- return oneOf(loc.weekdays("short", true), 1);
- case "cccc":
- return oneOf(loc.weekdays("long", true), 1);
- // offset/zone
- case "Z":
- case "ZZ":
- return offset(new RegExp("([+-]" + oneOrTwo.source + ")(?::(" + two.source + "))?"), 2);
- case "ZZZ":
- return offset(new RegExp("([+-]" + oneOrTwo.source + ")(" + two.source + ")?"), 2);
- // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
- // because we don't have any way to figure out what they are
- case "z":
- return simple(/[a-z_+-/]{1,256}?/i);
- // this special-case "token" represents a place where a macro-token expanded into a white-space literal
- // in this case we accept any non-newline white-space
- case " ":
- return simple(/[^\S\n\r]/);
- default:
- return literal(t);
- }
- };
- var unit = unitate(token) || {
- invalidReason: MISSING_FTP
- };
- unit.token = token;
- return unit;
-}
-var partTypeStyleToTokenVal = {
- year: {
- "2-digit": "yy",
- numeric: "yyyyy"
- },
- month: {
- numeric: "M",
- "2-digit": "MM",
- short: "MMM",
- long: "MMMM"
- },
- day: {
- numeric: "d",
- "2-digit": "dd"
- },
- weekday: {
- short: "EEE",
- long: "EEEE"
- },
- dayperiod: "a",
- dayPeriod: "a",
- hour12: {
- numeric: "h",
- "2-digit": "hh"
- },
- hour24: {
- numeric: "H",
- "2-digit": "HH"
- },
- minute: {
- numeric: "m",
- "2-digit": "mm"
- },
- second: {
- numeric: "s",
- "2-digit": "ss"
- },
- timeZoneName: {
- long: "ZZZZZ",
- short: "ZZZ"
- }
-};
-function tokenForPart(part, formatOpts, resolvedOpts) {
- var type = part.type,
- value = part.value;
- if (type === "literal") {
- var isSpace = /^\s+$/.test(value);
- return {
- literal: !isSpace,
- val: isSpace ? " " : value
- };
- }
- var style = formatOpts[type];
-
- // The user might have explicitly specified hour12 or hourCycle
- // if so, respect their decision
- // if not, refer back to the resolvedOpts, which are based on the locale
- var actualType = type;
- if (type === "hour") {
- if (formatOpts.hour12 != null) {
- actualType = formatOpts.hour12 ? "hour12" : "hour24";
- } else if (formatOpts.hourCycle != null) {
- if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") {
- actualType = "hour12";
- } else {
- actualType = "hour24";
- }
- } else {
- // tokens only differentiate between 24 hours or not,
- // so we do not need to check hourCycle here, which is less supported anyways
- actualType = resolvedOpts.hour12 ? "hour12" : "hour24";
- }
- }
- var val = partTypeStyleToTokenVal[actualType];
- if (typeof val === "object") {
- val = val[style];
- }
- if (val) {
- return {
- literal: false,
- val: val
- };
- }
- return undefined;
-}
-function buildRegex(units) {
- var re = units.map(function (u) {
- return u.regex;
- }).reduce(function (f, r) {
- return f + "(" + r.source + ")";
- }, "");
- return ["^" + re + "$", units];
-}
-function match(input, regex, handlers) {
- var matches = input.match(regex);
- if (matches) {
- var all = {};
- var matchIndex = 1;
- for (var i in handlers) {
- if (hasOwnProperty(handlers, i)) {
- var h = handlers[i],
- groups = h.groups ? h.groups + 1 : 1;
- if (!h.literal && h.token) {
- all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
- }
- matchIndex += groups;
- }
- }
- return [matches, all];
- } else {
- return [matches, {}];
- }
-}
-function dateTimeFromMatches(matches) {
- var toField = function toField(token) {
- switch (token) {
- case "S":
- return "millisecond";
- case "s":
- return "second";
- case "m":
- return "minute";
- case "h":
- case "H":
- return "hour";
- case "d":
- return "day";
- case "o":
- return "ordinal";
- case "L":
- case "M":
- return "month";
- case "y":
- return "year";
- case "E":
- case "c":
- return "weekday";
- case "W":
- return "weekNumber";
- case "k":
- return "weekYear";
- case "q":
- return "quarter";
- default:
- return null;
- }
- };
- var zone = null;
- var specificOffset;
- if (!isUndefined(matches.z)) {
- zone = IANAZone.create(matches.z);
- }
- if (!isUndefined(matches.Z)) {
- if (!zone) {
- zone = new FixedOffsetZone(matches.Z);
- }
- specificOffset = matches.Z;
- }
- if (!isUndefined(matches.q)) {
- matches.M = (matches.q - 1) * 3 + 1;
- }
- if (!isUndefined(matches.h)) {
- if (matches.h < 12 && matches.a === 1) {
- matches.h += 12;
- } else if (matches.h === 12 && matches.a === 0) {
- matches.h = 0;
- }
- }
- if (matches.G === 0 && matches.y) {
- matches.y = -matches.y;
- }
- if (!isUndefined(matches.u)) {
- matches.S = parseMillis(matches.u);
- }
- var vals = Object.keys(matches).reduce(function (r, k) {
- var f = toField(k);
- if (f) {
- r[f] = matches[k];
- }
- return r;
- }, {});
- return [vals, zone, specificOffset];
-}
-var dummyDateTimeCache = null;
-function getDummyDateTime() {
- if (!dummyDateTimeCache) {
- dummyDateTimeCache = DateTime.fromMillis(1555555555555);
- }
- return dummyDateTimeCache;
-}
-function maybeExpandMacroToken(token, locale) {
- if (token.literal) {
- return token;
- }
- var formatOpts = Formatter.macroTokenToFormatOpts(token.val);
- var tokens = formatOptsToTokens(formatOpts, locale);
- if (tokens == null || tokens.includes(undefined)) {
- return token;
- }
- return tokens;
-}
-function expandMacroTokens(tokens, locale) {
- var _Array$prototype;
- return (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, tokens.map(function (t) {
- return maybeExpandMacroToken(t, locale);
- }));
-}
-
-/**
- * @private
- */
-
-var TokenParser = /*#__PURE__*/function () {
- function TokenParser(locale, format) {
- this.locale = locale;
- this.format = format;
- this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale);
- this.units = this.tokens.map(function (t) {
- return unitForToken(t, locale);
- });
- this.disqualifyingUnit = this.units.find(function (t) {
- return t.invalidReason;
- });
- if (!this.disqualifyingUnit) {
- var _buildRegex = buildRegex(this.units),
- regexString = _buildRegex[0],
- handlers = _buildRegex[1];
- this.regex = RegExp(regexString, "i");
- this.handlers = handlers;
- }
- }
- var _proto = TokenParser.prototype;
- _proto.explainFromTokens = function explainFromTokens(input) {
- if (!this.isValid) {
- return {
- input: input,
- tokens: this.tokens,
- invalidReason: this.invalidReason
- };
- } else {
- var _match = match(input, this.regex, this.handlers),
- rawMatches = _match[0],
- matches = _match[1],
- _ref6 = matches ? dateTimeFromMatches(matches) : [null, null, undefined],
- result = _ref6[0],
- zone = _ref6[1],
- specificOffset = _ref6[2];
- if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
- throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");
- }
- return {
- input: input,
- tokens: this.tokens,
- regex: this.regex,
- rawMatches: rawMatches,
- matches: matches,
- result: result,
- zone: zone,
- specificOffset: specificOffset
- };
- }
- };
- _createClass(TokenParser, [{
- key: "isValid",
- get: function get() {
- return !this.disqualifyingUnit;
- }
- }, {
- key: "invalidReason",
- get: function get() {
- return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null;
- }
- }]);
- return TokenParser;
-}();
-function explainFromTokens(locale, input, format) {
- var parser = new TokenParser(locale, format);
- return parser.explainFromTokens(input);
-}
-function parseFromTokens(locale, input, format) {
- var _explainFromTokens = explainFromTokens(locale, input, format),
- result = _explainFromTokens.result,
- zone = _explainFromTokens.zone,
- specificOffset = _explainFromTokens.specificOffset,
- invalidReason = _explainFromTokens.invalidReason;
- return [result, zone, specificOffset, invalidReason];
-}
-function formatOptsToTokens(formatOpts, locale) {
- if (!formatOpts) {
- return null;
- }
- var formatter = Formatter.create(locale, formatOpts);
- var df = formatter.dtFormatter(getDummyDateTime());
- var parts = df.formatToParts();
- var resolvedOpts = df.resolvedOptions();
- return parts.map(function (p) {
- return tokenForPart(p, formatOpts, resolvedOpts);
- });
-}
-
-var INVALID = "Invalid DateTime";
-var MAX_DATE = 8.64e15;
-function unsupportedZone(zone) {
- return new Invalid("unsupported zone", "the zone \"" + zone.name + "\" is not supported");
-}
-
-// we cache week data on the DT object and this intermediates the cache
-/**
- * @param {DateTime} dt
- */
-function possiblyCachedWeekData(dt) {
- if (dt.weekData === null) {
- dt.weekData = gregorianToWeek(dt.c);
- }
- return dt.weekData;
-}
-
-/**
- * @param {DateTime} dt
- */
-function possiblyCachedLocalWeekData(dt) {
- if (dt.localWeekData === null) {
- dt.localWeekData = gregorianToWeek(dt.c, dt.loc.getMinDaysInFirstWeek(), dt.loc.getStartOfWeek());
- }
- return dt.localWeekData;
-}
-
-// clone really means, "make a new object with these modifications". all "setters" really use this
-// to create a new object while only changing some of the properties
-function clone(inst, alts) {
- var current = {
- ts: inst.ts,
- zone: inst.zone,
- c: inst.c,
- o: inst.o,
- loc: inst.loc,
- invalid: inst.invalid
- };
- return new DateTime(_extends({}, current, alts, {
- old: current
- }));
-}
-
-// find the right offset a given local time. The o input is our guess, which determines which
-// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
-function fixOffset(localTS, o, tz) {
- // Our UTC time is just a guess because our offset is just a guess
- var utcGuess = localTS - o * 60 * 1000;
-
- // Test whether the zone matches the offset for this ts
- var o2 = tz.offset(utcGuess);
-
- // If so, offset didn't change and we're done
- if (o === o2) {
- return [utcGuess, o];
- }
-
- // If not, change the ts by the difference in the offset
- utcGuess -= (o2 - o) * 60 * 1000;
-
- // If that gives us the local time we want, we're done
- var o3 = tz.offset(utcGuess);
- if (o2 === o3) {
- return [utcGuess, o2];
- }
-
- // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
- return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
-}
-
-// convert an epoch timestamp into a calendar object with the given offset
-function tsToObj(ts, offset) {
- ts += offset * 60 * 1000;
- var d = new Date(ts);
- return {
- year: d.getUTCFullYear(),
- month: d.getUTCMonth() + 1,
- day: d.getUTCDate(),
- hour: d.getUTCHours(),
- minute: d.getUTCMinutes(),
- second: d.getUTCSeconds(),
- millisecond: d.getUTCMilliseconds()
- };
-}
-
-// convert a calendar object to a epoch timestamp
-function objToTS(obj, offset, zone) {
- return fixOffset(objToLocalTS(obj), offset, zone);
-}
-
-// create a new DT instance by adding a duration, adjusting for DSTs
-function adjustTime(inst, dur) {
- var oPre = inst.o,
- year = inst.c.year + Math.trunc(dur.years),
- month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,
- c = _extends({}, inst.c, {
- year: year,
- month: month,
- day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
- }),
- millisToAdd = Duration.fromObject({
- years: dur.years - Math.trunc(dur.years),
- quarters: dur.quarters - Math.trunc(dur.quarters),
- months: dur.months - Math.trunc(dur.months),
- weeks: dur.weeks - Math.trunc(dur.weeks),
- days: dur.days - Math.trunc(dur.days),
- hours: dur.hours,
- minutes: dur.minutes,
- seconds: dur.seconds,
- milliseconds: dur.milliseconds
- }).as("milliseconds"),
- localTS = objToLocalTS(c);
- var _fixOffset = fixOffset(localTS, oPre, inst.zone),
- ts = _fixOffset[0],
- o = _fixOffset[1];
- if (millisToAdd !== 0) {
- ts += millisToAdd;
- // that could have changed the offset by going over a DST, but we want to keep the ts the same
- o = inst.zone.offset(ts);
- }
- return {
- ts: ts,
- o: o
- };
-}
-
-// helper useful in turning the results of parsing into real dates
-// by handling the zone options
-function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {
- var setZone = opts.setZone,
- zone = opts.zone;
- if (parsed && Object.keys(parsed).length !== 0 || parsedZone) {
- var interpretationZone = parsedZone || zone,
- inst = DateTime.fromObject(parsed, _extends({}, opts, {
- zone: interpretationZone,
- specificOffset: specificOffset
- }));
- return setZone ? inst : inst.setZone(zone);
- } else {
- return DateTime.invalid(new Invalid("unparsable", "the input \"" + text + "\" can't be parsed as " + format));
- }
-}
-
-// if you want to output a technical format (e.g. RFC 2822), this helper
-// helps handle the details
-function toTechFormat(dt, format, allowZ) {
- if (allowZ === void 0) {
- allowZ = true;
- }
- return dt.isValid ? Formatter.create(Locale.create("en-US"), {
- allowZ: allowZ,
- forceSimple: true
- }).formatDateTimeFromString(dt, format) : null;
-}
-function _toISODate(o, extended, precision) {
- var longFormat = o.c.year > 9999 || o.c.year < 0;
- var c = "";
- if (longFormat && o.c.year >= 0) c += "+";
- c += padStart(o.c.year, longFormat ? 6 : 4);
- if (precision === "year") return c;
- if (extended) {
- c += "-";
- c += padStart(o.c.month);
- if (precision === "month") return c;
- c += "-";
- } else {
- c += padStart(o.c.month);
- if (precision === "month") return c;
- }
- c += padStart(o.c.day);
- return c;
-}
-function _toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision) {
- var showSeconds = !suppressSeconds || o.c.millisecond !== 0 || o.c.second !== 0,
- c = "";
- switch (precision) {
- case "day":
- case "month":
- case "year":
- break;
- default:
- c += padStart(o.c.hour);
- if (precision === "hour") break;
- if (extended) {
- c += ":";
- c += padStart(o.c.minute);
- if (precision === "minute") break;
- if (showSeconds) {
- c += ":";
- c += padStart(o.c.second);
- }
- } else {
- c += padStart(o.c.minute);
- if (precision === "minute") break;
- if (showSeconds) {
- c += padStart(o.c.second);
- }
- }
- if (precision === "second") break;
- if (showSeconds && (!suppressMilliseconds || o.c.millisecond !== 0)) {
- c += ".";
- c += padStart(o.c.millisecond, 3);
- }
- }
- if (includeOffset) {
- if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
- c += "Z";
- } else if (o.o < 0) {
- c += "-";
- c += padStart(Math.trunc(-o.o / 60));
- c += ":";
- c += padStart(Math.trunc(-o.o % 60));
- } else {
- c += "+";
- c += padStart(Math.trunc(o.o / 60));
- c += ":";
- c += padStart(Math.trunc(o.o % 60));
- }
- }
- if (extendedZone) {
- c += "[" + o.zone.ianaName + "]";
- }
- return c;
-}
-
-// defaults for unspecified units in the supported calendars
-var defaultUnitValues = {
- month: 1,
- day: 1,
- hour: 0,
- minute: 0,
- second: 0,
- millisecond: 0
- },
- defaultWeekUnitValues = {
- weekNumber: 1,
- weekday: 1,
- hour: 0,
- minute: 0,
- second: 0,
- millisecond: 0
- },
- defaultOrdinalUnitValues = {
- ordinal: 1,
- hour: 0,
- minute: 0,
- second: 0,
- millisecond: 0
- };
-
-// Units in the supported calendars, sorted by bigness
-var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"],
- orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"],
- orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
-
-// standardize case and plurality in units
-function normalizeUnit(unit) {
- var normalized = {
- year: "year",
- years: "year",
- month: "month",
- months: "month",
- day: "day",
- days: "day",
- hour: "hour",
- hours: "hour",
- minute: "minute",
- minutes: "minute",
- quarter: "quarter",
- quarters: "quarter",
- second: "second",
- seconds: "second",
- millisecond: "millisecond",
- milliseconds: "millisecond",
- weekday: "weekday",
- weekdays: "weekday",
- weeknumber: "weekNumber",
- weeksnumber: "weekNumber",
- weeknumbers: "weekNumber",
- weekyear: "weekYear",
- weekyears: "weekYear",
- ordinal: "ordinal"
- }[unit.toLowerCase()];
- if (!normalized) throw new InvalidUnitError(unit);
- return normalized;
-}
-function normalizeUnitWithLocalWeeks(unit) {
- switch (unit.toLowerCase()) {
- case "localweekday":
- case "localweekdays":
- return "localWeekday";
- case "localweeknumber":
- case "localweeknumbers":
- return "localWeekNumber";
- case "localweekyear":
- case "localweekyears":
- return "localWeekYear";
- default:
- return normalizeUnit(unit);
- }
-}
-
-// cache offsets for zones based on the current timestamp when this function is
-// first called. When we are handling a datetime from components like (year,
-// month, day, hour) in a time zone, we need a guess about what the timezone
-// offset is so that we can convert into a UTC timestamp. One way is to find the
-// offset of now in the zone. The actual date may have a different offset (for
-// example, if we handle a date in June while we're in December in a zone that
-// observes DST), but we can check and adjust that.
-//
-// When handling many dates, calculating the offset for now every time is
-// expensive. It's just a guess, so we can cache the offset to use even if we
-// are right on a time change boundary (we'll just correct in the other
-// direction). Using a timestamp from first read is a slight optimization for
-// handling dates close to the current date, since those dates will usually be
-// in the same offset (we could set the timestamp statically, instead). We use a
-// single timestamp for all zones to make things a bit more predictable.
-//
-// This is safe for quickDT (used by local() and utc()) because we don't fill in
-// higher-order units from tsNow (as we do in fromObject, this requires that
-// offset is calculated from tsNow).
-/**
- * @param {Zone} zone
- * @return {number}
- */
-function guessOffsetForZone(zone) {
- if (zoneOffsetTs === undefined) {
- zoneOffsetTs = Settings.now();
- }
-
- // Do not cache anything but IANA zones, because it is not safe to do so.
- // Guessing an offset which is not present in the zone can cause wrong results from fixOffset
- if (zone.type !== "iana") {
- return zone.offset(zoneOffsetTs);
- }
- var zoneName = zone.name;
- var offsetGuess = zoneOffsetGuessCache.get(zoneName);
- if (offsetGuess === undefined) {
- offsetGuess = zone.offset(zoneOffsetTs);
- zoneOffsetGuessCache.set(zoneName, offsetGuess);
- }
- return offsetGuess;
-}
-
-// this is a dumbed down version of fromObject() that runs about 60% faster
-// but doesn't do any validation, makes a bunch of assumptions about what units
-// are present, and so on.
-function quickDT(obj, opts) {
- var zone = normalizeZone(opts.zone, Settings.defaultZone);
- if (!zone.isValid) {
- return DateTime.invalid(unsupportedZone(zone));
- }
- var loc = Locale.fromObject(opts);
- var ts, o;
-
- // assume we have the higher-order units
- if (!isUndefined(obj.year)) {
- for (var _i = 0, _orderedUnits = orderedUnits; _i < _orderedUnits.length; _i++) {
- var u = _orderedUnits[_i];
- if (isUndefined(obj[u])) {
- obj[u] = defaultUnitValues[u];
- }
- }
- var invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
- if (invalid) {
- return DateTime.invalid(invalid);
- }
- var offsetProvis = guessOffsetForZone(zone);
- var _objToTS = objToTS(obj, offsetProvis, zone);
- ts = _objToTS[0];
- o = _objToTS[1];
- } else {
- ts = Settings.now();
- }
- return new DateTime({
- ts: ts,
- zone: zone,
- loc: loc,
- o: o
- });
-}
-function diffRelative(start, end, opts) {
- var round = isUndefined(opts.round) ? true : opts.round,
- rounding = isUndefined(opts.rounding) ? "trunc" : opts.rounding,
- format = function format(c, unit) {
- c = roundTo(c, round || opts.calendary ? 0 : 2, opts.calendary ? "round" : rounding);
- var formatter = end.loc.clone(opts).relFormatter(opts);
- return formatter.format(c, unit);
- },
- differ = function differ(unit) {
- if (opts.calendary) {
- if (!end.hasSame(start, unit)) {
- return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
- } else return 0;
- } else {
- return end.diff(start, unit).get(unit);
- }
- };
- if (opts.unit) {
- return format(differ(opts.unit), opts.unit);
- }
- for (var _iterator = _createForOfIteratorHelperLoose(opts.units), _step; !(_step = _iterator()).done;) {
- var unit = _step.value;
- var count = differ(unit);
- if (Math.abs(count) >= 1) {
- return format(count, unit);
- }
- }
- return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
-}
-function lastOpts(argList) {
- var opts = {},
- args;
- if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
- opts = argList[argList.length - 1];
- args = Array.from(argList).slice(0, argList.length - 1);
- } else {
- args = Array.from(argList);
- }
- return [opts, args];
-}
-
-/**
- * Timestamp to use for cached zone offset guesses (exposed for test)
- */
-var zoneOffsetTs;
-/**
- * Cache for zone offset guesses (exposed for test).
- *
- * This optimizes quickDT via guessOffsetForZone to avoid repeated calls of
- * zone.offset().
- */
-var zoneOffsetGuessCache = new Map();
-
-/**
- * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
- *
- * A DateTime comprises of:
- * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
- * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
- * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
- *
- * Here is a brief overview of the most commonly used functionality it provides:
- *
- * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.
- * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},
- * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.
- * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.
- * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.
- * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.
- * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.
- *
- * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
- */
-var DateTime = /*#__PURE__*/function (_Symbol$for) {
- /**
- * @access private
- */
- function DateTime(config) {
- var zone = config.zone || Settings.defaultZone;
- var invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
- /**
- * @access private
- */
- this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
- var c = null,
- o = null;
- if (!invalid) {
- var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
- if (unchanged) {
- var _ref = [config.old.c, config.old.o];
- c = _ref[0];
- o = _ref[1];
- } else {
- // If an offset has been passed and we have not been called from
- // clone(), we can trust it and avoid the offset calculation.
- var ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);
- c = tsToObj(this.ts, ot);
- invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
- c = invalid ? null : c;
- o = invalid ? null : ot;
- }
- }
-
- /**
- * @access private
- */
- this._zone = zone;
- /**
- * @access private
- */
- this.loc = config.loc || Locale.create();
- /**
- * @access private
- */
- this.invalid = invalid;
- /**
- * @access private
- */
- this.weekData = null;
- /**
- * @access private
- */
- this.localWeekData = null;
- /**
- * @access private
- */
- this.c = c;
- /**
- * @access private
- */
- this.o = o;
- /**
- * @access private
- */
- this.isLuxonDateTime = true;
- }
-
- // CONSTRUCT
-
- /**
- * Create a DateTime for the current instant, in the system's time zone.
- *
- * Use Settings to override these default values if needed.
- * @example DateTime.now().toISO() //~> now in the ISO format
- * @return {DateTime}
- */
- DateTime.now = function now() {
- return new DateTime({});
- }
-
- /**
- * Create a local DateTime
- * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
- * @param {number} [month=1] - The month, 1-indexed
- * @param {number} [day=1] - The day of the month, 1-indexed
- * @param {number} [hour=0] - The hour of the day, in 24-hour time
- * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
- * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
- * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
- * @example DateTime.local() //~> now
- * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time
- * @example DateTime.local(2017) //~> 2017-01-01T00:00:00
- * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
- * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale
- * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
- * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC
- * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
- * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
- * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
- * @return {DateTime}
- */;
- DateTime.local = function local() {
- var _lastOpts = lastOpts(arguments),
- opts = _lastOpts[0],
- args = _lastOpts[1],
- year = args[0],
- month = args[1],
- day = args[2],
- hour = args[3],
- minute = args[4],
- second = args[5],
- millisecond = args[6];
- return quickDT({
- year: year,
- month: month,
- day: day,
- hour: hour,
- minute: minute,
- second: second,
- millisecond: millisecond
- }, opts);
- }
-
- /**
- * Create a DateTime in UTC
- * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
- * @param {number} [month=1] - The month, 1-indexed
- * @param {number} [day=1] - The day of the month
- * @param {number} [hour=0] - The hour of the day, in 24-hour time
- * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
- * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
- * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
- * @param {Object} options - configuration options for the DateTime
- * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
- * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
- * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
- * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance
- * @example DateTime.utc() //~> now
- * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
- * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
- * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
- * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
- * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
- * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale
- * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
- * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
- * @return {DateTime}
- */;
- DateTime.utc = function utc() {
- var _lastOpts2 = lastOpts(arguments),
- opts = _lastOpts2[0],
- args = _lastOpts2[1],
- year = args[0],
- month = args[1],
- day = args[2],
- hour = args[3],
- minute = args[4],
- second = args[5],
- millisecond = args[6];
- opts.zone = FixedOffsetZone.utcInstance;
- return quickDT({
- year: year,
- month: month,
- day: day,
- hour: hour,
- minute: minute,
- second: second,
- millisecond: millisecond
- }, opts);
- }
-
- /**
- * Create a DateTime from a JavaScript Date object. Uses the default zone.
- * @param {Date} date - a JavaScript Date object
- * @param {Object} options - configuration options for the DateTime
- * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
- * @return {DateTime}
- */;
- DateTime.fromJSDate = function fromJSDate(date, options) {
- if (options === void 0) {
- options = {};
- }
- var ts = isDate(date) ? date.valueOf() : NaN;
- if (Number.isNaN(ts)) {
- return DateTime.invalid("invalid input");
- }
- var zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
- if (!zoneToUse.isValid) {
- return DateTime.invalid(unsupportedZone(zoneToUse));
- }
- return new DateTime({
- ts: ts,
- zone: zoneToUse,
- loc: Locale.fromObject(options)
- });
- }
-
- /**
- * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
- * @param {number} milliseconds - a number of milliseconds since 1970 UTC
- * @param {Object} options - configuration options for the DateTime
- * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
- * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
- * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
- * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
- * @return {DateTime}
- */;
- DateTime.fromMillis = function fromMillis(milliseconds, options) {
- if (options === void 0) {
- options = {};
- }
- if (!isNumber(milliseconds)) {
- throw new InvalidArgumentError("fromMillis requires a numerical input, but received a " + typeof milliseconds + " with value " + milliseconds);
- } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
- // this isn't perfect because we can still end up out of range because of additional shifting, but it's a start
- return DateTime.invalid("Timestamp out of range");
- } else {
- return new DateTime({
- ts: milliseconds,
- zone: normalizeZone(options.zone, Settings.defaultZone),
- loc: Locale.fromObject(options)
- });
- }
- }
-
- /**
- * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
- * @param {number} seconds - a number of seconds since 1970 UTC
- * @param {Object} options - configuration options for the DateTime
- * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
- * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
- * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
- * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
- * @return {DateTime}
- */;
- DateTime.fromSeconds = function fromSeconds(seconds, options) {
- if (options === void 0) {
- options = {};
- }
- if (!isNumber(seconds)) {
- throw new InvalidArgumentError("fromSeconds requires a numerical input");
- } else {
- return new DateTime({
- ts: seconds * 1000,
- zone: normalizeZone(options.zone, Settings.defaultZone),
- loc: Locale.fromObject(options)
- });
- }
- }
-
- /**
- * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
- * @param {Object} obj - the object to create the DateTime from
- * @param {number} obj.year - a year, such as 1987
- * @param {number} obj.month - a month, 1-12
- * @param {number} obj.day - a day of the month, 1-31, depending on the month
- * @param {number} obj.ordinal - day of the year, 1-365 or 366
- * @param {number} obj.weekYear - an ISO week year
- * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
- * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
- * @param {number} obj.localWeekYear - a week year, according to the locale
- * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale
- * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale
- * @param {number} obj.hour - hour of the day, 0-23
- * @param {number} obj.minute - minute of the hour, 0-59
- * @param {number} obj.second - second of the minute, 0-59
- * @param {number} obj.millisecond - millisecond of the second, 0-999
- * @param {Object} opts - options for creating this DateTime
- * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
- * @param {string} [opts.locale='system\'s locale'] - a locale to set on the resulting DateTime instance
- * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
- * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
- * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
- * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
- * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
- * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
- * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
- * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
- * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
- * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26'
- * @return {DateTime}
- */;
- DateTime.fromObject = function fromObject(obj, opts) {
- if (opts === void 0) {
- opts = {};
- }
- obj = obj || {};
- var zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
- if (!zoneToUse.isValid) {
- return DateTime.invalid(unsupportedZone(zoneToUse));
- }
- var loc = Locale.fromObject(opts);
- var normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);
- var _usesLocalWeekValues = usesLocalWeekValues(normalized, loc),
- minDaysInFirstWeek = _usesLocalWeekValues.minDaysInFirstWeek,
- startOfWeek = _usesLocalWeekValues.startOfWeek;
- var tsNow = Settings.now(),
- offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow),
- containsOrdinal = !isUndefined(normalized.ordinal),
- containsGregorYear = !isUndefined(normalized.year),
- containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
- containsGregor = containsGregorYear || containsGregorMD,
- definiteWeekDef = normalized.weekYear || normalized.weekNumber;
-
- // cases:
- // just a weekday -> this week's instance of that weekday, no worries
- // (gregorian data or ordinal) + (weekYear or weekNumber) -> error
- // (gregorian month or day) + ordinal -> error
- // otherwise just use weeks or ordinals or gregorian, depending on what's specified
-
- if ((containsGregor || containsOrdinal) && definiteWeekDef) {
- throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
- }
- if (containsGregorMD && containsOrdinal) {
- throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
- }
- var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
-
- // configure ourselves to deal with gregorian dates or week stuff
- var units,
- defaultValues,
- objNow = tsToObj(tsNow, offsetProvis);
- if (useWeekData) {
- units = orderedWeekUnits;
- defaultValues = defaultWeekUnitValues;
- objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);
- } else if (containsOrdinal) {
- units = orderedOrdinalUnits;
- defaultValues = defaultOrdinalUnitValues;
- objNow = gregorianToOrdinal(objNow);
- } else {
- units = orderedUnits;
- defaultValues = defaultUnitValues;
- }
-
- // set default values for missing stuff
- var foundFirst = false;
- for (var _iterator2 = _createForOfIteratorHelperLoose(units), _step2; !(_step2 = _iterator2()).done;) {
- var u = _step2.value;
- var v = normalized[u];
- if (!isUndefined(v)) {
- foundFirst = true;
- } else if (foundFirst) {
- normalized[u] = defaultValues[u];
- } else {
- normalized[u] = objNow[u];
- }
- }
-
- // make sure the values we have are in range
- var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized),
- invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
- if (invalid) {
- return DateTime.invalid(invalid);
- }
-
- // compute the actual time
- var gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized,
- _objToTS2 = objToTS(gregorian, offsetProvis, zoneToUse),
- tsFinal = _objToTS2[0],
- offsetFinal = _objToTS2[1],
- inst = new DateTime({
- ts: tsFinal,
- zone: zoneToUse,
- o: offsetFinal,
- loc: loc
- });
-
- // gregorian data + weekday serves only to validate
- if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
- return DateTime.invalid("mismatched weekday", "you can't specify both a weekday of " + normalized.weekday + " and a date of " + inst.toISO());
- }
- if (!inst.isValid) {
- return DateTime.invalid(inst.invalid);
- }
- return inst;
- }
-
- /**
- * Create a DateTime from an ISO 8601 string
- * @param {string} text - the ISO string
- * @param {Object} opts - options to affect the creation
- * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
- * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
- * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
- * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
- * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
- * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance
- * @example DateTime.fromISO('2016-05-25T09:08:34.123')
- * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
- * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
- * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
- * @example DateTime.fromISO('2016-W05-4')
- * @return {DateTime}
- */;
- DateTime.fromISO = function fromISO(text, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var _parseISODate = parseISODate(text),
- vals = _parseISODate[0],
- parsedZone = _parseISODate[1];
- return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
- }
-
- /**
- * Create a DateTime from an RFC 2822 string
- * @param {string} text - the RFC 2822 string
- * @param {Object} opts - options to affect the creation
- * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
- * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
- * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
- * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
- * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
- * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
- * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
- * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
- * @return {DateTime}
- */;
- DateTime.fromRFC2822 = function fromRFC2822(text, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var _parseRFC2822Date = parseRFC2822Date(text),
- vals = _parseRFC2822Date[0],
- parsedZone = _parseRFC2822Date[1];
- return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
- }
-
- /**
- * Create a DateTime from an HTTP header date
- * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
- * @param {string} text - the HTTP header date
- * @param {Object} opts - options to affect the creation
- * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
- * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
- * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
- * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
- * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
- * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
- * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
- * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
- * @return {DateTime}
- */;
- DateTime.fromHTTP = function fromHTTP(text, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var _parseHTTPDate = parseHTTPDate(text),
- vals = _parseHTTPDate[0],
- parsedZone = _parseHTTPDate[1];
- return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
- }
-
- /**
- * Create a DateTime from an input string and format string.
- * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
- * @param {string} text - the string to parse
- * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
- * @param {Object} opts - options to affect the creation
- * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
- * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
- * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
- * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
- * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
- * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @return {DateTime}
- */;
- DateTime.fromFormat = function fromFormat(text, fmt, opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (isUndefined(text) || isUndefined(fmt)) {
- throw new InvalidArgumentError("fromFormat requires an input string and a format");
- }
- var _opts = opts,
- _opts$locale = _opts.locale,
- locale = _opts$locale === void 0 ? null : _opts$locale,
- _opts$numberingSystem = _opts.numberingSystem,
- numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem,
- localeToUse = Locale.fromOpts({
- locale: locale,
- numberingSystem: numberingSystem,
- defaultToEN: true
- }),
- _parseFromTokens = parseFromTokens(localeToUse, text, fmt),
- vals = _parseFromTokens[0],
- parsedZone = _parseFromTokens[1],
- specificOffset = _parseFromTokens[2],
- invalid = _parseFromTokens[3];
- if (invalid) {
- return DateTime.invalid(invalid);
- } else {
- return parseDataToDateTime(vals, parsedZone, opts, "format " + fmt, text, specificOffset);
- }
- }
-
- /**
- * @deprecated use fromFormat instead
- */;
- DateTime.fromString = function fromString(text, fmt, opts) {
- if (opts === void 0) {
- opts = {};
- }
- return DateTime.fromFormat(text, fmt, opts);
- }
-
- /**
- * Create a DateTime from a SQL date, time, or datetime
- * Defaults to en-US if no locale has been specified, regardless of the system's locale
- * @param {string} text - the string to parse
- * @param {Object} opts - options to affect the creation
- * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
- * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
- * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
- * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
- * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
- * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
- * @example DateTime.fromSQL('2017-05-15')
- * @example DateTime.fromSQL('2017-05-15 09:12:34')
- * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
- * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
- * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
- * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
- * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
- * @example DateTime.fromSQL('09:12:34.342')
- * @return {DateTime}
- */;
- DateTime.fromSQL = function fromSQL(text, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var _parseSQL = parseSQL(text),
- vals = _parseSQL[0],
- parsedZone = _parseSQL[1];
- return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
- }
-
- /**
- * Create an invalid DateTime.
- * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.
- * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
- * @return {DateTime}
- */;
- DateTime.invalid = function invalid(reason, explanation) {
- if (explanation === void 0) {
- explanation = null;
- }
- if (!reason) {
- throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
- }
- var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
- if (Settings.throwOnInvalid) {
- throw new InvalidDateTimeError(invalid);
- } else {
- return new DateTime({
- invalid: invalid
- });
- }
- }
-
- /**
- * Check if an object is an instance of DateTime. Works across context boundaries
- * @param {object} o
- * @return {boolean}
- */;
- DateTime.isDateTime = function isDateTime(o) {
- return o && o.isLuxonDateTime || false;
- }
-
- /**
- * Produce the format string for a set of options
- * @param formatOpts
- * @param localeOpts
- * @returns {string}
- */;
- DateTime.parseFormatForOpts = function parseFormatForOpts(formatOpts, localeOpts) {
- if (localeOpts === void 0) {
- localeOpts = {};
- }
- var tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
- return !tokenList ? null : tokenList.map(function (t) {
- return t ? t.val : null;
- }).join("");
- }
-
- /**
- * Produce the the fully expanded format token for the locale
- * Does NOT quote characters, so quoted tokens will not round trip correctly
- * @param fmt
- * @param localeOpts
- * @returns {string}
- */;
- DateTime.expandFormat = function expandFormat(fmt, localeOpts) {
- if (localeOpts === void 0) {
- localeOpts = {};
- }
- var expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
- return expanded.map(function (t) {
- return t.val;
- }).join("");
- };
- DateTime.resetCache = function resetCache() {
- zoneOffsetTs = undefined;
- zoneOffsetGuessCache.clear();
- }
-
- // INFO
-
- /**
- * Get the value of unit.
- * @param {string} unit - a unit such as 'minute' or 'day'
- * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
- * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
- * @return {number}
- */;
- var _proto = DateTime.prototype;
- _proto.get = function get(unit) {
- return this[unit];
- }
-
- /**
- * Returns whether the DateTime is valid. Invalid DateTimes occur when:
- * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
- * * The DateTime was created by an operation on another invalid date
- * @type {boolean}
- */;
- /**
- * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC
- * in this DateTime's zone. During DST changes local time can be ambiguous, for example
- * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.
- * This method will return both possible DateTimes if this DateTime's local time is ambiguous.
- * @returns {DateTime[]}
- */
- _proto.getPossibleOffsets = function getPossibleOffsets() {
- if (!this.isValid || this.isOffsetFixed) {
- return [this];
- }
- var dayMs = 86400000;
- var minuteMs = 60000;
- var localTS = objToLocalTS(this.c);
- var oEarlier = this.zone.offset(localTS - dayMs);
- var oLater = this.zone.offset(localTS + dayMs);
- var o1 = this.zone.offset(localTS - oEarlier * minuteMs);
- var o2 = this.zone.offset(localTS - oLater * minuteMs);
- if (o1 === o2) {
- return [this];
- }
- var ts1 = localTS - o1 * minuteMs;
- var ts2 = localTS - o2 * minuteMs;
- var c1 = tsToObj(ts1, o1);
- var c2 = tsToObj(ts2, o2);
- if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) {
- return [clone(this, {
- ts: ts1
- }), clone(this, {
- ts: ts2
- })];
- }
- return [this];
- }
-
- /**
- * Returns true if this DateTime is in a leap year, false otherwise
- * @example DateTime.local(2016).isInLeapYear //=> true
- * @example DateTime.local(2013).isInLeapYear //=> false
- * @type {boolean}
- */;
- /**
- * Returns the resolved Intl options for this DateTime.
- * This is useful in understanding the behavior of formatting methods
- * @param {Object} opts - the same options as toLocaleString
- * @return {Object}
- */
- _proto.resolvedLocaleOptions = function resolvedLocaleOptions(opts) {
- if (opts === void 0) {
- opts = {};
- }
- var _Formatter$create$res = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this),
- locale = _Formatter$create$res.locale,
- numberingSystem = _Formatter$create$res.numberingSystem,
- calendar = _Formatter$create$res.calendar;
- return {
- locale: locale,
- numberingSystem: numberingSystem,
- outputCalendar: calendar
- };
- }
-
- // TRANSFORM
-
- /**
- * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
- *
- * Equivalent to {@link DateTime#setZone}('utc')
- * @param {number} [offset=0] - optionally, an offset from UTC in minutes
- * @param {Object} [opts={}] - options to pass to `setZone()`
- * @return {DateTime}
- */;
- _proto.toUTC = function toUTC(offset, opts) {
- if (offset === void 0) {
- offset = 0;
- }
- if (opts === void 0) {
- opts = {};
- }
- return this.setZone(FixedOffsetZone.instance(offset), opts);
- }
-
- /**
- * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
- *
- * Equivalent to `setZone('local')`
- * @return {DateTime}
- */;
- _proto.toLocal = function toLocal() {
- return this.setZone(Settings.defaultZone);
- }
-
- /**
- * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
- *
- * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
- * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
- * @param {Object} opts - options
- * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
- * @return {DateTime}
- */;
- _proto.setZone = function setZone(zone, _temp) {
- var _ref2 = _temp === void 0 ? {} : _temp,
- _ref2$keepLocalTime = _ref2.keepLocalTime,
- keepLocalTime = _ref2$keepLocalTime === void 0 ? false : _ref2$keepLocalTime,
- _ref2$keepCalendarTim = _ref2.keepCalendarTime,
- keepCalendarTime = _ref2$keepCalendarTim === void 0 ? false : _ref2$keepCalendarTim;
- zone = normalizeZone(zone, Settings.defaultZone);
- if (zone.equals(this.zone)) {
- return this;
- } else if (!zone.isValid) {
- return DateTime.invalid(unsupportedZone(zone));
- } else {
- var newTS = this.ts;
- if (keepLocalTime || keepCalendarTime) {
- var offsetGuess = zone.offset(this.ts);
- var asObj = this.toObject();
- var _objToTS3 = objToTS(asObj, offsetGuess, zone);
- newTS = _objToTS3[0];
- }
- return clone(this, {
- ts: newTS,
- zone: zone
- });
- }
- }
-
- /**
- * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
- * @param {Object} properties - the properties to set
- * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
- * @return {DateTime}
- */;
- _proto.reconfigure = function reconfigure(_temp2) {
- var _ref3 = _temp2 === void 0 ? {} : _temp2,
- locale = _ref3.locale,
- numberingSystem = _ref3.numberingSystem,
- outputCalendar = _ref3.outputCalendar;
- var loc = this.loc.clone({
- locale: locale,
- numberingSystem: numberingSystem,
- outputCalendar: outputCalendar
- });
- return clone(this, {
- loc: loc
- });
- }
-
- /**
- * "Set" the locale. Returns a newly-constructed DateTime.
- * Just a convenient alias for reconfigure({ locale })
- * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
- * @return {DateTime}
- */;
- _proto.setLocale = function setLocale(locale) {
- return this.reconfigure({
- locale: locale
- });
- }
-
- /**
- * "Set" the values of specified units. Returns a newly-constructed DateTime.
- * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
- *
- * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.
- * They cannot be mixed with ISO-week units like `weekday`.
- * @param {Object} values - a mapping of units to numbers
- * @example dt.set({ year: 2017 })
- * @example dt.set({ hour: 8, minute: 30 })
- * @example dt.set({ weekday: 5 })
- * @example dt.set({ year: 2005, ordinal: 234 })
- * @return {DateTime}
- */;
- _proto.set = function set(values) {
- if (!this.isValid) return this;
- var normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);
- var _usesLocalWeekValues2 = usesLocalWeekValues(normalized, this.loc),
- minDaysInFirstWeek = _usesLocalWeekValues2.minDaysInFirstWeek,
- startOfWeek = _usesLocalWeekValues2.startOfWeek;
- var settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday),
- containsOrdinal = !isUndefined(normalized.ordinal),
- containsGregorYear = !isUndefined(normalized.year),
- containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
- containsGregor = containsGregorYear || containsGregorMD,
- definiteWeekDef = normalized.weekYear || normalized.weekNumber;
- if ((containsGregor || containsOrdinal) && definiteWeekDef) {
- throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
- }
- if (containsGregorMD && containsOrdinal) {
- throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
- }
- var mixed;
- if (settingWeekStuff) {
- mixed = weekToGregorian(_extends({}, gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), normalized), minDaysInFirstWeek, startOfWeek);
- } else if (!isUndefined(normalized.ordinal)) {
- mixed = ordinalToGregorian(_extends({}, gregorianToOrdinal(this.c), normalized));
- } else {
- mixed = _extends({}, this.toObject(), normalized);
-
- // if we didn't set the day but we ended up on an overflow date,
- // use the last day of the right month
- if (isUndefined(normalized.day)) {
- mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
- }
- }
- var _objToTS4 = objToTS(mixed, this.o, this.zone),
- ts = _objToTS4[0],
- o = _objToTS4[1];
- return clone(this, {
- ts: ts,
- o: o
- });
- }
-
- /**
- * Add a period of time to this DateTime and return the resulting DateTime
- *
- * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
- * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
- * @example DateTime.now().plus(123) //~> in 123 milliseconds
- * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
- * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
- * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
- * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
- * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
- * @return {DateTime}
- */;
- _proto.plus = function plus(duration) {
- if (!this.isValid) return this;
- var dur = Duration.fromDurationLike(duration);
- return clone(this, adjustTime(this, dur));
- }
-
- /**
- * Subtract a period of time to this DateTime and return the resulting DateTime
- * See {@link DateTime#plus}
- * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
- @return {DateTime}
- */;
- _proto.minus = function minus(duration) {
- if (!this.isValid) return this;
- var dur = Duration.fromDurationLike(duration).negate();
- return clone(this, adjustTime(this, dur));
- }
-
- /**
- * "Set" this DateTime to the beginning of a unit of time.
- * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
- * @param {Object} opts - options
- * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
- * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
- * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
- * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
- * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
- * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
- * @return {DateTime}
- */;
- _proto.startOf = function startOf(unit, _temp3) {
- var _ref4 = _temp3 === void 0 ? {} : _temp3,
- _ref4$useLocaleWeeks = _ref4.useLocaleWeeks,
- useLocaleWeeks = _ref4$useLocaleWeeks === void 0 ? false : _ref4$useLocaleWeeks;
- if (!this.isValid) return this;
- var o = {},
- normalizedUnit = Duration.normalizeUnit(unit);
- switch (normalizedUnit) {
- case "years":
- o.month = 1;
- // falls through
- case "quarters":
- case "months":
- o.day = 1;
- // falls through
- case "weeks":
- case "days":
- o.hour = 0;
- // falls through
- case "hours":
- o.minute = 0;
- // falls through
- case "minutes":
- o.second = 0;
- // falls through
- case "seconds":
- o.millisecond = 0;
- break;
- // no default, invalid units throw in normalizeUnit()
- }
-
- if (normalizedUnit === "weeks") {
- if (useLocaleWeeks) {
- var startOfWeek = this.loc.getStartOfWeek();
- var weekday = this.weekday;
- if (weekday < startOfWeek) {
- o.weekNumber = this.weekNumber - 1;
- }
- o.weekday = startOfWeek;
- } else {
- o.weekday = 1;
- }
- }
- if (normalizedUnit === "quarters") {
- var q = Math.ceil(this.month / 3);
- o.month = (q - 1) * 3 + 1;
- }
- return this.set(o);
- }
-
- /**
- * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
- * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
- * @param {Object} opts - options
- * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
- * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
- * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
- * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
- * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
- * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
- * @return {DateTime}
- */;
- _proto.endOf = function endOf(unit, opts) {
- var _this$plus;
- return this.isValid ? this.plus((_this$plus = {}, _this$plus[unit] = 1, _this$plus)).startOf(unit, opts).minus(1) : this;
- }
-
- // OUTPUT
-
- /**
- * Returns a string representation of this DateTime formatted according to the specified format string.
- * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
- * Defaults to en-US if no locale has been specified, regardless of the system's locale.
- * @param {string} fmt - the format string
- * @param {Object} opts - opts to override the configuration options on this DateTime
- * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
- * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
- * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
- * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
- * @return {string}
- */;
- _proto.toFormat = function toFormat(fmt, opts) {
- if (opts === void 0) {
- opts = {};
- }
- return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID;
- }
-
- /**
- * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
- * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
- * of the DateTime in the assigned locale.
- * Defaults to the system's locale if no locale has been specified
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
- * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
- * @param {Object} opts - opts to override the configuration options on this DateTime
- * @example DateTime.now().toLocaleString(); //=> 4/20/2017
- * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
- * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
- * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
- * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
- * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
- * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
- * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
- * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
- * @return {string}
- */;
- _proto.toLocaleString = function toLocaleString(formatOpts, opts) {
- if (formatOpts === void 0) {
- formatOpts = DATE_SHORT;
- }
- if (opts === void 0) {
- opts = {};
- }
- return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID;
- }
-
- /**
- * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
- * Defaults to the system's locale if no locale has been specified
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
- * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
- * @example DateTime.now().toLocaleParts(); //=> [
- * //=> { type: 'day', value: '25' },
- * //=> { type: 'literal', value: '/' },
- * //=> { type: 'month', value: '05' },
- * //=> { type: 'literal', value: '/' },
- * //=> { type: 'year', value: '1982' }
- * //=> ]
- */;
- _proto.toLocaleParts = function toLocaleParts(opts) {
- if (opts === void 0) {
- opts = {};
- }
- return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this DateTime
- * @param {Object} opts - options
- * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
- * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
- * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
- * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
- * @param {string} [opts.format='extended'] - choose between the basic and extended format
- * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'years', 'months', 'days', 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0.
- * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
- * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
- * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
- * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
- * @example DateTime.now().toISO({ precision: 'day' }) //=> '2017-04-22Z'
- * @example DateTime.now().toISO({ precision: 'minute' }) //=> '2017-04-22T20:47Z'
- * @return {string|null}
- */;
- _proto.toISO = function toISO(_temp4) {
- var _ref5 = _temp4 === void 0 ? {} : _temp4,
- _ref5$format = _ref5.format,
- format = _ref5$format === void 0 ? "extended" : _ref5$format,
- _ref5$suppressSeconds = _ref5.suppressSeconds,
- suppressSeconds = _ref5$suppressSeconds === void 0 ? false : _ref5$suppressSeconds,
- _ref5$suppressMillise = _ref5.suppressMilliseconds,
- suppressMilliseconds = _ref5$suppressMillise === void 0 ? false : _ref5$suppressMillise,
- _ref5$includeOffset = _ref5.includeOffset,
- includeOffset = _ref5$includeOffset === void 0 ? true : _ref5$includeOffset,
- _ref5$extendedZone = _ref5.extendedZone,
- extendedZone = _ref5$extendedZone === void 0 ? false : _ref5$extendedZone,
- _ref5$precision = _ref5.precision,
- precision = _ref5$precision === void 0 ? "milliseconds" : _ref5$precision;
- if (!this.isValid) {
- return null;
- }
- precision = normalizeUnit(precision);
- var ext = format === "extended";
- var c = _toISODate(this, ext, precision);
- if (orderedUnits.indexOf(precision) >= 3) c += "T";
- c += _toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision);
- return c;
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this DateTime's date component
- * @param {Object} opts - options
- * @param {string} [opts.format='extended'] - choose between the basic and extended format
- * @param {string} [opts.precision='day'] - truncate output to desired precision: 'years', 'months', or 'days'.
- * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
- * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
- * @example DateTime.utc(1982, 5, 25).toISODate({ precision: 'month' }) //=> '1982-05'
- * @return {string|null}
- */;
- _proto.toISODate = function toISODate(_temp5) {
- var _ref6 = _temp5 === void 0 ? {} : _temp5,
- _ref6$format = _ref6.format,
- format = _ref6$format === void 0 ? "extended" : _ref6$format,
- _ref6$precision = _ref6.precision,
- precision = _ref6$precision === void 0 ? "day" : _ref6$precision;
- if (!this.isValid) {
- return null;
- }
- return _toISODate(this, format === "extended", normalizeUnit(precision));
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this DateTime's week date
- * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
- * @return {string}
- */;
- _proto.toISOWeekDate = function toISOWeekDate() {
- return toTechFormat(this, "kkkk-'W'WW-c");
- }
-
- /**
- * Returns an ISO 8601-compliant string representation of this DateTime's time component
- * @param {Object} opts - options
- * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
- * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
- * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
- * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
- * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
- * @param {string} [opts.format='extended'] - choose between the basic and extended format
- * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0.
- * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
- * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
- * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
- * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
- * @example DateTime.utc().set({ hour: 7, minute: 34, second: 56 }).toISOTime({ precision: 'minute' }) //=> '07:34Z'
- * @return {string}
- */;
- _proto.toISOTime = function toISOTime(_temp6) {
- var _ref7 = _temp6 === void 0 ? {} : _temp6,
- _ref7$suppressMillise = _ref7.suppressMilliseconds,
- suppressMilliseconds = _ref7$suppressMillise === void 0 ? false : _ref7$suppressMillise,
- _ref7$suppressSeconds = _ref7.suppressSeconds,
- suppressSeconds = _ref7$suppressSeconds === void 0 ? false : _ref7$suppressSeconds,
- _ref7$includeOffset = _ref7.includeOffset,
- includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset,
- _ref7$includePrefix = _ref7.includePrefix,
- includePrefix = _ref7$includePrefix === void 0 ? false : _ref7$includePrefix,
- _ref7$extendedZone = _ref7.extendedZone,
- extendedZone = _ref7$extendedZone === void 0 ? false : _ref7$extendedZone,
- _ref7$format = _ref7.format,
- format = _ref7$format === void 0 ? "extended" : _ref7$format,
- _ref7$precision = _ref7.precision,
- precision = _ref7$precision === void 0 ? "milliseconds" : _ref7$precision;
- if (!this.isValid) {
- return null;
- }
- precision = normalizeUnit(precision);
- var c = includePrefix && orderedUnits.indexOf(precision) >= 3 ? "T" : "";
- return c + _toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision);
- }
-
- /**
- * Returns an RFC 2822-compatible string representation of this DateTime
- * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
- * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
- * @return {string}
- */;
- _proto.toRFC2822 = function toRFC2822() {
- return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
- }
-
- /**
- * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
- * Specifically, the string conforms to RFC 1123.
- * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
- * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
- * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
- * @return {string}
- */;
- _proto.toHTTP = function toHTTP() {
- return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
- }
-
- /**
- * Returns a string representation of this DateTime appropriate for use in SQL Date
- * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
- * @return {string|null}
- */;
- _proto.toSQLDate = function toSQLDate() {
- if (!this.isValid) {
- return null;
- }
- return _toISODate(this, true);
- }
-
- /**
- * Returns a string representation of this DateTime appropriate for use in SQL Time
- * @param {Object} opts - options
- * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
- * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
- * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
- * @example DateTime.utc().toSQL() //=> '05:15:16.345'
- * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
- * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
- * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
- * @return {string}
- */;
- _proto.toSQLTime = function toSQLTime(_temp7) {
- var _ref8 = _temp7 === void 0 ? {} : _temp7,
- _ref8$includeOffset = _ref8.includeOffset,
- includeOffset = _ref8$includeOffset === void 0 ? true : _ref8$includeOffset,
- _ref8$includeZone = _ref8.includeZone,
- includeZone = _ref8$includeZone === void 0 ? false : _ref8$includeZone,
- _ref8$includeOffsetSp = _ref8.includeOffsetSpace,
- includeOffsetSpace = _ref8$includeOffsetSp === void 0 ? true : _ref8$includeOffsetSp;
- var fmt = "HH:mm:ss.SSS";
- if (includeZone || includeOffset) {
- if (includeOffsetSpace) {
- fmt += " ";
- }
- if (includeZone) {
- fmt += "z";
- } else if (includeOffset) {
- fmt += "ZZ";
- }
- }
- return toTechFormat(this, fmt, true);
- }
-
- /**
- * Returns a string representation of this DateTime appropriate for use in SQL DateTime
- * @param {Object} opts - options
- * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
- * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
- * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
- * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
- * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
- * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
- * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
- * @return {string}
- */;
- _proto.toSQL = function toSQL(opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (!this.isValid) {
- return null;
- }
- return this.toSQLDate() + " " + this.toSQLTime(opts);
- }
-
- /**
- * Returns a string representation of this DateTime appropriate for debugging
- * @return {string}
- */;
- _proto.toString = function toString() {
- return this.isValid ? this.toISO() : INVALID;
- }
-
- /**
- * Returns a string representation of this DateTime appropriate for the REPL.
- * @return {string}
- */;
- _proto[_Symbol$for] = function () {
- if (this.isValid) {
- return "DateTime { ts: " + this.toISO() + ", zone: " + this.zone.name + ", locale: " + this.locale + " }";
- } else {
- return "DateTime { Invalid, reason: " + this.invalidReason + " }";
- }
- }
-
- /**
- * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
- * @return {number}
- */;
- _proto.valueOf = function valueOf() {
- return this.toMillis();
- }
-
- /**
- * Returns the epoch milliseconds of this DateTime.
- * @return {number}
- */;
- _proto.toMillis = function toMillis() {
- return this.isValid ? this.ts : NaN;
- }
-
- /**
- * Returns the epoch seconds (including milliseconds in the fractional part) of this DateTime.
- * @return {number}
- */;
- _proto.toSeconds = function toSeconds() {
- return this.isValid ? this.ts / 1000 : NaN;
- }
-
- /**
- * Returns the epoch seconds (as a whole number) of this DateTime.
- * @return {number}
- */;
- _proto.toUnixInteger = function toUnixInteger() {
- return this.isValid ? Math.floor(this.ts / 1000) : NaN;
- }
-
- /**
- * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
- * @return {string}
- */;
- _proto.toJSON = function toJSON() {
- return this.toISO();
- }
-
- /**
- * Returns a BSON serializable equivalent to this DateTime.
- * @return {Date}
- */;
- _proto.toBSON = function toBSON() {
- return this.toJSDate();
- }
-
- /**
- * Returns a JavaScript object with this DateTime's year, month, day, and so on.
- * @param opts - options for generating the object
- * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
- * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
- * @return {Object}
- */;
- _proto.toObject = function toObject(opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (!this.isValid) return {};
- var base = _extends({}, this.c);
- if (opts.includeConfig) {
- base.outputCalendar = this.outputCalendar;
- base.numberingSystem = this.loc.numberingSystem;
- base.locale = this.loc.locale;
- }
- return base;
- }
-
- /**
- * Returns a JavaScript Date equivalent to this DateTime.
- * @return {Date}
- */;
- _proto.toJSDate = function toJSDate() {
- return new Date(this.isValid ? this.ts : NaN);
- }
-
- // COMPARE
-
- /**
- * Return the difference between two DateTimes as a Duration.
- * @param {DateTime} otherDateTime - the DateTime to compare this one to
- * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
- * @param {Object} opts - options that affect the creation of the Duration
- * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
- * @example
- * var i1 = DateTime.fromISO('1982-05-25T09:45'),
- * i2 = DateTime.fromISO('1983-10-14T10:30');
- * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
- * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
- * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
- * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
- * @return {Duration}
- */;
- _proto.diff = function diff(otherDateTime, unit, opts) {
- if (unit === void 0) {
- unit = "milliseconds";
- }
- if (opts === void 0) {
- opts = {};
- }
- if (!this.isValid || !otherDateTime.isValid) {
- return Duration.invalid("created by diffing an invalid DateTime");
- }
- var durOpts = _extends({
- locale: this.locale,
- numberingSystem: this.numberingSystem
- }, opts);
- var units = maybeArray(unit).map(Duration.normalizeUnit),
- otherIsLater = otherDateTime.valueOf() > this.valueOf(),
- earlier = otherIsLater ? this : otherDateTime,
- later = otherIsLater ? otherDateTime : this,
- diffed = _diff(earlier, later, units, durOpts);
- return otherIsLater ? diffed.negate() : diffed;
- }
-
- /**
- * Return the difference between this DateTime and right now.
- * See {@link DateTime#diff}
- * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
- * @param {Object} opts - options that affect the creation of the Duration
- * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
- * @return {Duration}
- */;
- _proto.diffNow = function diffNow(unit, opts) {
- if (unit === void 0) {
- unit = "milliseconds";
- }
- if (opts === void 0) {
- opts = {};
- }
- return this.diff(DateTime.now(), unit, opts);
- }
-
- /**
- * Return an Interval spanning between this DateTime and another DateTime
- * @param {DateTime} otherDateTime - the other end point of the Interval
- * @return {Interval|DateTime}
- */;
- _proto.until = function until(otherDateTime) {
- return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
- }
-
- /**
- * Return whether this DateTime is in the same unit of time as another DateTime.
- * Higher-order units must also be identical for this function to return `true`.
- * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
- * @param {DateTime} otherDateTime - the other DateTime
- * @param {string} unit - the unit of time to check sameness on
- * @param {Object} opts - options
- * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used
- * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
- * @return {boolean}
- */;
- _proto.hasSame = function hasSame(otherDateTime, unit, opts) {
- if (!this.isValid) return false;
- var inputMs = otherDateTime.valueOf();
- var adjustedToZone = this.setZone(otherDateTime.zone, {
- keepLocalTime: true
- });
- return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts);
- }
-
- /**
- * Equality check
- * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
- * To compare just the millisecond values, use `+dt1 === +dt2`.
- * @param {DateTime} other - the other DateTime
- * @return {boolean}
- */;
- _proto.equals = function equals(other) {
- return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
- }
-
- /**
- * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
- * platform supports Intl.RelativeTimeFormat. Rounds towards zero by default.
- * @param {Object} options - options that affect the output
- * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
- * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
- * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
- * @param {boolean} [options.round=true] - whether to round the numbers in the output.
- * @param {string} [options.rounding="trunc"] - rounding method to use when rounding the numbers in the output. Can be "trunc" (toward zero), "expand" (away from zero), "round", "floor", or "ceil".
- * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
- * @param {string} options.locale - override the locale of this DateTime
- * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
- * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
- * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
- * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
- * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
- * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
- * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
- */;
- _proto.toRelative = function toRelative(options) {
- if (options === void 0) {
- options = {};
- }
- if (!this.isValid) return null;
- var base = options.base || DateTime.fromObject({}, {
- zone: this.zone
- }),
- padding = options.padding ? this < base ? -options.padding : options.padding : 0;
- var units = ["years", "months", "days", "hours", "minutes", "seconds"];
- var unit = options.unit;
- if (Array.isArray(options.unit)) {
- units = options.unit;
- unit = undefined;
- }
- return diffRelative(base, this.plus(padding), _extends({}, options, {
- numeric: "always",
- units: units,
- unit: unit
- }));
- }
-
- /**
- * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
- * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
- * @param {Object} options - options that affect the output
- * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
- * @param {string} options.locale - override the locale of this DateTime
- * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
- * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
- * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
- * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
- * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
- * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
- */;
- _proto.toRelativeCalendar = function toRelativeCalendar(options) {
- if (options === void 0) {
- options = {};
- }
- if (!this.isValid) return null;
- return diffRelative(options.base || DateTime.fromObject({}, {
- zone: this.zone
- }), this, _extends({}, options, {
- numeric: "auto",
- units: ["years", "months", "days"],
- calendary: true
- }));
- }
-
- /**
- * Return the min of several date times
- * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
- * @return {DateTime} the min DateTime, or undefined if called with no argument
- */;
- DateTime.min = function min() {
- for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) {
- dateTimes[_key] = arguments[_key];
- }
- if (!dateTimes.every(DateTime.isDateTime)) {
- throw new InvalidArgumentError("min requires all arguments be DateTimes");
- }
- return bestBy(dateTimes, function (i) {
- return i.valueOf();
- }, Math.min);
- }
-
- /**
- * Return the max of several date times
- * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
- * @return {DateTime} the max DateTime, or undefined if called with no argument
- */;
- DateTime.max = function max() {
- for (var _len2 = arguments.length, dateTimes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- dateTimes[_key2] = arguments[_key2];
- }
- if (!dateTimes.every(DateTime.isDateTime)) {
- throw new InvalidArgumentError("max requires all arguments be DateTimes");
- }
- return bestBy(dateTimes, function (i) {
- return i.valueOf();
- }, Math.max);
- }
-
- // MISC
-
- /**
- * Explain how a string would be parsed by fromFormat()
- * @param {string} text - the string to parse
- * @param {string} fmt - the format the string is expected to be in (see description)
- * @param {Object} options - options taken by fromFormat()
- * @return {Object}
- */;
- DateTime.fromFormatExplain = function fromFormatExplain(text, fmt, options) {
- if (options === void 0) {
- options = {};
- }
- var _options = options,
- _options$locale = _options.locale,
- locale = _options$locale === void 0 ? null : _options$locale,
- _options$numberingSys = _options.numberingSystem,
- numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys,
- localeToUse = Locale.fromOpts({
- locale: locale,
- numberingSystem: numberingSystem,
- defaultToEN: true
- });
- return explainFromTokens(localeToUse, text, fmt);
- }
-
- /**
- * @deprecated use fromFormatExplain instead
- */;
- DateTime.fromStringExplain = function fromStringExplain(text, fmt, options) {
- if (options === void 0) {
- options = {};
- }
- return DateTime.fromFormatExplain(text, fmt, options);
- }
-
- /**
- * Build a parser for `fmt` using the given locale. This parser can be passed
- * to {@link DateTime.fromFormatParser} to a parse a date in this format. This
- * can be used to optimize cases where many dates need to be parsed in a
- * specific format.
- *
- * @param {String} fmt - the format the string is expected to be in (see
- * description)
- * @param {Object} options - options used to set locale and numberingSystem
- * for parser
- * @returns {TokenParser} - opaque object to be used
- */;
- DateTime.buildFormatParser = function buildFormatParser(fmt, options) {
- if (options === void 0) {
- options = {};
- }
- var _options2 = options,
- _options2$locale = _options2.locale,
- locale = _options2$locale === void 0 ? null : _options2$locale,
- _options2$numberingSy = _options2.numberingSystem,
- numberingSystem = _options2$numberingSy === void 0 ? null : _options2$numberingSy,
- localeToUse = Locale.fromOpts({
- locale: locale,
- numberingSystem: numberingSystem,
- defaultToEN: true
- });
- return new TokenParser(localeToUse, fmt);
- }
-
- /**
- * Create a DateTime from an input string and format parser.
- *
- * The format parser must have been created with the same locale as this call.
- *
- * @param {String} text - the string to parse
- * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}
- * @param {Object} opts - options taken by fromFormat()
- * @returns {DateTime}
- */;
- DateTime.fromFormatParser = function fromFormatParser(text, formatParser, opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (isUndefined(text) || isUndefined(formatParser)) {
- throw new InvalidArgumentError("fromFormatParser requires an input string and a format parser");
- }
- var _opts2 = opts,
- _opts2$locale = _opts2.locale,
- locale = _opts2$locale === void 0 ? null : _opts2$locale,
- _opts2$numberingSyste = _opts2.numberingSystem,
- numberingSystem = _opts2$numberingSyste === void 0 ? null : _opts2$numberingSyste,
- localeToUse = Locale.fromOpts({
- locale: locale,
- numberingSystem: numberingSystem,
- defaultToEN: true
- });
- if (!localeToUse.equals(formatParser.locale)) {
- throw new InvalidArgumentError("fromFormatParser called with a locale of " + localeToUse + ", " + ("but the format parser was created for " + formatParser.locale));
- }
- var _formatParser$explain = formatParser.explainFromTokens(text),
- result = _formatParser$explain.result,
- zone = _formatParser$explain.zone,
- specificOffset = _formatParser$explain.specificOffset,
- invalidReason = _formatParser$explain.invalidReason;
- if (invalidReason) {
- return DateTime.invalid(invalidReason);
- } else {
- return parseDataToDateTime(result, zone, opts, "format " + formatParser.format, text, specificOffset);
- }
- }
-
- // FORMAT PRESETS
-
- /**
- * {@link DateTime#toLocaleString} format like 10/14/1983
- * @type {Object}
- */;
- _createClass(DateTime, [{
- key: "isValid",
- get: function get() {
- return this.invalid === null;
- }
-
- /**
- * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
- * @type {string}
- */
- }, {
- key: "invalidReason",
- get: function get() {
- return this.invalid ? this.invalid.reason : null;
- }
-
- /**
- * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
- * @type {string}
- */
- }, {
- key: "invalidExplanation",
- get: function get() {
- return this.invalid ? this.invalid.explanation : null;
- }
-
- /**
- * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
- *
- * @type {string}
- */
- }, {
- key: "locale",
- get: function get() {
- return this.isValid ? this.loc.locale : null;
- }
-
- /**
- * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
- *
- * @type {string}
- */
- }, {
- key: "numberingSystem",
- get: function get() {
- return this.isValid ? this.loc.numberingSystem : null;
- }
-
- /**
- * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
- *
- * @type {string}
- */
- }, {
- key: "outputCalendar",
- get: function get() {
- return this.isValid ? this.loc.outputCalendar : null;
- }
-
- /**
- * Get the time zone associated with this DateTime.
- * @type {Zone}
- */
- }, {
- key: "zone",
- get: function get() {
- return this._zone;
- }
-
- /**
- * Get the name of the time zone.
- * @type {string}
- */
- }, {
- key: "zoneName",
- get: function get() {
- return this.isValid ? this.zone.name : null;
- }
-
- /**
- * Get the year
- * @example DateTime.local(2017, 5, 25).year //=> 2017
- * @type {number}
- */
- }, {
- key: "year",
- get: function get() {
- return this.isValid ? this.c.year : NaN;
- }
-
- /**
- * Get the quarter
- * @example DateTime.local(2017, 5, 25).quarter //=> 2
- * @type {number}
- */
- }, {
- key: "quarter",
- get: function get() {
- return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
- }
-
- /**
- * Get the month (1-12).
- * @example DateTime.local(2017, 5, 25).month //=> 5
- * @type {number}
- */
- }, {
- key: "month",
- get: function get() {
- return this.isValid ? this.c.month : NaN;
- }
-
- /**
- * Get the day of the month (1-30ish).
- * @example DateTime.local(2017, 5, 25).day //=> 25
- * @type {number}
- */
- }, {
- key: "day",
- get: function get() {
- return this.isValid ? this.c.day : NaN;
- }
-
- /**
- * Get the hour of the day (0-23).
- * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
- * @type {number}
- */
- }, {
- key: "hour",
- get: function get() {
- return this.isValid ? this.c.hour : NaN;
- }
-
- /**
- * Get the minute of the hour (0-59).
- * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
- * @type {number}
- */
- }, {
- key: "minute",
- get: function get() {
- return this.isValid ? this.c.minute : NaN;
- }
-
- /**
- * Get the second of the minute (0-59).
- * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
- * @type {number}
- */
- }, {
- key: "second",
- get: function get() {
- return this.isValid ? this.c.second : NaN;
- }
-
- /**
- * Get the millisecond of the second (0-999).
- * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
- * @type {number}
- */
- }, {
- key: "millisecond",
- get: function get() {
- return this.isValid ? this.c.millisecond : NaN;
- }
-
- /**
- * Get the week year
- * @see https://en.wikipedia.org/wiki/ISO_week_date
- * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
- * @type {number}
- */
- }, {
- key: "weekYear",
- get: function get() {
- return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
- }
-
- /**
- * Get the week number of the week year (1-52ish).
- * @see https://en.wikipedia.org/wiki/ISO_week_date
- * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
- * @type {number}
- */
- }, {
- key: "weekNumber",
- get: function get() {
- return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
- }
-
- /**
- * Get the day of the week.
- * 1 is Monday and 7 is Sunday
- * @see https://en.wikipedia.org/wiki/ISO_week_date
- * @example DateTime.local(2014, 11, 31).weekday //=> 4
- * @type {number}
- */
- }, {
- key: "weekday",
- get: function get() {
- return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
- }
-
- /**
- * Returns true if this date is on a weekend according to the locale, false otherwise
- * @returns {boolean}
- */
- }, {
- key: "isWeekend",
- get: function get() {
- return this.isValid && this.loc.getWeekendDays().includes(this.weekday);
- }
-
- /**
- * Get the day of the week according to the locale.
- * 1 is the first day of the week and 7 is the last day of the week.
- * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,
- * @returns {number}
- */
- }, {
- key: "localWeekday",
- get: function get() {
- return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;
- }
-
- /**
- * Get the week number of the week year according to the locale. Different locales assign week numbers differently,
- * because the week can start on different days of the week (see localWeekday) and because a different number of days
- * is required for a week to count as the first week of a year.
- * @returns {number}
- */
- }, {
- key: "localWeekNumber",
- get: function get() {
- return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;
- }
-
- /**
- * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)
- * differently, see localWeekNumber.
- * @returns {number}
- */
- }, {
- key: "localWeekYear",
- get: function get() {
- return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;
- }
-
- /**
- * Get the ordinal (meaning the day of the year)
- * @example DateTime.local(2017, 5, 25).ordinal //=> 145
- * @type {number|DateTime}
- */
- }, {
- key: "ordinal",
- get: function get() {
- return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
- }
-
- /**
- * Get the human readable short month name, such as 'Oct'.
- * Defaults to the system's locale if no locale has been specified
- * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
- * @type {string}
- */
- }, {
- key: "monthShort",
- get: function get() {
- return this.isValid ? Info.months("short", {
- locObj: this.loc
- })[this.month - 1] : null;
- }
-
- /**
- * Get the human readable long month name, such as 'October'.
- * Defaults to the system's locale if no locale has been specified
- * @example DateTime.local(2017, 10, 30).monthLong //=> October
- * @type {string}
- */
- }, {
- key: "monthLong",
- get: function get() {
- return this.isValid ? Info.months("long", {
- locObj: this.loc
- })[this.month - 1] : null;
- }
-
- /**
- * Get the human readable short weekday, such as 'Mon'.
- * Defaults to the system's locale if no locale has been specified
- * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
- * @type {string}
- */
- }, {
- key: "weekdayShort",
- get: function get() {
- return this.isValid ? Info.weekdays("short", {
- locObj: this.loc
- })[this.weekday - 1] : null;
- }
-
- /**
- * Get the human readable long weekday, such as 'Monday'.
- * Defaults to the system's locale if no locale has been specified
- * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
- * @type {string}
- */
- }, {
- key: "weekdayLong",
- get: function get() {
- return this.isValid ? Info.weekdays("long", {
- locObj: this.loc
- })[this.weekday - 1] : null;
- }
-
- /**
- * Get the UTC offset of this DateTime in minutes
- * @example DateTime.now().offset //=> -240
- * @example DateTime.utc().offset //=> 0
- * @type {number}
- */
- }, {
- key: "offset",
- get: function get() {
- return this.isValid ? +this.o : NaN;
- }
-
- /**
- * Get the short human name for the zone's current offset, for example "EST" or "EDT".
- * Defaults to the system's locale if no locale has been specified
- * @type {string}
- */
- }, {
- key: "offsetNameShort",
- get: function get() {
- if (this.isValid) {
- return this.zone.offsetName(this.ts, {
- format: "short",
- locale: this.locale
- });
- } else {
- return null;
- }
- }
-
- /**
- * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
- * Defaults to the system's locale if no locale has been specified
- * @type {string}
- */
- }, {
- key: "offsetNameLong",
- get: function get() {
- if (this.isValid) {
- return this.zone.offsetName(this.ts, {
- format: "long",
- locale: this.locale
- });
- } else {
- return null;
- }
- }
-
- /**
- * Get whether this zone's offset ever changes, as in a DST.
- * @type {boolean}
- */
- }, {
- key: "isOffsetFixed",
- get: function get() {
- return this.isValid ? this.zone.isUniversal : null;
- }
-
- /**
- * Get whether the DateTime is in a DST.
- * @type {boolean}
- */
- }, {
- key: "isInDST",
- get: function get() {
- if (this.isOffsetFixed) {
- return false;
- } else {
- return this.offset > this.set({
- month: 1,
- day: 1
- }).offset || this.offset > this.set({
- month: 5
- }).offset;
- }
- }
- }, {
- key: "isInLeapYear",
- get: function get() {
- return isLeapYear(this.year);
- }
-
- /**
- * Returns the number of days in this DateTime's month
- * @example DateTime.local(2016, 2).daysInMonth //=> 29
- * @example DateTime.local(2016, 3).daysInMonth //=> 31
- * @type {number}
- */
- }, {
- key: "daysInMonth",
- get: function get() {
- return daysInMonth(this.year, this.month);
- }
-
- /**
- * Returns the number of days in this DateTime's year
- * @example DateTime.local(2016).daysInYear //=> 366
- * @example DateTime.local(2013).daysInYear //=> 365
- * @type {number}
- */
- }, {
- key: "daysInYear",
- get: function get() {
- return this.isValid ? daysInYear(this.year) : NaN;
- }
-
- /**
- * Returns the number of weeks in this DateTime's year
- * @see https://en.wikipedia.org/wiki/ISO_week_date
- * @example DateTime.local(2004).weeksInWeekYear //=> 53
- * @example DateTime.local(2013).weeksInWeekYear //=> 52
- * @type {number}
- */
- }, {
- key: "weeksInWeekYear",
- get: function get() {
- return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
- }
-
- /**
- * Returns the number of weeks in this DateTime's local week year
- * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52
- * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53
- * @type {number}
- */
- }, {
- key: "weeksInLocalWeekYear",
- get: function get() {
- return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN;
- }
- }], [{
- key: "DATE_SHORT",
- get: function get() {
- return DATE_SHORT;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
- * @type {Object}
- */
- }, {
- key: "DATE_MED",
- get: function get() {
- return DATE_MED;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
- * @type {Object}
- */
- }, {
- key: "DATE_MED_WITH_WEEKDAY",
- get: function get() {
- return DATE_MED_WITH_WEEKDAY;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'October 14, 1983'
- * @type {Object}
- */
- }, {
- key: "DATE_FULL",
- get: function get() {
- return DATE_FULL;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
- * @type {Object}
- */
- }, {
- key: "DATE_HUGE",
- get: function get() {
- return DATE_HUGE;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "TIME_SIMPLE",
- get: function get() {
- return TIME_SIMPLE;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "TIME_WITH_SECONDS",
- get: function get() {
- return TIME_WITH_SECONDS;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "TIME_WITH_SHORT_OFFSET",
- get: function get() {
- return TIME_WITH_SHORT_OFFSET;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "TIME_WITH_LONG_OFFSET",
- get: function get() {
- return TIME_WITH_LONG_OFFSET;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
- * @type {Object}
- */
- }, {
- key: "TIME_24_SIMPLE",
- get: function get() {
- return TIME_24_SIMPLE;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
- * @type {Object}
- */
- }, {
- key: "TIME_24_WITH_SECONDS",
- get: function get() {
- return TIME_24_WITH_SECONDS;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
- * @type {Object}
- */
- }, {
- key: "TIME_24_WITH_SHORT_OFFSET",
- get: function get() {
- return TIME_24_WITH_SHORT_OFFSET;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
- * @type {Object}
- */
- }, {
- key: "TIME_24_WITH_LONG_OFFSET",
- get: function get() {
- return TIME_24_WITH_LONG_OFFSET;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_SHORT",
- get: function get() {
- return DATETIME_SHORT;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_SHORT_WITH_SECONDS",
- get: function get() {
- return DATETIME_SHORT_WITH_SECONDS;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_MED",
- get: function get() {
- return DATETIME_MED;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_MED_WITH_SECONDS",
- get: function get() {
- return DATETIME_MED_WITH_SECONDS;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_MED_WITH_WEEKDAY",
- get: function get() {
- return DATETIME_MED_WITH_WEEKDAY;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_FULL",
- get: function get() {
- return DATETIME_FULL;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_FULL_WITH_SECONDS",
- get: function get() {
- return DATETIME_FULL_WITH_SECONDS;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_HUGE",
- get: function get() {
- return DATETIME_HUGE;
- }
-
- /**
- * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
- * @type {Object}
- */
- }, {
- key: "DATETIME_HUGE_WITH_SECONDS",
- get: function get() {
- return DATETIME_HUGE_WITH_SECONDS;
- }
- }]);
- return DateTime;
-}(Symbol.for("nodejs.util.inspect.custom"));
-function friendlyDateTime(dateTimeish) {
- if (DateTime.isDateTime(dateTimeish)) {
- return dateTimeish;
- } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
- return DateTime.fromJSDate(dateTimeish);
- } else if (dateTimeish && typeof dateTimeish === "object") {
- return DateTime.fromObject(dateTimeish);
- } else {
- throw new InvalidArgumentError("Unknown datetime argument: " + dateTimeish + ", of type " + typeof dateTimeish);
- }
-}
-
-var VERSION = "3.7.2";
-
-exports.DateTime = DateTime;
-exports.Duration = Duration;
-exports.FixedOffsetZone = FixedOffsetZone;
-exports.IANAZone = IANAZone;
-exports.Info = Info;
-exports.Interval = Interval;
-exports.InvalidZone = InvalidZone;
-exports.Settings = Settings;
-exports.SystemZone = SystemZone;
-exports.VERSION = VERSION;
-exports.Zone = Zone;
-
-
-},{}]},{},[1]);
diff --git a/examples/browser/exec-age.js b/examples/browser/exec-age.js
new file mode 100644
index 000000000..f59095b63
--- /dev/null
+++ b/examples/browser/exec-age.js
@@ -0,0 +1,28 @@
+import cql from 'cql-execution';
+import measure from './age.json';
+
+window.cql = cql;
+window.patients = [
+ {
+ id: '1',
+ recordType: 'Patient',
+ name: 'John Smith',
+ gender: 'M',
+ birthDate: '1980-02-17'
+ },
+ {
+ id: '2',
+ recordType: 'Patient',
+ name: 'Sally Smith',
+ gender: 'F',
+ birthDate: '2007-08-02'
+ }
+];
+
+window.executeAgeExample = async function () {
+ const lib = new cql.Library(measure);
+ const executor = new cql.Executor(lib);
+ const patientSource = new cql.PatientSource(window.patients);
+
+ return executor.exec(patientSource);
+};
diff --git a/examples/browser/index.html b/examples/browser/index.html
new file mode 100644
index 000000000..06c66506f
--- /dev/null
+++ b/examples/browser/index.html
@@ -0,0 +1,65 @@
+
+
+
+
+
+ CQL Execution Browser Example
+
+
+
+
+
+
CQL Execution Browser Example
+
+ This runs the AgeAtMP CQL used by the Node.js and TypeScript examples against
+ the same two patients. The CQL counts patients as InDemographic if they were
+ 2 - 17 years old at the start of the measurement period (January 1, 2013).
+