Last active
September 1, 2018 02:42
-
-
Save stevensacks/6d24f350b18357238e7cb1b5a95746d1 to your computer and use it in GitHub Desktop.
Top Ten words in an array
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
// "word" array generator | |
const letter = () => String.fromCharCode(~~(Math.random() * 26) + 97); | |
const pair = () => `${letter()}${letter()}`; | |
const gen = length => | |
Array(length) | |
.fill() | |
.map(pair); | |
// actual counting code | |
const count = arr => | |
arr.reduce((acc, value) => { | |
if (!acc[value]) acc[value] = { value, count: 0 } | |
acc[value].count++ | |
return acc | |
}, {}); | |
const sort = (a, b) => (a.count > b.count ? -1 : a.count < b.count ? 1 : 0); | |
const topTen = counted => | |
Object.keys(counted) | |
.map(key => counted[key]) | |
.sort(sort) | |
.slice(0, 10); | |
const arrayOfWords = gen(100000); | |
const start = Date.now(); | |
const result = topTen(count(arrayOfWords)); | |
const time = Date.now() - start; | |
console.table(result); | |
console.log(`${time}ms`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment