sanctuary-js / sanctuary

:see_no_evil: Refuge from unsafe JavaScript
https://sanctuary.js.org
MIT License
3.04k stars 94 forks source link

regexp: add S.replaceWith and S.replaceBy #686

Closed davidchambers closed 4 years ago

davidchambers commented 4 years ago

Competes with #685

This pull request adds the following two functions:

replaceWith ::                          String  -> RegExp -> String -> String
replaceBy   :: (Array (Maybe String) -> String) -> RegExp -> String -> String

Design decisions:

I have opened sanctuary-js/sanctuary-site#88 to provide several examples of replaceWith and replaceBy in use.

@sanctuary-js/owners, what do you think of the proposed additions to the library?

davidchambers commented 4 years ago

I did like that with the other PR both functions began with the regexp, but with these names the parameter order you have makes perfect sense and reads well.

It is convenient for S.replaceBy to take the replacement function first (and thus the pattern second) in case one wishes to define a variant for patterns without optional capturing groups:

//    replace__ :: RegExp -> (Array String -> String) -> String -> String
//
//    Variant of proposed function `S.replace_` (sanctuary-js/sanctuary#685)
//    for patterns without optional capturing groups.
const replace__ = S.flip (S.compose (S.flip (S.replace_)) (S.contramap (S.justs)));
//    replaceBy_ :: (Array String -> String) -> RegExp -> String -> String
//
//    Variant of proposed function `S.replaceBy` (sanctuary-js/sanctuary#686)
//    for patterns without optional capturing groups.
const replaceBy_ = S.compose (S.replaceBy) (S.contramap (S.justs));

I am aware of two other reasons to take the pattern second:

davidchambers commented 4 years ago

Superseded by #693