str.wordCounts()

// ⭐️ str.wordCounts()
String.prototype.wordCounts = function(
    // word pattern
    regex = /(?=[a-zA-Z'-]*[a-zA-Z])[a-zA-Z'-]+/g
){
    const dict = new Map();
    
    this.replace(regex, match => {          
        let key = match.toLowerCase();             // lowercased
        dict.set(key, 
            dict.has(key) ? dict.get(key) + 1 : 1
        );   // count it
    });
    
    return dict;
};

// ⭐️ str.topWords(n): top n words
String.prototype.topWords = function(n){
    return [...this.wordCounts()]       // Map -> Array ⭐️
        .sort((a,b) => b[1] - a[1])     // sort: descending
        .slice(0, n)                    // top n
        .map(a => a[0])                 // [key, value] -> key
};

Last updated