Skip to content

Commit 02dbf41

Browse files
committed
Added nextUid() function for unified way of generating IDs in angular
1 parent 7f6fe33 commit 02dbf41

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/Angular.js

+31
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ var $$element = '$element',
114114
angularCallbacks = extensionMap(angular, 'callbacks'),
115115
nodeName_,
116116
rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/,
117+
uid = ['0', '0', '0'];
117118
DATE_ISOSTRING_LN = 24;
118119

119120
/**
@@ -188,6 +189,36 @@ function formatError(arg) {
188189
return arg;
189190
}
190191

192+
/**
193+
* @description
194+
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
195+
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
196+
* the number string gets longer over time, and it can also overflow, where as the the nextId
197+
* will grow much slower, it is a string, and it will never overflow.
198+
*
199+
* @returns an unique alpha-numeric string
200+
*/
201+
function nextUid() {
202+
var index = uid.length;
203+
var digit;
204+
205+
while(index) {
206+
index--;
207+
digit = uid[index].charCodeAt(0);
208+
if (digit == 57 /*'9'*/) {
209+
uid[index] = 'A';
210+
return uid.join('');
211+
}
212+
if (digit == 90 /*'Z'*/) {
213+
uid[index] = '0';
214+
} else {
215+
uid[index] = String.fromCharCode(digit + 1);
216+
return uid.join('');
217+
}
218+
}
219+
uid.unshift('0');
220+
return uid.join('');
221+
}
191222

192223
/**
193224
* @workInProgress

test/AngularSpec.js

+18
Original file line numberDiff line numberDiff line change
@@ -583,4 +583,22 @@ describe('angular', function(){
583583
});
584584
}
585585
});
586+
587+
588+
describe('nextUid()', function(){
589+
it('should retun new id per call', function(){
590+
var last;
591+
var current;
592+
var count = 100;
593+
594+
last = nextUid();
595+
while(count--) {
596+
current = nextUid();
597+
expect(current.match(/[\d\w]+/)).toBeTruthy();
598+
expect(last).not.toEqual(current);
599+
last = current;
600+
}
601+
});
602+
});
603+
586604
});

0 commit comments

Comments
 (0)