Skip to content

Commit

Permalink
use array.resize for setLength
Browse files Browse the repository at this point in the history
  • Loading branch information
charlesisfeline authored Mar 30, 2024
1 parent 4da7a3e commit 4d95089
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 18 deletions.
22 changes: 4 additions & 18 deletions flixel/util/FlxArrayUtil.hx
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,11 @@ class FlxArrayUtil
* @param array The array.
* @param newLength The length you want the array to have.
*/
@:generic
public static function setLength<T>(array:Array<T>, newLength:Int):Array<T>
public static inline function setLength<T>(array:Array<T>, newLength:Int):Array<T>
{
if (newLength < 0)
return array;

var oldLength:Int = array.length;
var diff:Int = newLength - oldLength;
if (diff >= 0)
return array;

#if flash
untyped array.length = newLength;
#else
diff = -diff;
for (i in 0...diff)
array.pop();
#end

if (newLength > 0)
array.resize(newLength);

return array;
}

Expand Down
7 changes: 7 additions & 0 deletions tests/unit/src/flixel/util/FlxArrayUtilTest.hx
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,11 @@ class FlxArrayUtilTest
Assert.isTrue([0, 1, 2, 3, 4, 5].safeSwap(0, 2).equals([2, 1, 0, 3, 4, 5]));
Assert.isTrue([0, 1, 2, 3, 4, 5].safeSwap(1, 6).equals([0, 1, 2, 3, 4, 5]));
}

@Test
function testSetLength()
{
Assert.isTrue([0, 1, 2, 3, 4, 5].setLength(3).equals([0, 1, 2]));
Assert.isTrue([0, 1, 2].setLength(5).equals([0, 1, 2, 0, 0]));
}
}

0 comments on commit 4d95089

Please sign in to comment.