Working with the SI system units in JavaScript

Dr. Viktor Sirotin
CodeX
Published in
2 min readJul 15, 2023
The International System of Units, known as the SI.

When programming in a traditional way, it’s easy to overlook the units of measurement associated with the numbers we operate on. For example, you could add meters to liters, and no compiler will help us with that. This problem is real and has already been proven to lead to accidents costing millions of dollars. (One of the stories can be found here).

To avoid this, special libraries that handle physical units in the SI system, such as meters or watts, and other units like currencies or items, can be used. One such library is KotUniL (si-units), originally developed in Kotlin. Shortly after its release, the author of the library received numerous requests to port it to JavaScript. Some time ago, as part of ensuring the library’s cross-platform compatibility, a version of the library for JavaScript was developed.

As is customary in the JavaScript world, you can include the library in your project using NPM from this repository.

Unfortunately, JavaScript does not support operator overloading, so the code looks less elegant than in Kotlin.

Let’s consider the following problem as an example: Masha was cleaning the outside of an aquarium when she accidentally bumped into a nearby vase, causing the aquarium glass to break and the water to spill out. Before this mishap, the aquarium contained 32 liters of water. Masha’s room has a length of 4 meters and a width of 4.3 meters. At what height in millimeters is the water currently located in the room, assuming it remains there and doesn’t leak out?

In Kotlin, the solution would look like this:

val s = 4.m * 4.3.m
val h = 32.l/s

In JavaScript, instead of arithmetic operations with dimensional units, we have to use functions:

var s = m.times(4).timesExp(m.times(4.3));
var v = l.times(32);
var h = v.divExp(s);

However, all the other advantages of KotUniL are preserved. You can’t add amperes to seconds, but you can multiply and divide them.

For further information about KotUniL, you can visit the repository on GitHub (see detailed usage examples in the web_app_js module). You can also read about the theoretical foundations and usage specifics of KotUniL in this series of articles:
KotUniL = SI Units + Kotlin. Part One: Introduction to KotUniL (this)

KotUniL = SI Units + Kotlin. Part Two: Advanced Features

KotUniL = SI Units + Kotlin. Part Three: When only one unit test is enough

--

--

Dr. Viktor Sirotin
CodeX
Writer for

I love programming, UML, model-driven software engineering, DSL, philosophy, mathematics, modern history and really good music. My homepage: www.sirotin.eu