Skip to content

Commit

Permalink
Add addition
Browse files Browse the repository at this point in the history
  • Loading branch information
agnoster committed Aug 16, 2012
1 parent 70ecc75 commit d734ef7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ Ratio.prototype =

return this.times(x.reciprocal())
}
, plus: function(x, d) {
if (d) x = Ratio(x, d)
else x = Ratio(x)

return Ratio(this.n * x.d + x.n * this.d, this.d * x.d)
}
}

module.exports = Ratio
27 changes: 27 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,5 +183,32 @@ describe("Ratio", function() {
ratio(1,2).neg().toString().should.equal("-1/2")
})
})

describe("Addition", function() {

it("behaves reasonably with primitive addition", function() {
(ratio(1,2) + ratio(1,4)).should.equal(0.75)
})

it("can add ratios", function() {
ratio(1,7).plus(ratio(2,7)).toString().should.equal("3/7")
})

it("can add (n,d) pair representing a ratio", function() {
ratio(1,7).plus(2,7).toString().should.equal("3/7")
})

it("can add integers", function() {
ratio(1).plus(2).toString().should.equal("3")
})

it("can add decimals", function() {
ratio(1,4).plus(0.75).toString().should.equal("1")
})

it("can add with different bases", function() {
ratio(2,3).plus(1,6).toString().should.equal("5/6")
})
})
})
})

0 comments on commit d734ef7

Please sign in to comment.