JSFiddle - React, Tailwind, and code Playground
by soulwire
JavaScript
/**
* Given a string of text and n-gram size, returns an object containing frequency of n-grams
*/
function nGrams(text, n) {
const words = text.toLowerCase().split(/\s+/)
const result = {};
for (let i = 0; i <= words.length - n; i++) {
const gram = words.slice(i, i + n).join(' ');
result[gram] = (result[gram] || 0) + 1;
}
return result;
}
console.log(nGrams("The quick fox jumped over the quick fox", 2));
// {the quick: 2, quick fox: 2, fox jumped: 1, jumped over: 1, over the: 1}