Last active
May 1, 2016 04:21
-
-
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.
This file contains 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
// 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