Skip to content

Instantly share code, notes, and snippets.

@galkin
Created June 26, 2024 09:46
Show Gist options
  • Save galkin/8e92588740fd6c59ab9abb3d4730e756 to your computer and use it in GitHub Desktop.
Save galkin/8e92588740fd6c59ab9abb3d4730e756 to your computer and use it in GitHub Desktop.
Functional VS imperative
const { randomInt } = require('crypto');
const numbers = Array.from({ length: 100_000 }).map(() => randomInt(1, 1000));
console.time('functional');
const resultByFunctional = numbers
.filter((n) => n % 2 === 0)
.reduce((a, n) => a + n, 0);
console.timeEnd('functional');
console.time('for of');
let resultForOf = 0;
for (const n of numbers) {
if (n % 2 === 0) {
resultForOf += n;
}
}
console.timeEnd('for of');
console.time('for');
let resultFor = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
resultFor += numbers[i];
}
}
console.timeEnd('for');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment