Last active
April 5, 2018 19:14
-
-
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
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
/** | |
* 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