﻿// 

// Prototype a filter method for JS Array
Array.prototype.filter = function(afCriteria) {
    
    // Get length of criteria function array
    var afLength = afCriteria.length;
    
    if (afLength == 0) {
        return this;
    }
    
    // Define results array
    var aResults = [];
    
    // Loop through array
    for (var i=0; i<this.length; i++) {
        
        // Set passes flag to false before checking
        var bPasses = true;
    
        // Loop through criteria function array
        for (var j=0; j<afLength && bPasses; j++) {
            
            // Check that the item doesn't pass
            if (!afCriteria[j].check(this[i])) {
                
                // Set a flag to not include this element
                var bPasses = false;
            }
        }
        
        // If the result passes, add it to the results
        if (bPasses) {
            aResults.push(this[i]);
        }
    }
    
    // Return results array
    return aResults;
}


// Create ByProperty filter type
function PropertyEquals(sProperty, value) {
    this.sProperty = sProperty;
    this.value = value;
    
    // function ran by filter
    this.check = function(item) {
        
        // if the property doesn't exist, return false
        if (typeof(item[this.sProperty]) == "undefined") {
            return false;
        }
        
        // Check the criteria
        if (item[this.sProperty] === this.value) {
            return true;
        } else {
            return false;
        }
    }
    
    // Return this object
    return this;
}