Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Array.take method #587

Merged
merged 4 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -469,6 +469,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