A set class for MooTools
JavaScript
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
externals
LICENSE.txt
Set.js
index.html
readme.textile
test.js

readme.textile

A Set implementation for MooTools

How it works

JavaScript has no sane notion of equality when comparing Arrays or Objects. This is particularly frustrating in light of the ubiquitous use of JSON. For example:

[1, 2, 3] != [1, 2, 3]
{first:"Bob", last:"Smith"} != {first:"Bob", last:"Smith"}

One easy workaround is to JSON.encode the arrays before comparing them. This works reasonably well as long as you don’t have Objects in your array.

This Set implementation can deal with Objects. It converts Objects into an array of arrays, one for each key value pair. It does so recursively. In order to allow for comparison, these arrays are sorted by the original key.

{first:"Bob", last:"Smith"} -> [['first', 'Bob'], ['last', 'Smith']]

Then we can JSON encode this array to do equality checks. You can see this for yourself by using $hash directly.

$hash({first:"Bob", last:"Smith"}) == $hash({last:"Smith", first:"Bob"})

Features

Set supports intersection, union, and difference. These return new Set instances. If you want the result as an JavaScript Array you can use aintersection, aunion, adifference.

var set1 = new Set([1, 2, [3, 4], 9]);
var set2 = new Set([1, [3, 4], 9, 5]);
set1.aintersection(set2) -> [1, [3, 4], 9]

For large collections, sets are much faster than using things like Array.contains or interating through the array as long as you are willing to pay the cost of initializing the Set. For large collections which are searched or compared frequently Sets are particularly useful.

$hash is also handy. You can now sanely check if any two JavaScript Objects are equal. Note this isn’t useful or desirable for MooTools class instances. The standard JavaScript Object equality check is the desired behavior.