-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq.ts
25 lines (24 loc) · 948 Bytes
/
q.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Quantity } from "./quantity.ts";
import { QuantityError } from "./error.ts";
/**
* Construct a `Quantity` instance from a string.
*/
export function Q(strings: string | readonly string[], ...keys: unknown[]): Quantity {
let fullString: string;
if (typeof strings == "string") {
fullString = strings;
} else {
fullString = strings[0];
for (let i = 0; i < keys.length; i++) {
fullString += String(keys[i]);
fullString += strings[i + 1];
}
}
const match = /([-+]?\d*\.?\d*)(\s*±\s*([\d\.]+))?\s*(.*)/.exec(fullString);
if (match === null) throw new QuantityError(`Unable to parse Q template string: ${fullString}`);
const magnitude = parseFloat(match[1]);
const plusMinusStr = match[3];
const plusMinus = plusMinusStr ? parseFloat(plusMinusStr) : undefined;
const units = match[4];
return new Quantity(magnitude, { units, plusMinus });
}