Skip to content

Commit 24b6456

Browse files
committed
feat: add array enumerate
1 parent 52e088e commit 24b6456

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,16 @@ use nodash::ArrayExtensions;
128128
assert([1, 2, 3].pad_end::<5>(0) == [1, 2, 3, 0, 0]);
129129
```
130130

131+
#### `enumerate`
132+
133+
Returns an array of tuples, where each tuple contains the index and the value of the array element.
134+
135+
```rs
136+
use nodash::ArrayExtensions;
137+
138+
assert(["a", "b", "c"].enumerate() == [(0, "a"), (1, "b"), (2, "c")]);
139+
```
140+
131141
### `pack_bytes`
132142

133143
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)`.

src/array.nr

+13
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ impl<T, let N: u32> crate::ArrayExtensions<T, N> for [T; N] {
3737
}
3838
res
3939
}
40+
41+
fn enumerate(self) -> [(u32, T); N] {
42+
let mut res = [(0, self[0]); N]; // TODO: should I use std::zeroed() instead?
43+
for i in 1..N {
44+
res[i] = (i as u32, self[i]);
45+
}
46+
res
47+
}
4048
}
4149

4250
// TODO: write tests
@@ -82,4 +90,9 @@ mod tests {
8290
fn test_pad_end() {
8391
assert([1, 2, 3].pad_end::<5>(0) == [1, 2, 3, 0, 0]);
8492
}
93+
94+
#[test]
95+
fn test_enumerate() {
96+
assert(["a", "b", "c"].enumerate() == [(0, "a"), (1, "b"), (2, "c")]);
97+
}
8598
}

src/lib.nr

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ pub use array::pack_bytes;
88
pub use math::{clamp, div_ceil, sqrt::sqrt};
99
pub use string::{str_to_u64, to_hex_string_bytes};
1010

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

0 commit comments

Comments
 (0)