Chapter 10: Optimizing Synchronous Functions samples

This commit is contained in:
Beth Griggs
2020-08-30 23:30:37 +01:00
parent ef82559a0e
commit 575ab40a00
5 changed files with 88 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
const benchmark = require("benchmark");
const slow = require("./slow");
const loop = require("./loop");
const suite = new benchmark.Suite();
const maxNumber = 100; // number to pass through to sumOfSquares()
suite.add("slow", function () {
slow(maxNumber);
});
suite.add("loop", function () {
loop(maxNumber);
});
suite.on("complete", printResults);
suite.run();
function printResults() {
this.forEach((benchmark) => {
console.log(benchmark.toString());
});
console.log("Fastest implementation is", this.filter("fastest")[0].name);
}
+10
View File
@@ -0,0 +1,10 @@
function sumOfSquares(maxNumber) {
let i = 0;
let sum = 0;
for (i; i <= maxNumber; i++) {
sum += i ** 2;
}
return sum;
}
module.exports = sumOfSquares;
+27
View File
@@ -0,0 +1,27 @@
{
"name": "optimize-sync",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"benchmark": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/benchmark/-/benchmark-2.1.4.tgz",
"integrity": "sha1-CfPeMckWQl1JjMLuVloOvzwqVik=",
"requires": {
"lodash": "^4.17.4",
"platform": "^1.3.3"
}
},
"lodash": {
"version": "4.17.20",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
"integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA=="
},
"platform": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
"integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "optimize-sync",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"benchmark": "^2.1.4"
}
}
+13
View File
@@ -0,0 +1,13 @@
function sumOfSquares(maxNumber) {
const array = Array.from(Array(maxNumber + 1).keys());
return array
.map((number) => {
return number ** 2;
})
.reduce((accumulator, item) => {
return accumulator + item;
});
}
module.exports = sumOfSquares;