Skip to content

Commit

Permalink
feat: inverse()
Browse files Browse the repository at this point in the history
  • Loading branch information
HarryGogonis committed Jun 26, 2017
1 parent 3fd5472 commit 497e817
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,44 @@ class Matrix extends Map {
determinant () {
return (this.get('a') * this.get('d')) - (this.get('b') * this.get('c'))
}

/**
* @return {boolean} true if matrix is invertible
*/
isInvertible () {
return this.determinant() !== 0
}

/**
* @return {Matrix} inverse of the current matrix.
* @throws Will throw an error if the matrix is not invertable
*/
inverse () {
if (this.isIdentity()) {
return new Matrix()
}

if (!this.isInvertible()) {
throw new Error('Matrix is not invertible.')
}

const dt = this.determinant()
const a = this.get('a')
const b = this.get('b')
const c = this.get('c')
const d = this.get('d')
const e = this.get('e')
const f = this.get('f')

return this.withMutations(matrix => matrix
.set('a', d / dt)
.set('b', -b / dt)
.set('c', -c / dt)
.set('d', a / dt)
.set('e', ((c * f) - (d * e)) / dt)
.set('f', -((a * f) - (b * e)) / dt)
)
}
}

export default Matrix
16 changes: 16 additions & 0 deletions src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,19 @@ describe('determinant', () => {
expect(new Matrix().determinant()).toBe(1)
expect(new Matrix(1, 1, 1, 1, 0, 0).determinant()).toBe(0)
})

describe('isInvertable', () => {
expect(mockMatrix.isInvertible()).toBe(true)
expect(new Matrix().isInvertible()).toBe(true)
expect(new Matrix(1, 1, 1, 1, 0, 0).isInvertible()).toBe(false)
})

describe('inverse', () => {
const mockMatrixInverted = new Matrix(-2, 1, 1.5, -0.5, 1, -2)

expect(mockMatrix.inverse().equals(mockMatrixInverted)).toBe(true)
expect(new Matrix().inverse().equals(new Matrix())).toBe(true)
expect(() => {
new Matrix(1, 1, 1, 1, 0, 0).inverse()
}).toThrow()
})

0 comments on commit 497e817

Please sign in to comment.