aabb check object/function
can return object, callback, etc
by wrxsti85
JavaScript
var verify = function(str, callback){
this.contains = function(arr){
var result = true;
for(i = 0; i < arr.length; i++){
if(arr[i] != "a" && arr[i] != "b"){
result = false;
reason = 'contains additional letters';
break;
}
}
return result;
};
this.order = function(arr){
var result = true,
last = arr[0],
tog = 'a',
compare = function(a, b){
if(a === b){
return true;
}
return false;
};
if(last !== 'a'){
reason = 'out of order';
return false;
}
for(i = 1; i < arr.length; i++){
if(!compare(arr[i], last)){
tog = 'b';
}
if(!compare(arr[i], tog)){
result = false;
reason = 'out of order';
break;
}
last = arr[i];
}
return result;
};
this.amount = function(arr){
var counts = {};
for(i = 0; i < arr.length; i++) {
var num = arr[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
if(counts['a'] === counts['b']){
return true;
}
reason = 'incorrect amount';
return false;
};
if(typeof str === "undefined") return this;
if(typeof str !== "string") return {result: false, reason: 'Please enter a string!'};
var arr = str.split(''), result = true, reason = null;
if(!this.contains(arr) || !this.order(arr) || !this.amount(arr)) result = false;
if(typeof callback !== 'undefined'){
callback(result, reason);
} else {
return {result: result, reason: reason};
}
};
// Test 1
//verify('aabb', function(result, reason){
// document.body.innerHTML += result + '<br />' + reason + '<br />';
//});
// Test 2
//var test = new...