Add split for arrays.

This commit is contained in:
Stephen Chung 2021-02-23 11:57:50 +08:00
parent ac3d8e35d4
commit e88713611c
2 changed files with 14 additions and 1 deletions

View File

@ -30,6 +30,7 @@ Enhancements
* `Position` now implements `Add` and `AddAssign`.
* `Scope` now implements `IntoIterator`.
* Strings now have the `split_rev` method and variations of `split` with maximum number of segments.
* Arrays now have the `split` method.
Version 0.19.12

View File

@ -3,7 +3,7 @@
use crate::engine::{OP_EQUALS, TYPICAL_ARRAY_SIZE};
use crate::plugin::*;
use crate::stdlib::{any::TypeId, boxed::Box, cmp::max, cmp::Ordering, string::ToString};
use crate::stdlib::{any::TypeId, boxed::Box, cmp::max, cmp::Ordering, mem, string::ToString};
use crate::{
def_package, Array, Dynamic, EvalAltResult, FnPtr, ImmutableString, NativeCallContext,
Position, INT,
@ -191,6 +191,18 @@ mod array_functions {
array[start..].iter().cloned().collect()
}
#[rhai_fn(name = "split")]
pub fn split_at(array: &mut Array, start: INT) -> Array {
if start <= 0 {
mem::take(array)
} else if start as usize >= array.len() {
Default::default()
} else {
let mut result: Array = Default::default();
result.extend(array.drain(start as usize..));
result
}
}
#[rhai_fn(return_raw)]
pub fn map(
ctx: NativeCallContext,