I have an array consisting of A LOT of Symbol
objects:
var symbols = {
alpha : new Symbol('alpha', 'symbol_0', 'α', 'GreekSymbol'),
beta : new Symbol('beta', 'symbol_1', 'β', 'GreekSymbol'),
gamma : new Symbol('gamma', 'symbol_2', 'γ', 'GreekSymbol'),
delta : new Symbol('delta', 'symbol_3', 'δ', 'GreekSymbol'),
... about 500 of these different types of symbols...
};
The second parameter for the Symbol
object is an ID that will be used in HTML. Since the HTML specs don't allow duplicate IDs, I want to assign each Symbol
a unique ID and still be able to know that this ID corresponds to a Symbol
. So I like the idea of having the symbol_
prefix but I don't like the idea of manually typing out symbol_0
through symbol_500
.
How should I generate unique IDs? Can I automate this process and generate a unique ID when I'm declaring the above array?
UPDATE
Is it actually a good idea to do this client-side?
Make a function that increments a counter:
function makeCounter() {
var i = 0;
return function() {
return i++;
}
}
var id = makeCounter();
Now each call to id
will return a unique value:
id(); // 0
id(); // 1
id(); // 2
id(); // 3
Use it like this:
new Symbol('alpha', 'symbol_' + id(), 'α,', 'GreekSymbol')
A more fully-featured version would allow you to specify the prefix and an optional start value:
function generateId(prefix, start) {
var i = start || 0;
return function() {
return prefix + i++;
}
}
// start the counter at 12
var id = generateId("symbol_", 12);
id();
Output:
"symbol_12"
A simple object that keeps track of the number of calls should work.
function IdGenerator(baseName) {
this.baseName = "" + baseName;
this.number = 0;
}
IdGenerator.prototype.next = function () {
return "" + this.baseName + this.number++;
};
var gen = new IdGenerator("symbol_")
for (var i = 0; i < 100; i++) {
console.log(gen.next());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With