diff --git a/src/math/p5.Vector.js b/src/math/p5.Vector.js index 8314d6356b..425de523bb 100644 --- a/src/math/p5.Vector.js +++ b/src/math/p5.Vector.js @@ -2364,4 +2364,23 @@ p5.Vector.normalize = function normalize(v, target) { return target.normalize(); }; +/** + * Returns a string representation of a vector v. This method is useful for + * logging vectors in the console. + * Note that the static method p5.Vector.toString() overrides the existing + * inherited method Function.prototype.toString(). + */ +/** + * @method toString + * @static + * @param {p5.Vector} v the vector to stringify + * @return {String} the string representation + */ +p5.Vector.toString = function toString(v) { + // NOTE: Returning `v.toString()` directly here will cause test cases such as + // `assert.instanceOf(v, p5.Vector)` that check if something is an instance + // of a p5.Vector to fail. Using `String(v)` as a workaround. + return String(v); +}; + export default p5.Vector; diff --git a/test/unit/math/p5.Vector.js b/test/unit/math/p5.Vector.js index 7c317c4822..2aa35cab4c 100644 --- a/test/unit/math/p5.Vector.js +++ b/test/unit/math/p5.Vector.js @@ -58,7 +58,7 @@ suite('p5.Vector', function() { setup(function() { v = new p5.Vector(); }); - test('should set constant to DEGREES', function() { + test('should create instance of p5.Vector', function() { assert.instanceOf(v, p5.Vector); }); @@ -1288,4 +1288,29 @@ suite('p5.Vector', function() { ); }); }); + + suite('toString', function() { + let v, vString; + + setup(function() { + v = new p5.Vector(0, -1, 1); + vString = 'p5.Vector Object : [0, -1, 1]'; + }); + + suite('p5.Vector.prototype.toString() [INSTANCE]', function() { + test('v.toString() should return "p5.Vector Object : [0, -1, 1]"', function() { + expect(v.toString()).to.equal(vString); + }); + + test('String(v) should return "p5.Vector Object : [0, -1, 1]"', function() { + expect(String(v)).to.equal(vString); + }); + }); + + suite('p5.Vector.toString() [CLASS]', function() { + test('p5.Vector.toString(v) should return "p5.Vector Object : [0, -1, 1]"', function() { + expect(p5.Vector.toString(v)).to.equal(vString); + }); + }); + }); });