Skip to content

Instantly share code, notes, and snippets.

@Jarrio
Last active February 7, 2020 13:43
Show Gist options
  • Save Jarrio/cd7fab738399c52204fc1d40759f9853 to your computer and use it in GitHub Desktop.
Save Jarrio/cd7fab738399c52204fc1d40759f9853 to your computer and use it in GitHub Desktop.
Abstract for array allows for backwards referencing indexes, first/last getters and a built in backwards loop!
package utilities;
@:forward abstract CArray<T>(Array<T>) {
public var last(get, never):T;
public var first(get, never):T;
public function new(value) {
this = value;
}
public function rewind(data:T->Void, end:Int = 0) {
var i = this.length;
while(i-- > 0) {
data(this[i]);
if (end > 0 && i == (this.length - end)) {
break;
}
}
}
@:arrayAccess private function getRange(range:IntIterator) {
return @:privateAccess this.slice(range.min, range.max + 1);
}
@:arrayAccess private function get(key:Int) {
return (key >= 0) ? this[key] : this[this.length + key];
}
@:from static function fromArray<T>(value:Array<T>):CArray<T> {
return new CArray<T>(value);
}
private function get_first():T {
return this[0];
}
private function get_last():T {
return this[this.length - 1];
}
}
@Jarrio
Copy link
Author

Jarrio commented Jun 12, 2019

Output:

Test.hx:29: Last: 5
Test.hx:30: First: 1
Test.hx:31: 2nd from last: 4

@Jarrio
Copy link
Author

Jarrio commented Jun 13, 2019

var array:CArray<Int> = [1, 2, 3, 4, 5];
trace(array[1...3]); //[1,2,3]
array.rewind((data) -> trace(data)); // You can even add an end condition!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment