Add start parameter to array enumerate (#1818)

This commit is contained in:
bluebear94 2023-07-29 17:11:21 -04:00 committed by GitHub
parent 5bd97e218b
commit 66df130ca4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 3 deletions

View File

@ -392,10 +392,18 @@ impl Array {
} }
/// Enumerate all items in the array. /// Enumerate all items in the array.
pub fn enumerate(&self) -> Self { pub fn enumerate(&self, start: i64) -> StrResult<Self> {
self.iter() self.iter()
.enumerate() .enumerate()
.map(|(i, value)| array![i, value.clone()].into_value()) .map(|(i, value)| {
Ok(array![
start
.checked_add_unsigned(i as u64)
.ok_or_else(|| "array index is too large".to_string())?,
value.clone()
]
.into_value())
})
.collect() .collect()
} }

View File

@ -146,7 +146,10 @@ pub fn call(
} }
"sorted" => array.sorted(vm, span, args.named("key")?)?.into_value(), "sorted" => array.sorted(vm, span, args.named("key")?)?.into_value(),
"zip" => array.zip(args.expect("other")?).into_value(), "zip" => array.zip(args.expect("other")?).into_value(),
"enumerate" => array.enumerate().into_value(), "enumerate" => array
.enumerate(args.named("start")?.unwrap_or(0))
.at(span)?
.into_value(),
"dedup" => array.dedup(vm, args.named("key")?)?.into_value(), "dedup" => array.dedup(vm, args.named("key")?)?.into_value(),
_ => return missing(), _ => return missing(),
}, },

View File

@ -892,6 +892,9 @@ The returned array consists of `(index, value)` pairs in the form of length-2
arrays. These can be [destructured]($scripting/#bindings) with a let binding or arrays. These can be [destructured]($scripting/#bindings) with a let binding or
for loop. for loop.
- start: integer (named)
The index returned for the first pair of the returned list.
Defaults to `{0}`.
- returns: array - returns: array
### zip() ### zip()

View File

@ -238,6 +238,15 @@
#test(((1, 2), 3).zip((4, 5)), (((1, 2), 4), (3, 5))) #test(((1, 2), 3).zip((4, 5)), (((1, 2), 4), (3, 5)))
#test((1, "hi").zip((true, false)), ((1, true), ("hi", false))) #test((1, "hi").zip((true, false)), ((1, true), ("hi", false)))
---
// Test the `enumerate` method.
#test(().enumerate(), ())
#test(().enumerate(start: 5), ())
#test(("a", "b", "c").enumerate(), ((0, "a"), (1, "b"), (2, "c")))
#test(("a", "b", "c").enumerate(start: 1), ((1, "a"), (2, "b"), (3, "c")))
#test(("a", "b", "c").enumerate(start: 42), ((42, "a"), (43, "b"), (44, "c")))
#test(("a", "b", "c").enumerate(start: -7), ((-7, "a"), (-6, "b"), (-5, "c")))
--- ---
// Test the `dedup` method. // Test the `dedup` method.
#test(().dedup(), ()) #test(().dedup(), ())