Skip to content

Commit

Permalink
feat: add array enumerate
Browse files Browse the repository at this point in the history
  • Loading branch information
olehmisar committed Nov 28, 2024
1 parent 52e088e commit 24b6456
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,16 @@ use nodash::ArrayExtensions;
assert([1, 2, 3].pad_end::<5>(0) == [1, 2, 3, 0, 0]);
```

#### `enumerate`

Returns an array of tuples, where each tuple contains the index and the value of the array element.

```rs
use nodash::ArrayExtensions;

assert(["a", "b", "c"].enumerate() == [(0, "a"), (1, "b"), (2, "c")]);
```

### `pack_bytes`

Packs `[u8; N]` into `[Field; N / 31 + 1]`. Useful, if you need to get a hash over bytes. I.e., `pedersen_hash(pack_bytes(bytes))` will be MUCH cheaper than `pedersen_hash(bytes)`.
Expand Down
13 changes: 13 additions & 0 deletions src/array.nr
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ impl<T, let N: u32> crate::ArrayExtensions<T, N> for [T; N] {
}
res
}

fn enumerate(self) -> [(u32, T); N] {
let mut res = [(0, self[0]); N]; // TODO: should I use std::zeroed() instead?
for i in 1..N {
res[i] = (i as u32, self[i]);
}
res
}
}

// TODO: write tests
Expand Down Expand Up @@ -82,4 +90,9 @@ mod tests {
fn test_pad_end() {
assert([1, 2, 3].pad_end::<5>(0) == [1, 2, 3, 0, 0]);
}

#[test]
fn test_enumerate() {
assert(["a", "b", "c"].enumerate() == [(0, "a"), (1, "b"), (2, "c")]);
}
}
3 changes: 2 additions & 1 deletion src/lib.nr
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ pub use array::pack_bytes;
pub use math::{clamp, div_ceil, sqrt::sqrt};
pub use string::{str_to_u64, to_hex_string_bytes};

trait ArrayExtensions<T, let N: u32> {
pub trait ArrayExtensions<T, let N: u32> {
fn slice<let L: u32>(self, start: u32) -> [T; L];
fn concat<let M: u32>(self, other: [T; M]) -> [T; N + M];
fn pad_start<let M: u32>(self, pad_value: T) -> [T; M];
fn pad_end<let M: u32>(self, pad_value: T) -> [T; M];
fn enumerate(self) -> [(u32, T); N];
}

0 comments on commit 24b6456

Please sign in to comment.