@@ -54,6 +54,7 @@ import qualified Text.Regex.TDFA.ReadRegex as R
54
54
import Prelude hiding (lines , replicate )
55
55
import Data.Aeson.Key (fromText )
56
56
import Data.Aeson.Types (Pair )
57
+ import qualified Data.Either as V
57
58
58
59
59
60
-- $setup
@@ -154,6 +155,44 @@ oneOfArray arr = do
154
155
pure $ arr' V. ! idx
155
156
156
157
158
+ -- | Join argument expressions into a string.
159
+ --
160
+ -- If there is more than one argument the first first argument is used as separator.
161
+ -- If there is a single argument and it is an array, the array is concattenated.
162
+ --
163
+ -- >>> exec "join(['Hello', 'World'])"
164
+ -- String "HelloWorld"
165
+ --
166
+ -- >>> exec "join('-', 'Hello', 'World')"
167
+ -- String "Hello-World"
168
+ --
169
+ -- >>> exec "join('foo')"
170
+ -- String "foo"
171
+ --
172
+ -- >>> exec "join([1, 2, 3])"
173
+ -- String "123"
174
+ --
175
+ -- >>> exec "join()"
176
+ -- String ""
177
+ joinArgs :: [Expr ] -> Fake Value
178
+ joinArgs [] = pure $ String " "
179
+ joinArgs [arg] = do
180
+ val <- eval arg
181
+ pure $ case val of
182
+ (String _) -> val
183
+ (Array arr') -> do
184
+ let strings = V. rights . V. toList $ fmap A. asText arr'
185
+ text = T. intercalate " " strings
186
+ String text
187
+ _ -> error $ " Expected a string or array, but received: " <> show val
188
+ joinArgs (x: xs) = do
189
+ sep <- Except. liftEither . A. asText =<< eval x
190
+ values <- mapM eval xs
191
+ let strings = V. rights $ fmap A. asText values
192
+ text = T. intercalate sep strings
193
+ pure $ String text
194
+
195
+
157
196
-- | Select one random argument
158
197
--
159
198
-- >>> exec "oneOf(37, 42, 21)"
@@ -443,6 +482,7 @@ eval (Fn "randomDateTime" [lower, upper]) = do
443
482
upper' <- rightToMaybe . A. asText <$> eval upper
444
483
randomDateTime lower' upper'
445
484
eval (Fn " array" args) = Array . V. fromList <$> mapM eval args
485
+ eval (Fn " join" args) = joinArgs args
446
486
eval (Fn " oneOf" [arg]) = oneOfArray arg
447
487
eval (Fn " oneOf" args) = oneOfArgs args
448
488
eval (Fn " replicate" [num, expr]) = replicate num expr
0 commit comments