Skip to content

Instantly share code, notes, and snippets.

@renatocassino
Created August 8, 2018 02:04
Show Gist options
  • Save renatocassino/49f71ddf4d188fb20e75b96ba33ecc05 to your computer and use it in GitHub Desktop.
Save renatocassino/49f71ddf4d188fb20e75b96ba33ecc05 to your computer and use it in GitHub Desktop.
2048-addNumberBenchmark.js
// npm i --save benchmark
const Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
const addNumberFunc = (board, point, number=2)=>{
const line = board[point[0]];
return [
...board.slice(0, point[0]),
[
...line.slice(0, point[1]),
number,
...line.slice(point[1]+1, line.length)
],
...board.slice(point[0]+1, board.length)
];
}
const addNumber = (board, point, number=2) => {
return board.map(
(line, columnIdx) => line.map((block, lineIdx) =>
columnIdx === point[0] && lineIdx === point[1] ? number : block
));
};
const board = [[2, 2, 2, 2], [0, 4, 16, 16], [8, 8, 0, 32], [0, 0, 0, 64]];
// add tests
suite
.add('Using slice', function() {
addNumberFunc(board, [1, 1]);
})
.add('Using map', function() {
addNumber(board, [1, 1]);
})
.on('complete', function() {
this.forEach((bench) => {
console.log(`Test ${bench.name}`);
console.log(`Runned ${bench.count} times`);
console.log('============');
});
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true, maxTime: 20 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment