Skip to content

Instantly share code, notes, and snippets.

@inactivist
Last active April 5, 2018 19:14
Show Gist options
  • Save inactivist/7614182 to your computer and use it in GitHub Desktop.
Save inactivist/7614182 to your computer and use it in GitHub Desktop.
Generate w-shingles from a string or array in JavaScript. https://en.wikipedia.org/wiki/W-shingling
/**
* Make w-shingles from a source string or array.
* @param {string} collection The collection (array or string) to shingle.
* @param {string} size The shingle size (4 for 4-shingles, etc.)
* @return {array} An array of shingles.
*/
function shingle(collection, size) {
var shingles = [];
for (var i=0; i<collection.length-size+1; i++) {
shingles.push(collection.slice(i, i+size));
}
return shingles;
}
var testString = "a rose is a rose is a rose";
console.log(testString);
// Shingle words
console.log("Words:", shingle(testString.split(' '), 4));
// Shingle characters
console.log("Characters:", shingle(testString, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment