commit 3faf2411824aa78b4f73027925830b99e668f2d2
parent 61ab8cd178ce3b94438e624ddae9697dbed5f88c
Author: Jacob R. Edwards <jacob@jacobedwards.org>
Date: Mon, 19 Aug 2024 09:12:16 -0700
Add unit separate and combine Units methods
The separate method takes a number and a unit system and iterates
over the units in the system from biggest to smallest, converting
as much of the number to the current unit as possible while still
being a whole number.
The combine method does the opposite, reconstructing the original
number.
Diffstat:
1 file changed, 32 insertions(+), 0 deletions(-)
diff --git a/files/floorplans/floorplan/editor.js b/files/floorplans/floorplan/editor.js
@@ -116,6 +116,38 @@ class Units {
}
return name
}
+
+ separate(units, system) {
+ let parts = []
+ let unit = this.biggest(this.systems[system])
+
+ do {
+ let n = this.get(unit)
+ if (units >= n) {
+ let amount = Math.floor(units / n)
+ units -= amount * n // not sure about floating mod in js
+ parts.push({ unit: unit, symbol: this.data[unit].symbol, amount: amount })
+ }
+ } while (units > 0 && (unit = this.data[unit].base))
+ if (units > 0) {
+ parts.push({ "amount": units })
+ }
+ return parts
+ }
+
+ combine(parts) {
+ let t = 0
+ for (let i in parts) {
+ if (!parts[i].unit) {
+ if (!parts[i].symbol) {
+ throw new Error("Requires unit or symbol")
+ }
+ parts[i].unit = this.symbols[parts[i].symbol]
+ }
+ t += this.get(parts[i].unit, parts[i].amount)
+ }
+ return t
+ }
}
export class FloorplanEditor {