Skip to content

Commit

Permalink
🛠 add toJSON() method to vector and anchor
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re committed Jun 7, 2019
1 parent 125bda0 commit 754495d
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
30 changes: 30 additions & 0 deletions js/anchor.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,36 @@ Anchor.prototype.normalizeRotate = function() {
this.rotate.y = utils.modulo( this.rotate.y, TAU );
this.rotate.z = utils.modulo( this.rotate.z, TAU );
};

Anchor.prototype.toJSON = function () {
var result = {};
var optionKeys = this.constructor.optionKeys;

[...optionKeys, 'children'].forEach(function (key) {

This comment has been minimized.

Copy link
@natemoo-re

natemoo-re Jun 7, 2019

Oops, some ES6 snuck in here. I will remove it.

if (['addTo', 'dragRotate', 'element', 'resize'].includes(key)) return;
var value = this[key];
var defaults = this.constructor.defaults;

if (!['undefined', 'function'].includes(typeof value) && value !== defaults[key]) {
if (Array.isArray(value) && value.length === 0) {
return;
}
if (value.toJSON) {
var serialized = value.toJSON();
if (typeof serialized !== 'undefined') {
if (key === 'scale' && serialized === 1) {
return;
}
result[key] = serialized;
}
} else {
result[key] = value;
}
}
}, this);

return result;
};

// ----- subclass ----- //

Expand Down
22 changes: 22 additions & 0 deletions js/vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,28 @@ Vector.prototype.magnitude2d = function() {
Vector.prototype.copy = function() {
return new Vector( this );
};

Vector.prototype.toJSON = function() {
var x = this.x;
var y = this.y;
var z = this.z;

if ( x === y && y === z ) {
return ( x !== 0 ) ? x : undefined;
}

var obj = { x: x, y: y, z: z };
var result = {};

Object.keys( obj ).forEach( function ( key ) {
var value = obj[ key ];
if ( value !== 0 ) {
result[ key ] = value;
}
})

return Object.keys( result ).length ? result : undefined;
};

return Vector;

Expand Down

0 comments on commit 754495d

Please sign in to comment.