add std repeat command to replace "foo" * 3 (#10339)

related to
- https://github.com/nushell/nushell/issues/10233
- https://github.com/nushell/nushell/pull/10293
- https://github.com/nushell/nushell/pull/10292

inspired by @kubouch 

# Description
this PR adds a `repeat` command to the standard library

# User-Facing Changes
a new `repeat` command in `std`
```nushell
repeat anything a bunch of times, yielding a list of *n* times the input

# Examples
    repeat a string
    > "foo" | std repeat 3 | str join
    "foofoofoo"

Usage:
  > repeat <n>

Flags:
  -h, --help - Display the help message for this command

Parameters:
  n <int>: the number of repetitions, must be positive

Input/output types:
  ╭───┬───────┬───────────╮
  │ # │ input │  output   │
  ├───┼───────┼───────────┤
  │ 0 │ any   │ list<any> │
  ╰───┴───────┴───────────╯
```

# Tests + Formatting
a new test called `repeat_things` in `test_std.nu`

# After Submitting
This commit is contained in:
Antoine Stevan 2023-09-12 21:59:31 +02:00 committed by GitHub
parent 2a08865851
commit ba6d8ad261
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -294,3 +294,33 @@ Startup Time: ($nu.startup-time)
export def pwd [] {
$env.PWD
}
# repeat anything a bunch of times, yielding a list of *n* times the input
#
# # Examples
# repeat a string
# > "foo" | std repeat 3 | str join
# "foofoofoo"
export def repeat [
n: int # the number of repetitions, must be positive
]: any -> list<any> {
let item = $in
if $n < 0 {
let span = metadata $n | get span
error make {
msg: $"(ansi red_bold)invalid_argument(ansi reset)"
label: {
text: $"n should be a positive integer, found ($n)"
start: $span.start
end: $span.end
}
}
}
if $n == 0 {
return []
}
..($n - 1) | each { $item }
}

View File

@ -44,3 +44,14 @@ def path_add [] {
def banner [] {
std assert ((std banner | lines | length) == 15)
}
#[test]
def repeat_things [] {
std assert error { "foo" | std repeat -1 }
for x in ["foo", [1 2], {a: 1}] {
std assert equal ($x | std repeat 0) []
std assert equal ($x | std repeat 1) [$x]
std assert equal ($x | std repeat 2) [$x $x]
}
}