Skip to content

Commit

Permalink
Add color stickiness and rollback to an incremental iteration on colo…
Browse files Browse the repository at this point in the history
…r available
  • Loading branch information
lchenay committed Dec 22, 2016
1 parent 280a64d commit 9f4404f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
24 changes: 18 additions & 6 deletions src/debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ exports.formatters = {};

var prevTime;

/**
* Incremental cursor to have better color distribution
*/

var prevColor = 0;

/**
* Colors stickiness
*/

var previousColors = {};

/**
* Select a color.
* @param {String} namespace
Expand All @@ -42,14 +54,14 @@ var prevTime;
*/

function selectColor(namespace) {
var hash = 0, i;

for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
var previousColor = previousColors[namespace];
if (previousColor !== undefined) {
return previousColor;
}

return exports.colors[Math.abs(hash) % exports.colors.length];
previousColors[namespace] = exports.colors[prevColor++ % exports.colors.length];

return previousColors[namespace];
}

/**
Expand Down
27 changes: 20 additions & 7 deletions test/debug_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ var chai
, debug
, sinon
, sinonChai;

if (typeof module !== 'undefined') {
chai = require('chai');
expect = chai.expect;

debug = require('../src/index');
sinon = require('sinon');
sinonChai = require("sinon-chai");
Expand All @@ -20,28 +20,28 @@ if (typeof module !== 'undefined') {

describe('debug', function () {
var log = debug('test');

log.log = sinon.stub();

it('passes a basic sanity check', function () {
expect(log('hello world')).to.not.throw;
});

context('with log function', function () {

beforeEach(function () {
debug.enable('test');
log = debug('test');
});

it('uses it', function () {
log.log = sinon.stub();
log('using custom log function');

expect(log.log).to.have.been.calledOnce;
});
});

describe('custom functions', function () {
var log;

Expand All @@ -59,4 +59,17 @@ describe('debug', function () {
});
});
});

describe('colors stickiness', function () {
beforeEach(function () {
debug.enable('test');
});

it('should return same color for same namespace', function () {
var log1 = debug('test');
var log2 = debug('test');

expect(log1.color).to.equal(log2.color);
});
});
});

0 comments on commit 9f4404f

Please sign in to comment.