Skip to content

Instantly share code, notes, and snippets.

@GlauberF
Last active July 14, 2022 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GlauberF/627c8fc1ab5890b402dd2e2b6888f1a4 to your computer and use it in GitHub Desktop.
Save GlauberF/627c8fc1ab5890b402dd2e2b6888f1a4 to your computer and use it in GitHub Desktop.
NGram
//////////////////////////////////////
// Example
// nGram(2)('Brasil');
/////////////////////////////////////
/**
* Factory returning a function that converts a value string to n-grams.
*
* @param {number} n
*/
function nGram(n) {
if (
typeof n !== 'number' ||
Number.isNaN(n) ||
n < 1 ||
n === Number.POSITIVE_INFINITY
) {
throw new Error('`' + n + '` is not a valid argument for `n-gram`')
}
return grams
/**
* Create n-grams from a given value.
*
* @template {string|string[]} T
* @param {T} [value]
* @returns {T[]}
*/
function grams(value) {
/** @type {T[]} */
var nGrams = []
/** @type {number} */
var index
/** @type {string|string[]} */
var source
if (value === null || value === undefined) {
return nGrams
}
source = value.slice ? value : String(value)
index = source.length - n + 1
if (index < 1) {
return nGrams
}
while (index--) {
// @ts-ignore
nGrams[index] = source.slice(index, index + n)
}
return nGrams
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment