blues
blues

Reputation: 5185

Haxe get array last element

In haxe is there some way to get the last element of an array other than using arr[arr.length-1] as key? I would like to avoid needing a reference to the array.

Upvotes: 3

Views: 556

Answers (2)

Justinfront
Justinfront

Reputation: 472

Two obscure ways to achive similar, Gama11 solutions seem better, but always check speeds on targets if it's important, I have used null on js test, but often better to set to a valid value, some targets you may need Null or similar.

using Test;
class Test {
    static function main() {
        var arr = [0,1,2,3];
        trace( arr.last() );
    }
    static inline function last<T>( arr: Array<T>, j=null ){
        for( i in arr ) j = i;
        return j;
    }
}

This seems to create more verbose code.

class Test {
    static function main() {
        var arr = [0,1,2,3];
        var j = null;
        arr.map((i)->j=i);
        trace(j);
    }
}

Upvotes: -1

Gama11
Gama11

Reputation: 34138

No, but you could create a static extension for it:

using ArrayExtensions;

class Main {
    static function main() {
        var a = [1, 2, 3];
        trace(a.last()); // 3
    }
}
class ArrayExtensions {
    public static inline function last<T>(a:Array<T>):T {
        return a[a.length - 1];
    }
}

Alternatively, you could overload the array access operator with a custom abstract to get Python-style negative indices:

class Main {
    static function main() {
        var a:PythonArray<Int> = [1, 2, 3];
        trace(a[-1]); // 3
    }
}

@:forward
abstract PythonArray<T>(Array<T>) from Array<T> to Array<T> {
    @:arrayAccess function get(i) {
        return if (i < 0) this[this.length - i * -1] else this[i];
    }

    @:arrayAccess function set(i, v) {
        return if (i < 0) this[this.length - i * -1] = v else this[i] = v;
    }
}

This has the downside that the array has to be typed as that abstract.

Upvotes: 7

Related Questions