From 8ed3109c2688855fd2740dbdd57451efc2b55a74 Mon Sep 17 00:00:00 2001 From: Brian J Brennan Date: Tue, 16 Oct 2012 15:30:36 -0400 Subject: [PATCH] Method for testing whether a user has enough credits to earn a badge. --- models/badge.js | 18 ++++++++++++++++++ test/badge-model.test.js | 17 +++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/models/badge.js b/models/badge.js index acfe1ab..5c8c365 100644 --- a/models/badge.js +++ b/models/badge.js @@ -95,6 +95,24 @@ Badge.findByBehavior = function findByBehavior(shortnames, callback) { return Badge.find(searchTerms, callback); }; + +/** + * Check if the credits are enough to earn the badge + * + * @param {User} user An object resembling a User object. + * @return {Boolean} whether or not the badge is earned by the credits + */ + +Badge.prototype.hasEnoughCredit = function hasEnoughCredit(user) { + return this.behaviors.map(function (behavior) { + var name = behavior.shortname; + var minimum = behavior.count; + return user.credit[name] >= minimum; + }).reduce(function (result, value) { + return result && value; + }, true); +}; + /** * Remove a behavior from the list of required behaviors for the badge * diff --git a/test/badge-model.test.js b/test/badge-model.test.js index 49c8554..1684d07 100644 --- a/test/badge-model.test.js +++ b/test/badge-model.test.js @@ -160,6 +160,23 @@ test.applyFixtures(fixtures, function () { }); }); + test('Badge#hasEnoughCredit: should have enough', function (t) { + var badge = fixtures['link-comment']; + var expect = true; + var result = badge.hasEnoughCredit({ credit: { link: 10, comment: 10 }}); + t.same(expect, result); + t.end(); + }); + + test('Badge#hasEnoughCredit: not enough', function (t) { + var badge = fixtures['link-comment']; + var expect = false; + var result = badge.hasEnoughCredit({ credit: { link: 10 }}); + t.same(expect, result); + t.end(); + }); + + test('Badge default: shortname', function (t) { var badge = new Badge({ name: 'An awesome badge!',