Created
December 5, 2012 08:37
-
-
Save jayphelps/4213882 to your computer and use it in GitHub Desktop.
IdentifierBuilder - build the shortest possible unique names/keys. Helpful for compilers/minifiers/etc
This file contains hidden or 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
/** | |
* MIT Licensed (but really, do what you want with it) | |
* | |
* | |
* Usage: | |
* | |
* `IdentifierBuilder.create()` === `a` | |
* `IdentifierBuilder.create()` === `b` | |
* `IdentifierBuilder.create()` === `c` | |
* ... | |
* ... | |
* `IdentifierBuilder.create()` === `aa` | |
* `IdentifierBuilder.create()` === `ab` | |
* `IdentifierBuilder.create()` === `ac` | |
* | |
* You can use `.save()` and `.restore()` to | |
* push/pop scopes. | |
* | |
* `.createUniqueName(Number)` is used internally | |
* but could be handy for others. Pass it a count | |
* number and it will build a name assuming that | |
* number of names have been built prior. | |
* | |
* `IdentifierBuilder.createUniqueName(5000) === `gji` | |
*/ | |
var IdentifierBuilder = (function () { | |
var letters = "abcdefghijklmnopqrstuvwxyz".split(""), | |
letterCount = letters.length, | |
letterLastIndex = letterCount - 1; | |
function createUniqueName(i) { | |
if (i === undefined) return undefined; | |
var name = ""; | |
var counter = -1; | |
while (i > letterLastIndex) { | |
i -= letterCount; | |
counter++; | |
} | |
if (counter > -1) { | |
name += createUniqueName(counter); | |
} | |
i = Math.floor(i); | |
name += letters[i]; | |
return name; | |
} | |
var excludes = []; | |
var IdentifierBuilder = { | |
count: -1, | |
stack: [], | |
excludes: excludes, | |
createUniqueName: createUniqueName, | |
save: function () { | |
this.stack.push(IdentifierBuilder.count); | |
IdentifierBuilder.count = -1; | |
}, | |
restore: function () { | |
if (!this.stack.length) return; | |
IdentifierBuilder.count = this.stack.pop(); | |
}, | |
create: function () { | |
IdentifierBuilder.count++; | |
var name = createUniqueName(IdentifierBuilder.count); | |
if (excludes.indexOf(name) !== -1) { | |
return this.create(); | |
} else { | |
return name; | |
} | |
} | |
}; | |
return IdentifierBuilder; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment