test.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*jshint node:true, laxcomma:true */
  2. /*global describe:true, it:true */
  3. "use strict";
  4. var debug = require('debug')('rwc:test');
  5. var assert = require('assert');
  6. var rwc = require('../lib/random-weighted-choice');
  7. var randomCounter = 0;
  8. var randomValues = [0,0.19,0.5,0.7,0.9];
  9. var randomMock = function(values, reset) {
  10. if(typeof(values)=="undefined") values = randomValues;
  11. if (typeof(reset)=="undefined") reset = false;
  12. if (reset) randomCounter = 0;
  13. return values[randomCounter++];
  14. };
  15. describe('Temperature 50', function () {
  16. var table = [
  17. { weight: 1, id: "item1"} // Element 1
  18. , { weight: 1, id: "item2"} // Element 2
  19. , { weight: 4, id: "item3"} // Element with a 4 times likelihood
  20. , { weight: 2, id: "item4"} // Element 4
  21. , { weight: 2, id: "item5"}
  22. ];
  23. it('should return "item1"', function (){
  24. assert.equal('item1', rwc(table,null,randomMock));
  25. });
  26. it('should return "item2"', function (){
  27. assert.equal('item2', rwc(table,null,randomMock));
  28. });
  29. it('should return "item3"', function (){
  30. assert.equal('item3', rwc(table,null,randomMock));
  31. });
  32. it('should return "item4"', function (){
  33. assert.equal('item4', rwc(table,null,randomMock));
  34. });
  35. it('should return "item5"', function (){
  36. assert.equal('item5', rwc(table,null,randomMock));
  37. });
  38. });
  39. describe('Empty table', function () {
  40. it('should return null', function () {
  41. assert.equal(null, rwc([]));
  42. });
  43. });
  44. describe('One element', function () {
  45. it('should return the element', function () {
  46. assert.equal('a', rwc([{weight:1, id: 'a'}]));
  47. });
  48. });
  49. describe('No weight', function () {
  50. it('should return null', function () {
  51. assert.equal(null, rwc([{weight:0, id: 'a'}]));
  52. });
  53. });
  54. module.exports.random = randomMock;