Created
October 11, 2014 17:54
-
-
Save omnidan/7027eff00d519ecc956c to your computer and use it in GitHub Desktop.
CodeKata Kata02 Karate Chop benchmark - http://codekata.com/kata/kata02-karate-chop/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chops = {}; | |
var benchmark = false; | |
// solution 1 | |
chops['indexOf'] = function (needle, haystack) { | |
return haystack.indexOf(needle); | |
}; | |
// put your other solutions here in the same way as above | |
// testing / benchmarking code below! | |
var assert = require('assert'); | |
function testChop(chop) { | |
assert.equal(-1, chop(3, [])); | |
assert.equal(-1, chop(3, [1])); | |
assert.equal(0, chop(1, [1])); | |
assert.equal(0, chop(1, [1, 3, 5])); | |
assert.equal(1, chop(3, [1, 3, 5])); | |
assert.equal(2, chop(5, [1, 3, 5])); | |
assert.equal(-1, chop(0, [1, 3, 5])); | |
assert.equal(-1, chop(2, [1, 3, 5])); | |
assert.equal(-1, chop(4, [1, 3, 5])); | |
assert.equal(-1, chop(6, [1, 3, 5])); | |
assert.equal(0, chop(1, [1, 3, 5, 7])); | |
assert.equal(1, chop(3, [1, 3, 5, 7])); | |
assert.equal(2, chop(5, [1, 3, 5, 7])); | |
assert.equal(3, chop(7, [1, 3, 5, 7])); | |
assert.equal(-1, chop(0, [1, 3, 5, 7])); | |
assert.equal(-1, chop(2, [1, 3, 5, 7])); | |
assert.equal(-1, chop(4, [1, 3, 5, 7])); | |
assert.equal(-1, chop(6, [1, 3, 5, 7])); | |
assert.equal(-1, chop(8, [1, 3, 5, 7])); | |
return true; | |
} | |
for (var key in chops) { | |
var success = testChop(chops[key]); | |
console.log('Running unit tests on `' + key + '`:', (success === true) ? 'success' : 'FAIL'); | |
if (success !== true) delete chops[key]; | |
} | |
if (benchmark) { | |
var Benchtable = require('benchtable'); | |
var suite = new Benchtable(); | |
for (var key in chops) { | |
suite.addFunction(key, function() { | |
testChop(chops[key]); | |
}); | |
} | |
suite.addInput('Chop'); | |
suite.on('cycle', function(event) { | |
console.log(String(event.target)); | |
}); | |
suite.on('complete', function() { | |
console.log('Fastest is ' + this.filter('fastest').pluck('name')); | |
console.log(this.table.toString()); | |
}); | |
suite.run({ 'async': true }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment