Skip to content

Commit d74491d

Browse files
committed
simplify numberToIdentifer method
1 parent 8bc25f6 commit d74491d

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

lib/Template.js

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,21 @@ Template.toIdentifier = function(str) {
2020
return str.replace(/^[^a-zA-Z$_]/, "_").replace(/[^a-zA-Z0-9$_]/g, "_");
2121
};
2222

23-
var A_CODE = "a".charCodeAt(0);
24-
var Z_CODE = "z".charCodeAt(0);
25-
var AZ_COUNT = Z_CODE - A_CODE + 1;
26-
var A2_CODE = "A".charCodeAt(0);
27-
var Z2_CODE = "Z".charCodeAt(0);
28-
var AZ2_COUNT = Z2_CODE - A2_CODE + 1;
23+
var START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
24+
var START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
25+
var DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
26+
// map number to a single character a-z, A-Z or <_ + number> if number is too big
2927
Template.numberToIdentifer = function numberToIdentifer(n) {
30-
if(n < AZ_COUNT) return String.fromCharCode(A_CODE + n);
31-
if(n < AZ_COUNT + AZ2_COUNT) return String.fromCharCode(A2_CODE + n - AZ_COUNT);
32-
return "_" + (n - AZ_COUNT - AZ2_COUNT);
28+
// lower case
29+
if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
30+
31+
// upper case
32+
n -= DELTA_A_TO_Z;
33+
if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
34+
35+
// fall back to _ + number
36+
n -= DELTA_A_TO_Z;
37+
return "_" + n;
3338
};
3439

3540
Template.prototype = Object.create(Tapable.prototype);

0 commit comments

Comments
 (0)