Skip to content

Add class method and tests for p5.Vector.toString() #5348

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
27 changes: 26 additions & 1 deletion test/unit/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down Expand Up @@ -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);
});
});
});
});