nushell/crates/nu-command/tests/commands/chunk_by.rs
Renan Ribeiro dc9e8161d9
Implement chunk_by operation (#14410)
# Description

This pull requests implements a new ~~partition-by~~ `chunk-by` command.
The operation takes a closure and partitions the input list into
sublists based on the return value of the closure.
- fixes #14149

Examples, tests and and documentation were added accordingly.


![image](https://github.com/user-attachments/assets/c272e2ec-9af3-4a88-832b-ddca4eb14c8f)


![image](https://github.com/user-attachments/assets/178968e7-c165-4d8c-858c-98584d653b0a)
2024-11-29 13:37:27 -08:00

58 lines
1.1 KiB
Rust

use nu_test_support::{nu, pipeline};
#[test]
fn chunk_by_on_empty_input_returns_empty_list() {
let actual = nu!("[] | chunk-by {|it| $it} | to nuon");
assert!(actual.err.is_empty());
assert_eq!(actual.out, "[]");
}
#[test]
fn chunk_by_strings_works() {
let sample = r#"
[a a a b b b c c c a a a]
"#;
let actual = nu!(pipeline(&format!(
r#"
{sample}
| chunk-by {{|it| $it}}
| to nuon
"#
)));
assert_eq!(actual.out, "[[a, a, a], [b, b, b], [c, c, c], [a, a, a]]");
}
#[test]
fn chunk_by_field_works() {
let sample = r#"[
{
name: bob,
age: 20,
cool: false
},
{
name: jane,
age: 30,
cool: false
},
{
name: marie,
age: 19,
cool: true
},
{
name: carl,
age: 36,
cool: true
} ]"#;
let actual = nu!(pipeline(&format!(
r#"{sample}
| chunk-by {{|it| $it.cool}}
| length"#
)));
assert_eq!(actual.out, "2");
}