UNPKG

1.26 kBJavaScriptView Raw
1"use strict";
2
3module.exports = function( cls ) {
4 /**
5 * When you need a variable name, this method helps you to not
6 * duplicate its name.
7 * @param {string} name - Name to add to the list of already used names.
8 * @return {boolean} `true` if the name did not exist until now.
9 */
10 cls.prototype.addName = addName;
11 /**
12 * @param {string} name - Prefix of the name you want to get.
13 * @return {string} A name with a number appened to it.
14 * @example
15 * var p = new Parser();
16 * p.getFreeName("foo"); // -> "foo1"
17 * p.getFreeName("foo"); // -> "foo2"
18 * p.getFreeName("bar"); // -> "bar1"
19 * p.getFreeName("foo"); // -> "foo3"
20 */
21 cls.prototype.getFreeName = getFreeName;
22
23 return cls;
24};
25
26
27function addName( name ) {
28 if( !Array.isArray( this.names ) ) this.names = [];
29 if( this.names.indexOf( name ) > -1 ) return false;
30 this.names.push( name );
31 return true;
32};
33
34
35function getFreeName( name ) {
36 if( typeof this.namesCounters === 'undefined' ) this.namesCounters = {};
37 if( typeof this.namesCounters[name] === 'undefined' ) this.namesCounters[name] = 0;
38 var counter = this.namesCounters[name] + 1;
39 this.namesCounters[name] = counter;
40 return name + counter;
41}