Skip to content

Instantly share code, notes, and snippets.

@danielbenmergui
Created December 17, 2013 01:46
Show Gist options
  • Save danielbenmergui/7998539 to your computer and use it in GitHub Desktop.
Save danielbenmergui/7998539 to your computer and use it in GitHub Desktop.
This class implements a generic Set in Haxe. It is implemented with an array because it was important for me that the insertion order was preserved, so it is clearly not designed to do fast search if there are lots of elements. Code is minimal so it's self-explanatory. It does not do anything fancy but supports several convenience functions.
package gamelib;
class Set<T>
{
private var values:Array<T>;
public function new(initial_values:Array<T> = null)
{
values = [];
if(initial_values != null)
{
for(val in initial_values)
{
add(val);
}
}
}
public function clone():Set<T>
{
return new Set<T>(values);
}
public function equals(other:Set<T>):Bool
{
if(length != other.length) return false;
for(key in this)
{
if(other.has(key) == false) return false;
}
return true;
}
public function iterator():Iterator<T>
{
return values.iterator();
}
public function add(v:T):Set<T>
{
if(v != null && has(v) == false)
{
values.push(v);
}
return this;
}
public function subtract(other:Set<T>):Set<T>
{
for(key in other.values)
{
remove(key);
}
return this;
}
public function join(other:Set<T>):Set<T>
{
for(key in other.values)
{
add(key);
}
return this;
}
public function remove(v:T):Void
{
values.remove(v);
}
public function hasOnly(v:T):Bool
{
return values.length == 1 && has(v);
}
public function has(v:T):Bool
{
return Lambda.indexOf(values, v) != -1;
}
public function intersects(other:Set<T>):Bool
{
for(v in values)
{
if(other.has(v))
{
return true;
}
}
return false;
}
public function intersection(other:Set<T>):Set<T>
{
var ret = new Set<T>();
for(v in values)
{
if(other.has(v))
{
ret.add(v);
}
}
return ret;
}
public function toString():String
{
return values.join(", ");
}
public function toArray():Array<T>
{
return values.copy();
}
public function clear():Void
{
values = [];
}
public var length(get_length, never):Int;
private function get_length():Int
{
return values.length;
}
public static function setJoin<T>(from:Set<T>, other:Set<T>):Set<T>
{
var ret = from.clone();
ret.join(other);
return ret;
}
public static function setIntersect<T>(from:Set<T>, other:Set<T>):Set<T>
{
var ret = new Set<T>();
for(s in from.values)
{
if(other.has(s)) ret.add(s);
}
return ret;
}
public static function setSubtract<T>(from:Set<T>, other:Set<T>):Set<T>
{
var ret = new Set<T>();
for(s in from.values)
{
if(other.has(s) == false) ret.add(s);
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment