Suppose that we have a list of employees. Everytime, we want to add new employee into this list, the name of the employee will be generated with the following rules:
Here is my code snippet by Javascript:
Can check here: https://jsfiddle.net/avebff8t/2/
- the name of the new one is set to "[originalname] 1" - in case the name already exist, "[originalname] 2" is used, and so on.
Here is my code snippet by Javascript:
var employees =[ {id: 1, name: 'name'}, {id: 2, name: 'name 1'}, {id: 3, name: 'name 2'}, {id: 5, name: 'name 4'} ]; var commonUtils = { isExistName: function(_name, _collection, _prop) { for(var i = 0; i< _collection.length; i++){ if(_collection[i][_prop].localeCompare(_name)==0){ return true; } } return false; }, generateNewName: function(_name, _collection, _prop){ var i = 1; var searching = true; while (searching) { var newName = _name+ " " + i; if (!this.isExistName(newName, _collection, _prop)) { return newName; } i++; }; } }; console.log("newName: " + commonUtils.generateNewName("name", employees, 'name'))
Can check here: https://jsfiddle.net/avebff8t/2/
Comments
Post a Comment