Last active
December 28, 2015 15:38
-
-
Save nicksheffield/7522808 to your computer and use it in GitHub Desktop.
Push a string into an array. If there is already an instance of the string in the array, append an appropriate number to the end of the string first.
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
function append(arr, string){ | |
// if the string does exist in the array .. | |
if(arr.indexOf(string) != -1){ | |
var n = 2; | |
var fin = false; | |
// .. loop indefinitely until we decide we have found a usable number. | |
while(!fin){ | |
// if the string + the number doesn't exist | |
if(arr.indexOf(string+' ('+n+')') == -1){ | |
// add it | |
arr.push(string+' ('+n+')'); | |
// and end the loop. | |
fin = true; | |
// if the string + number does exist, then increase n and repeat the loop | |
}else{ | |
n += 1; | |
} | |
} | |
// if the string doesn't exist in the array .. | |
}else{ | |
// ..add it | |
arr.push(string); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment