Skip to content

Commit 754495d

Browse files
author
natemoo-re
committed
🛠 add toJSON() method to vector and anchor
1 parent 125bda0 commit 754495d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

js/anchor.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,36 @@ Anchor.prototype.normalizeRotate = function() {
212212
this.rotate.y = utils.modulo( this.rotate.y, TAU );
213213
this.rotate.z = utils.modulo( this.rotate.z, TAU );
214214
};
215+
216+
Anchor.prototype.toJSON = function () {
217+
var result = {};
218+
var optionKeys = this.constructor.optionKeys;
219+
220+
[...optionKeys, 'children'].forEach(function (key) {
221+
if (['addTo', 'dragRotate', 'element', 'resize'].includes(key)) return;
222+
var value = this[key];
223+
var defaults = this.constructor.defaults;
224+
225+
if (!['undefined', 'function'].includes(typeof value) && value !== defaults[key]) {
226+
if (Array.isArray(value) && value.length === 0) {
227+
return;
228+
}
229+
if (value.toJSON) {
230+
var serialized = value.toJSON();
231+
if (typeof serialized !== 'undefined') {
232+
if (key === 'scale' && serialized === 1) {
233+
return;
234+
}
235+
result[key] = serialized;
236+
}
237+
} else {
238+
result[key] = value;
239+
}
240+
}
241+
}, this);
242+
243+
return result;
244+
};
215245

216246
// ----- subclass ----- //
217247

js/vector.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,28 @@ Vector.prototype.magnitude2d = function() {
148148
Vector.prototype.copy = function() {
149149
return new Vector( this );
150150
};
151+
152+
Vector.prototype.toJSON = function() {
153+
var x = this.x;
154+
var y = this.y;
155+
var z = this.z;
156+
157+
if ( x === y && y === z ) {
158+
return ( x !== 0 ) ? x : undefined;
159+
}
160+
161+
var obj = { x: x, y: y, z: z };
162+
var result = {};
163+
164+
Object.keys( obj ).forEach( function ( key ) {
165+
var value = obj[ key ];
166+
if ( value !== 0 ) {
167+
result[ key ] = value;
168+
}
169+
})
170+
171+
return Object.keys( result ).length ? result : undefined;
172+
};
151173

152174
return Vector;
153175

0 commit comments

Comments
 (0)