Last active
August 29, 2015 14:27
-
-
Save colingourlay/08f78b1eded17cbac950 to your computer and use it in GitHub Desktop.
Simple unique ids from no-so-unique values
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
var uniquify = require('uniquifier')(); | |
console.log(uniquify(1)); | |
// > "1" | |
console.log(uniquify(2)); | |
// > "2" | |
console.log(uniquify(1)); | |
// > "1_1" | |
console.log(uniquify(3)); | |
// > "3" | |
console.log(uniquify(1)); | |
// > "1_2" | |
console.log(uniquify(3)); | |
// > "3_1" |
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
module.exports = function uniquifier(delimiter) { | |
var ids = {}; | |
delimiter = delimiter || '_'; | |
return function uniquify(value) { | |
var id = String(value); | |
if (ids[id] == null) { | |
ids[id] = 0; | |
return id; | |
} | |
ids[id]++; | |
return id + delimiter + ids[id]; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment