Set Subtraction (v2)

Revision 2 of this benchmark created by Andy on


Description

Various methods for finding the set that is the relative complement of "buildings" in "constructions"

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

var constructions = [{
        Name: "Mess hall",
        SqFt: 5000
    }, {
        Name: "Infirmary",
        SqFt: 2000
    }, {
        Name: "Bungalow",
        SqFt: 2000
    }, {
        Name: "HQ",
        SqFt: 2000
    }];
    
    var buildings = [{
        Name: "Infirmary",
        SqFt: 2000
    }, {
        Name: "HQ",
        SqFt: 2000
    }];
    
    
    function getValues(arr, key) {
        var out = [];
        for (var i = 0, l = arr.length; i < l; i++) {
          out.push(arr[i][key]);
        }
        return out;
    } 
       
        function notFoundIn(arr, arr2) { 
          // grab the names of the buildings
          var buildings = getValues(arr2, 'Name');
    
          // grab the names from the construction objects and filter
          // those that are not in the building array
          return getValues(arr, 'Name').filter(function (el) {
            return buildings.indexOf(el) === -1;
          });
        }
    
    if (!Array.prototype.notFoundIn) {
        Array.prototype.notFoundIn = function (inThisArray, key) {
            var thisArr = key ? getValues(this, key) : this;
            var arrIn = key ? getValues(inThisArray, key) : inThisArray;
            var out = [];
            for (var i = 0, l = thisArr.length; i < l; i++) {
                if (arrIn.indexOf(thisArr[i]) === -1) {
                    out.push(thisArr[i]);
                }
            }
            return out;
        }
    }
    // jquery grep functionized
    if (!Array.prototype.subtractSet) {
      Array.prototype.subtractSet = function (set, key) {
    return $.grep(this, function (a) {
        return $.grep(set, function (b) {
            return key ? b[key] === a[key] : a === b;
        }).length == 0;
    });
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
nested jQuery.grep() for relative complement of "buildings" in "constructions"
var foundBuildings = $.grep(constructions, function (a) {
    return $.grep(buildings, function (b) {
        return b.Name === a.Name
    }).length == 0;
});
ready
mapped index lookup with array.filter()
var foundBuildings = notFoundIn(constructions, buildings);
ready
extending Array with set relative complement function
constructions.notFoundIn(buildings, 'Name');
ready
jQuery.grep() set difference
constructions.subtractSet(buildings, 'Name');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.