Last active
January 7, 2021 16:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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