Skip to content

Instantly share code, notes, and snippets.

@Jarrio
Last active February 29, 2020 13:22
Show Gist options
  • Save Jarrio/9431cb55f73f096c0258fc6569b80ed5 to your computer and use it in GitHub Desktop.
Save Jarrio/9431cb55f73f096c0258fc6569b80ed5 to your computer and use it in GitHub Desktop.
A map that tracks length
package;
typedef TMap<A, B> = {
var length:Int;
var data:Map<A, B>;
}
@:forward abstract AMap<A, B>(TMap<A, B>) {
public var length(get, never):Int;
public function new(input) {
this = input;
}
public function set(key:A, value:B) {
this.data.set(key, value);
if (!this.data.exists(key)) {
this.length++;
}
}
public function get(key:A) {
if (this.data.exists(key)) {
return this.data.get(key);
}
return null;
}
@:arrayAccess public inline function getString(key:A) {
return this.data.get(key);
}
@:arrayAccess inline function setString(key:A, value:B) {
this.data.set(key, value);
if (!this.data.exists(key)) {
this.length++;
}
return value;
}
public function exists(key:A):Bool {
return this.data.exists(key);
}
public function remove(key:A):Bool {
if (this.data.remove(key)) {
this.length--;
return true;
}
return false;
}
public function keys() {
return this.data.keys();
}
public function iterator() {
return this.data.iterator();
}
public function keyValueIterator() {
return this.data.keyValueIterator();
}
public function toArray():Array<B> {
var data = [];
if (this == null || this.data == null) {
return [];
}
for (item in this.data) {
data.push(item);
}
return data;
}
@:from static function fromMap<A, B>(input:Map<A, B>) {
var counter = 0;
for (key => _ in input) {
counter++;
}
return new AMap({
length: counter,
data: input
});
}
private function get_length():Int {
return this.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment