Skip to content

Instantly share code, notes, and snippets.

@greduan
Created June 1, 2014 19:52
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 greduan/332b61882567c66d14ea to your computer and use it in GitHub Desktop.
Save greduan/332b61882567c66d14ea to your computer and use it in GitHub Desktop.
Finds the shortest unique string for a string in an array of strings. Meant to be used with hashes
/**
* Big thanks to Bruce who figured this out for me. What this function does is
* give you the shortest unique prefix of the strings (hashes) that you give it
* in the array.
*
* Args: {array} hashesArr, {function} callback
* Returns: {array} minHashes, through callback. Something like this:
*
* [ '1c',
* '28d',
* '4',
* '288',
* '19',
* 'f',
* '8' ]
*/
function minHash(hashesArr, callback) {
var minHashes = new Array();
hashesArr.forEach(function (val, index) {
var min = 0;
hashesArr.forEach(function (val2, index2) {
if (index === index2) return;
var i = 0;
while (val[i] === val2[i]) {
if(i >= min) min = i + 1;
i++;
}
});
minHashes[index] = val.substr(0, min + 1);
});
return callback(minHashes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment