Skip to content

Instantly share code, notes, and snippets.

@markknol
Last active January 7, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markknol/1613bd4db60e6d6d1a5bfba5332f43e5 to your computer and use it in GitHub Desktop.
Save markknol/1613bd4db60e6d6d1a5bfba5332f43e5 to your computer and use it in GitHub Desktop.
A Map for enums, that require you to have all of its enum values as keys, by providing them in constructor. Stricter EnumValueMap
class Test {
static function main() {
var mySet = new EnumSet((key:MyEnum) -> switch key {
case A: [1,2];
case B: [1,2,3];
case C: [1,2,3,4];
case D: [1,2,3,15];
});
mySet[A].push(911);
trace(mySet[A]);
var cachedSet = new EnumSet((key:MyEnum) -> switch key {
case A: [1,2];
case B: [1,2,3];
case C: [1,2,3,4];
case D: [1,2,3,15];
}, true);
cachedSet[A].push(911);
trace(cachedSet[A]);
}
}
enum MyEnum {
A;
B;
C;
D;
}
abstract EnumSet<K:EnumValue,V>(EnumSetImp<K,V>) {
public function new(cb:K->V, cacheValue:Bool = false) {
this = new EnumSetImp(cb, cacheValue);
}
@:arrayAccess public inline function get(key:K) {
return if (this.cacheValue) {
var value = this.map.get(key);
if (value == null) {
value = this.cb(key);
this.map.set(key, value);
}
value;
} else {
this.cb(key);
}
}
}
private class EnumSetImp<K:EnumValue,V> {
public final map:haxe.ds.EnumValueMap<K,V> = new haxe.ds.EnumValueMap<K,V>();
public final cb:K->V;
public final cacheValue:Bool;
public function new(cb:K->V, cacheValue) {
this.cb = cb;
this.cacheValue = cacheValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment