dividab / uom Goto Github PK
View Code? Open in Web Editor NEWExtensible unit of measure conversion with type safety for typescript
License: MIT License
Extensible unit of measure conversion with type safety for typescript
License: MIT License
This package is somewhat extensible because you can define new Units. However there is no clear strategy how you would package extended units and how you can use them with this package.
Today this package comes with a large set of different units. This causes a problem for some applications that wants to limit the number of units available in their application.
To solve this we could let the applications pick which units they want to work with. We could still include all the units in this package, but we need to provide a mechanism to work with a subset of the units.
For example, all units have meta-data which is registered in a global registry and this meta-data can then be used to fill UI drop-downs of available units. All units are automatically registered and available when this package is loaded. If we could disable this auto-registring and require an explicit call to register units that would give more control to applications to register the units they want to use and thus have control over what is displayed in the UI.
In addition we have some applications that use a different unit framework on the server-side and for those applications it is important that the units on the client side is the same as the supported units on the server-side.
The unit today have several concepts to describe its name/identification:
name
field in the Unit
type - Used as internal lookup identity, and for serialization.unit-name.ts
module with getName
function - Get name to display in UI, either derived or registered.unit-name.ts
module with registerLabel
function - Used to override derived name.symbol
field in BaseUnit
and AlternatveUnit
type - used as fallback to build a derived name/label when no label is registeredTo clarify what is what we should decide which concepts to keep and always use the same word to describe them.
unit-name.ts
module to unit-label.ts
unit-name.ts
module getName
function to getLabel
For the symbol
field we can either remove the function to have a fallback and default to blank when there is no registered label for a Unit, or we can rename this field to label
.
So there has been some breaking changes merged into master lately. Most of them are just to undocumented API but still there are apps using these undocumented API so we need to increment the major version. The changes I know of are recorded in the change log. If anyone know of more changes that have been done please add them too.
So any more changes we want to do before releasing 2.0.0?
Found this repo which may have some interesting ideas:
It seems like UnitFormat has been refactored to the point where it bascially does nothing. Could it be removed?
The README has an example of using UnitFormat.getUnitFormat()
that takes an Amount
but this is not how the code actually works anymore:
This is the example:
const length = Amount.create(10, Units.Meter);
const format = UnitFormat.getUnitFormat(length);
console.log(
"The amount is " +
Math.round(Amount.valueAs(Units.Inch, amount), format.decimalCount) +
" " +
format.label
);
This is how the code works:
export function getUnitFormat(
unit: Unit.Unit<unknown>,
unitsFormat: UnitFormatMap
): UnitFormat | undefined {
return unitsFormat[unit.name];
}
Many of the tests are the same code but different numbers. This can be rewritten so we separate out the data from the tests and replace all tests of the same type with a single test that loops on all the data items for that type of test.
I think it would be good to clarify which features this package supports, both in the code and in the readme. Here is a list of the ones I know we use:
We do not publish sourcemap files to npm but the js files still reference source maps which causes problems in applications which use webpack source-map-loader.
export const StandardLiterPerSecond = Unit.timesNumber(
"StandardLiterPerSecond",
3600 * 1000,
StandardCubicMeterPerHour
`);
It should be 1000 / 3600
Line 17 in 14902aa
The quantity Emission
is not registered in QuantityInfo.Therefore it is not possible to use QuantityInfo.getQuantityInfo("emission");
ACFM and ACFH labels should be capitalized
In order to be able to extend this package with new units we need to move away from having a statically defined Quantity union type that constrains Amount
. See #19 for more reasoning behind this.
Would like to have the units StandardCubicMeterPerHourPerSquareMeter
and StandardCubicFootPerSquareFeet added as IMassFlowPerArea
Due to Amount
being a generic, with a type parameter T extends Quantity.Quantity
, all Amount
s are interchangeable.
This happens since T extends Quantity.Quantity
won't give you one of the types in the union Quantity.Quantity
, but all types that extends any of them.
https://github.com/dividab/uom/blob/master/src/amount.ts#L11
In essence, this is totally OK:
const foo: Amount.Amount<Quantity.Temperature> = Amount.create(0, Units.Hour);
It is also very deceptive, because if you remove the explicity typing of foo
, its type is correct ( Amount.Amount<"Duration">
), but that will still not prevent assigning it to the wrong type.
const foo = Amount.create(0, Units.Hour);
const bar: Amount.Amount<Quantity.Temperature> = foo;
References:
If you create your own unit of an existing quantity and a format for that unit you cannot use Format.getUnitsForQuantity
since it assumes that you are using the native units.
Example:
const uom = require("uom");
const JohanPower = uom.Unit.timesNumber("JohanPower", 10000, uom.Units.Watt);
const JohanPowerFormat = uom.UnitFormat.createUnitFormat("JP", 0);
const myCustomUnits = {
Watt: uom.Units.Watt,
KiloWatt: uom.Units.KiloWatt,
JohanPower: JohanPower
};
const myCustomUnitFormats = {
Watt: uom.UnitsFormat.Meter,
KiloWatt: uom.UnitsFormat.KiloWatt,
JohanPower: JohanPowerFormat
};
const powerUnits = uom.Format.getUnitsForQuantity("Power", myCustomUnitFormats); // Crash
Instead it should accept a paramter of units, which could be defaulted to the native ones.
Ny IP-enhet för WattPerSquareMeter behöver skapas, BTUPerHourPerSquareFeet
From offline discussion with @AdamLuotonen:
Regarding Unit and Units ....
Problems:
PoundLbPerPoundLb and KilogramPerKilogram, etc. are reduced down to the same unit (One) because units are always reduced to their simplest form. This leads to trouble identifying which unit the user wants to display. The same value is displayed, but the unit label should be different (kg/kg vs lb/lb).
Known units vs. unknown units. We define a large amount of known units (MeterPerSecond, Percent, LiterPerMinute, etc.). However, the library allows creation of new units by the functions of unit-times.ts and unit-divide.ts. Units are dynamic and can be created in the applications (but it is not used a lot in practice). When serializing these new units they cannot be serialized in the form 123.22:CentiMeter
because that only works with known units.
Performance. Today, we send around instances of Unit everywhere, mainly in Amount objects. Unit contains a lot of information and may be a deep hierarchy describing how the unit is derived. When searching for the known name for the unit (for example, serialization) we run the following code:
export function getStringFromUnit (unit: Unit.Unit <Quantity>): string {
_ensureMetaAdded ();
const name = _unitToString [getUnitKey (unit)];
if (name === undefined) {
throw new error ("unknown unit" + unit);
}
return name;
}
Line 1382 in 9c7a38c
function getUnitKey (unit: Unit.Unit <Quantity>): string {
// Iterates whole array. ES6 does not have find
const foundUnit = getAllUnits () .filter (u => Unit.equals (u, unit)) [0];
if (! foundUnit) {
throw new error ("Unknown Unit" + JSON.stringify (unit));
}
return JSON.stringify (foundUnit);
}
Line 1432 in 9c7a38c
getUnitKey
is expensive (and therefore getStringFromUnit
is also expensive) because we have to walk through all units and compare the structure. Even if we did not compare the structure it would be expensive, there is still a loop over a growing list of units. Running JSON.stringify is also not free (imagine thousands of calls to this).
Well. My suggestion is that instead of passing around the representation of the units in the application, I suggest that we only pass around the known unit names. When you want to do something with the unit, the library internally merges the unit structure into a map, and performs the same code as before. Serializing and deserializing becomes straightforward, a short string of unit name.
A potential problem with this may be that some applications may be dependent on Unit's internal structure. For example, Unit.quantity is available today, but it could be replaced by a single function call getQuantityForUnit(unit)
. Another potential issue may be if someone serializes and saves Unit with JSON.stringify, and then expects to be able to deserialize it and use it with the new code. There are some tests that suggest that:
A bonus with this new approach is that you can easily see which unit a volume has when debugging. Instead of a complicated JSON structure, one gets a name.
Basically, the problem is that we want to identify units by name, but at the same time have a dynamic unit system that can build new units on the fly. I think it's enough that an application could record some own units at boot, but do not use dynamic units in the calculations?
While it is possible to generically divide any unit by any other unit and get a new unit that works for conversion, it is not possible to get the type of the new unit because we don't know which quantity it should get. To solve that UnitTimes
and UnitDivide
exists and they support dividing certain units by other units, and returning a correctly typed unit in the resulting quantity.
However it is still not possible to have a generic Amount.divide or Amount.times.
This might be solvable by using conditional types in typescript. Something like:
type Divide<Q1, Q2> = Q1 extends Length ?
Q2 extends Duration ? Velocity :
Q2 extends Length ? Dimensionless : never : never.
Each time stringToUnit is called, the string-to-unit map gets rebuilt with a lowercase key. When parsing a lot of propertyvaluesets, it adds up and becomes slow. Possible solution, the caller have responsibility of giving the unit map in with lower case keys.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.