aboutsummaryrefslogtreecommitdiffstats
path: root/src/types/SVGNumber.js
diff options
context:
space:
mode:
authorUlrich-Matthias Schäfer <ulima.ums@googlemail.com>2018-11-06 13:48:05 +0100
committerUlrich-Matthias Schäfer <ulima.ums@googlemail.com>2018-11-06 13:48:05 +0100
commita0b13ebcacfd74b9f521110c7225bb404325bcd3 (patch)
treea07c5cc422645e31d7dfef81ce4e54f03f0945f6 /src/types/SVGNumber.js
parent9f2696e8a2cf7e4eebc1cc7e31027fe2070094fa (diff)
downloadsvg.js-a0b13ebcacfd74b9f521110c7225bb404325bcd3.tar.gz
svg.js-a0b13ebcacfd74b9f521110c7225bb404325bcd3.zip
reordered modules, add es6 build
Diffstat (limited to 'src/types/SVGNumber.js')
-rw-r--r--src/types/SVGNumber.js87
1 files changed, 87 insertions, 0 deletions
diff --git a/src/types/SVGNumber.js b/src/types/SVGNumber.js
new file mode 100644
index 0000000..bba9741
--- /dev/null
+++ b/src/types/SVGNumber.js
@@ -0,0 +1,87 @@
+import { numberAndUnit } from '../modules/core/regex.js'
+
+// Module for unit convertions
+export default class SVGNumber {
+ // Initialize
+ constructor (...args) {
+ this.init(...args)
+ }
+
+ init (value, unit) {
+ unit = Array.isArray(value) ? value[1] : unit
+ value = Array.isArray(value) ? value[0] : value
+
+ // initialize defaults
+ this.value = 0
+ this.unit = unit || ''
+
+ // parse value
+ if (typeof value === 'number') {
+ // ensure a valid numeric value
+ this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value
+ } else if (typeof value === 'string') {
+ unit = value.match(numberAndUnit)
+
+ if (unit) {
+ // make value numeric
+ this.value = parseFloat(unit[1])
+
+ // normalize
+ if (unit[5] === '%') { this.value /= 100 } else if (unit[5] === 's') {
+ this.value *= 1000
+ }
+
+ // store unit
+ this.unit = unit[5]
+ }
+ } else {
+ if (value instanceof SVGNumber) {
+ this.value = value.valueOf()
+ this.unit = value.unit
+ }
+ }
+ }
+
+ toString () {
+ return (this.unit === '%' ? ~~(this.value * 1e8) / 1e6
+ : this.unit === 's' ? this.value / 1e3
+ : this.value
+ ) + this.unit
+ }
+
+ toJSON () {
+ return this.toString()
+ }
+
+ toArray () {
+ return [this.value, this.unit]
+ }
+
+ valueOf () {
+ return this.value
+ }
+
+ // Add number
+ plus (number) {
+ number = new SVGNumber(number)
+ return new SVGNumber(this + number, this.unit || number.unit)
+ }
+
+ // Subtract number
+ minus (number) {
+ number = new SVGNumber(number)
+ return new SVGNumber(this - number, this.unit || number.unit)
+ }
+
+ // Multiply number
+ times (number) {
+ number = new SVGNumber(number)
+ return new SVGNumber(this * number, this.unit || number.unit)
+ }
+
+ // Divide number
+ divide (number) {
+ number = new SVGNumber(number)
+ return new SVGNumber(this / number, this.unit || number.unit)
+ }
+}