Skip to content

Commit

Permalink
Added centroid static method
Browse files Browse the repository at this point in the history
  • Loading branch information
crashtheuniverse committed Jan 21, 2020
1 parent 3704130 commit c841ff6
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
33 changes: 31 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ Mathware
A small compact library for algebra and vector manipulation for Node.js.
Tries to be small and have no dependencies.

## Note
The library is permissive on purpose. It won't check a v2 vs a v3 sum.
It is on purpose to avoid the performance penalty hit.

I'll add soon JSDoc so at least you have those checks upfront.

Download
--------
Expand Down Expand Up @@ -40,7 +45,7 @@ You can also create with a shorthand
var v3 = mw.v3(1.0, 2.0, 3.0); // Vec3 {x:1 , y:2, z:3 }
```

Document
Documentation
--------

You can select the vector modules out for your need
Expand All @@ -66,6 +71,16 @@ var aNewVector = mw.vec3.add(v1, v2);
// v1{ 1,1,1} , v2{ 0,0, 1}, aNewVector {1,1,2}
```

## Chaining

All the in place methods that should return a vector, will return this
```js
var v1 = mw.v2(1,2)
.scalarMultiply(2)
.add( mw.v2(-2, -2) );
//v1 { x: 0, y : 2 }
```

### Instance Methods ###

**constructor**
Expand Down Expand Up @@ -123,4 +138,18 @@ Compares the two vectors and returns true if equal

### Static Methods ###

There is a static method version for every instance method that return a vector.
There is a static method version for every instance method that return a vector. also

**centroid(ary)**

Returns the centroid of an array of vectors

```js
//Define a square of 10x10
let v1 = mw.v2(0,0);
let v2 = mw.v2(10,10);
let v3 = mw.v2(0,10);
let v4 = mw.v2(10,0);
console.dir(mw.vec2.centroid([v1,v2,v3,v4])); // {x:5, y:5}
```

7 changes: 7 additions & 0 deletions lib/vec2.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,13 @@ class Vec2 {
return v1.squaredDistance(v2);
}

static centroid(vectors) {
if(vectors == undefined || vectors.length == 0) return new this;
let c = vectors.reduce( (sum, v) => {
return this.add(sum, v);
}, new this);
return c.scalarMultiply(1.0 / vectors.length);
}
}

module.exports = Vec2;
Expand Down
7 changes: 7 additions & 0 deletions lib/vec3.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,13 @@ class Vec3 {
return v1.squaredDistance(v2);
}

static centroid(vectors) {
if(vectors == undefined || vectors.length == 0) return new this;
let c = vectors.reduce( (sum, v) => {
return this.add(sum, v);
}, new this);
return c.scalarMultiply(1.0 / vectors.length);
}
}

module.exports = Vec3;
Expand Down

0 comments on commit c841ff6

Please sign in to comment.