Skip to content

Instantly share code, notes, and snippets.

@ScottKaye
Last active May 1, 2016 04:21
Show Gist options
  • Save ScottKaye/86fd0ec3691a58252833082716800aee to your computer and use it in GitHub Desktop.
Save ScottKaye/86fd0ec3691a58252833082716800aee to your computer and use it in GitHub Desktop.
Returns a value between 0 and 1 representing how often a word appears in a string.
// Full function
// Returns a value between 0 and 1 representing how often a word appears in a string
function wordRate(word, str) {
return str.split(word).filter(Boolean).length / str.split(" ").length;
}
// Golfed/minified, 58 bytes
const w = (w,s)=>s.split(w).filter(Boolean).length/s.split` `.length
// Usage
console.log(wordRate("blue", "blue red blue green") * 100 + "%"); // 50%
console.log(w("blue", "blue red blue green") * 100 + "%"); // 50%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment