Skip to content

Commit

Permalink
Add Array.take method (#587)
Browse files Browse the repository at this point in the history
Takes N elements from the start or end of the array
```motoko
let array = [1, 2, 3, 4, 5];
assert Array.take(array, 2) == [1, 2];
assert Array.take(array, -2) == [4, 5];
assert Array.take(array, 10) == [1, 2, 3, 4, 5];
assert Array.take(array, -99) == [1, 2, 3, 4, 5];
```

---------

Co-authored-by: Ryan Vandersmith <ryan.vandersmith@dfinity.org>
  • Loading branch information
ZenVoich and rvanasa authored Dec 7, 2023
1 parent 4a094f9 commit be273ff
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Array.mo
Original file line number Diff line number Diff line change
Expand Up @@ -842,5 +842,26 @@ module {
i += 1;
return ?result
}
};

/// Returns a new subarray of given length from the beginning or end of the given array
///
/// Returns the entire array if the length is greater than the size of the array
///
/// ```motoko include=import
/// let array = [1, 2, 3, 4, 5];
/// assert Array.take(array, 2) == [1, 2];
/// assert Array.take(array, -2) == [4, 5];
/// assert Array.take(array, 10) == [1, 2, 3, 4, 5];
/// assert Array.take(array, -99) == [1, 2, 3, 4, 5];
/// ```
/// Runtime: O(length);
/// Space: O(length);
public func take<T>(array : [T], length : Int) : [T] {
let len = Prim.abs(length);
let size = array.size();
let resSize = if (len < size) { len } else { size };
let start = if (length > 0) 0 else size - resSize;
subArray(array, start, resSize)
}
}
40 changes: 40 additions & 0 deletions test/Array.test.mo
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,46 @@ let suite = Suite.suite(
"prevIndexOf not found",
Array.prevIndexOf<Char>('g', ['c', 'o', 'f', 'f', 'e', 'e'], 6, Char.equal),
M.equals(T.optional(T.natTestable, null : ?Nat))
),
Suite.test(
"take empty",
Array.take([], 3),
M.equals(T.array<Int>(T.intTestable, []))
),
Suite.test(
"take empty negative",
Array.take([], -5),
M.equals(T.array<Int>(T.intTestable, []))
),
Suite.test(
"take 0 elements",
Array.take([1, 2, 3], 0),
M.equals(T.array<Int>(T.intTestable, []))
),
Suite.test(
"take -0 elements",
Array.take([1, 2, 3], -0),
M.equals(T.array<Int>(T.intTestable, []))
),
Suite.test(
"take first 3 elements",
Array.take([1, 2, 3, 4, 5], 3),
M.equals(T.array<Int>(T.intTestable, [1, 2, 3]))
),
Suite.test(
"take last 3 elements",
Array.take([1, 2, 3, 4, 5], -3),
M.equals(T.array<Int>(T.intTestable, [3, 4, 5]))
),
Suite.test(
"take first 5 elements of array of size 3",
Array.take([1, 2, 3], 5),
M.equals(T.array<Int>(T.intTestable, [1, 2, 3]))
),
Suite.test(
"take last 5 elements of array of size 3",
Array.take([1, 2, 3], -5),
M.equals(T.array<Int>(T.intTestable, [1, 2, 3]))
)
]
);
Expand Down

0 comments on commit be273ff

Please sign in to comment.