From 206d20426cb2959aab8cc3cfc8e62aa68bc7b52f Mon Sep 17 00:00:00 2001 From: h7x4 Date: Tue, 17 Oct 2023 01:12:49 +0200 Subject: [PATCH] lib.strings: add `replicate` `strings.replicate` returns n copies of a string, concatenated into a new string Co-authored-by: Silvan Mosberger --- lib/strings.nix | 14 ++++++++++++++ lib/tests/misc.nix | 5 +++++ 2 files changed, 19 insertions(+) diff --git a/lib/strings.nix b/lib/strings.nix index 628669d86bbd..695aaaacd348 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -144,6 +144,20 @@ rec { */ concatLines = concatMapStrings (s: s + "\n"); + /* + Replicate a string n times, + and concatenate the parts into a new string. + + Type: replicate :: int -> string -> string + + Example: + replicate 3 "v" + => "vvv" + replicate 5 "hello" + => "hellohellohellohellohello" + */ + replicate = n: s: concatStrings (lib.lists.replicate n s); + /* Construct a Unix-style, colon-separated search path consisting of the given `subDir` appended to each of the given paths. diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 2e7fda2b1f8b..1fb857a65e99 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -191,6 +191,11 @@ runTests { expected = "a\nb\nc\n"; }; + testReplicateString = { + expr = strings.replicate 5 "hello"; + expected = "hellohellohellohellohello"; + }; + testSplitStringsSimple = { expr = strings.splitString "." "a.b.c.d"; expected = [ "a" "b" "c" "d" ];