Users will enter various serials in a textarea. Each newline will indicate a new serial. Some requirements/restrictions:
- Leading and trailing white spaces are not allowed.
- White space within a serial is okay.
- Blank serials are not allowed
- I’d prefer to not use JQuery.
- Store duplicates so they can be shown to the user.
Based on my tests I have a working solution. I want to make sure I’m not missing or overlooking anything. My questions are:
- Is there a more efficient ways to check for duplicates?
- Are there any glaring test cases that my solution won’t catch?
Working Example: http://jsbin.com/ivusuj/1/
function duplicateCheck() {
var output = document.getElementById('Output');
output.innerHTML = '';
var duplicateSerials = [];
var count = 0;
var textArea = document.getElementById('Serials');
var serials = textArea.value.trim().split(/ *\n */);
for(var i = 0;i < serials.length;i++){
var serial = serials[i];
if(serials.indexOf(serial) != serials.lastIndexOf(serial) &&
duplicateSerials.indexOf(serial) == -1 && serial !== '') {
duplicateSerials.push(serial);
}
}
// For testing
output.innerHTML = '<pre>Serials:\t' + serials.toString() + "<br />" +
'Duplicates:\t' + duplicateSerials.toString() + "<br>" +
'</pre>';
}
Note: the above is for a client side check. The same check will be performed server side as well to ensure the data is valid.
Update
Solution comparison: http://jsbin.com/ivusuj/4/edit
I think you’d get significantly better performance if you used an object to determine which serials you’d seen before. Something closer to this:
Though that won’t work with serials that use periods.