dfinity / motoko-base

The Motoko base library
Apache License 2.0
483 stars 99 forks source link

Add `Array.take` method #587

Closed ZenVoich closed 11 months ago

ZenVoich commented 1 year ago

Takes N elements from the start or end of the array

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];
ZenVoich commented 1 year ago

Any feedback would be appreciated)

ZenVoich commented 1 year ago

Anything?

rvanasa commented 11 months ago

The more general signature seems okay to me because it's still possible to pass a Nat without any additional conversions (example). The +/- convention is reasonably intuitive for developers familiar with Python or JS.

Also, do we want a version for mutable arrays too?

+1

crusso commented 11 months ago

Also, do we want a version for mutable arrays too?

+1

Looking at the module api, I see that most (but not all) operations only operate on immutable arrays. Instead of adding a mutable variant of just this operation ( takeVar or takeVarArray?), perhaps we should consider later adding a new module VarArray with mutable versions of all relevant operations (VarArray.take, VarArray.filter etc).

So I'd say let's just merge this immutable Array.take for now until we find a suitable name or home for the mutable version.

We already have some historically inconsistent naming that it would be nice to resolve, eg Blob.fromArrayMut (not Blob.fromVarArray).