Skip to content

Instantly share code, notes, and snippets.

@oscarmorrison
Last active January 14, 2017 21:20
Show Gist options
  • Save oscarmorrison/526d181988aec20c6667be09698e7e82 to your computer and use it in GitHub Desktop.
Save oscarmorrison/526d181988aec20c6667be09698e7e82 to your computer and use it in GitHub Desktop.
count the words in a string, and order by popularity
let text = "There’s an interesting discussion on Quora about the differences between Golang and Scala. As a former academic with tendencies towards functional programming, I used to be very tempted by Scala.1 It offers all the functional goodness without the exoticism of Haskell, and came with reasonably good tools and frameworks. Like Clojure, it’s a functional language you can actually do some work with. The problem with Scala is, the more advanced you get, the more complicated (unreadable?) your code becomes. I remember that back in grad school the dude who was able to doodle the craziest and mathematically most challenging solution to some problem in Haskell was someone everyone looked up to. But it turns out in the “real world” simplicity always trumps virtuosity and sophistication, which is one of the many reasons I love Golang so much. A language with no “magic,” good concurrency support, great documentation and community that compiles into machine code and runs faster than Python? Yes, please. Read the whole Quora thread, though, there’s a lot of interesting stuff there."
let count = text.split(' ').reduce((count, word) => {
word = word.replace(/[^a-zA-Z]/g, '').toLowerCase();
count[word] = (count[word] || 0) + 1;
return count;
}, {})
let newCount = Object.keys(count).reduce((arr, key) => arr.concat({
word: key,
count: count[key]
}), []).sort((a,b) => b.count - a.count);
console.log(newCount);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment