Created
September 13, 2021 14:47
-
-
Save terion-name/ea4e7a2cda6f830b8819b1e254ce91cc to your computer and use it in GitHub Desktop.
second max compare
This file contains hidden or 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
Length of random ints array: 1000000 | |
Run looper | |
res: 99999883 | |
Time elapsed: 7 | |
Run reducer | |
res: 99999883 | |
Time elapsed: 26 | |
Diff: 19 |
This file contains hidden or 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
const arr = [...new Array(1000000)].map(() => Math.round(Math.random() * 100000000)) | |
console.log('Length of random ints array:', arr.length) | |
function looper() { | |
let max = Number.MIN_VALUE; | |
let premax = Number.MIN_VALUE; | |
let len = arr.length; | |
for (let i = 0; i < len; i++) { | |
let num = arr[i]; | |
if (num !== max) { | |
if (num > max) { | |
premax = max; | |
max = num; | |
} else if (num > premax) { | |
premax = num; | |
} | |
} | |
} | |
return premax; | |
} | |
function reducer() { | |
return arr.reduce((acc, v) => (acc[1] = acc[0] > v ? Math.max(acc[1], v) : acc[0], acc[0] = Math.max(acc[0], v), acc), [Number.MIN_VALUE, Number.MIN_VALUE])[1] | |
} | |
console.log('Run looper') | |
const lst = Date.now() | |
console.log('res:', looper()) | |
const lfn = Date.now(); | |
console.log('Time elapsed:', lfn - lst) | |
console.log('Run reducer') | |
const rst = Date.now() | |
console.log('res:', reducer()) | |
const rfn = Date.now(); | |
console.log('Time elapsed:', rfn - rst) | |
console.log('Diff:', (rfn - rst) - (lfn - lst)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment