Skip to content

Commit

Permalink
Support for arbitrary type patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagoarrais committed Nov 5, 2019
1 parent fbf8817 commit 8215057
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/lib/builtins/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,18 +744,16 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal
let replacement = get_argument(args, 1);
let replacement_str: &str = &ctx.value_to_rust_string(&replacement);

if pattern.is_string() {
let pattern_str: &str = &ctx.value_to_rust_string(&pattern);
// The Rust pattern is interpreted as a Regex and replaced in the original string with
// the replacement by using Regex.replace_all
let result_str = this_str.replace(pattern_str, replacement_str);
Ok(to_value(result_str))
} else {
pattern.with_internal_state_ref(|pattern_re: &RegExp| {
if let Some(re_internal_state) = pattern.get_internal_state() {
if let Some(pattern_re) = re_internal_state.downcast_ref::<RegExp>() {
let result_str = pattern_re.replace_all(this_str, replacement_str);
Ok(to_value(result_str.into_owned()))
})
return Ok(to_value(result_str.into_owned()));
}
}

let pattern_str: &str = &ctx.value_to_rust_string(&pattern);
let result_str = this_str.replace(pattern_str, replacement_str);
Ok(to_value(result_str))
}

fn get_argument(args: &[Value], idx: usize) -> Value {
Expand Down Expand Up @@ -1089,6 +1087,7 @@ mod tests {
var result1 = str.replace('dog', 'monkey');
var result2 = str.replace('dog.', 'monkey.');
var regexResult = str.replace(/dog./, 'monkey.');
var intResult = 'abc4e'.replace(4, 'd')
var exceptional1 = str.replace();
var exceptional2 = str.replace('dog');
"#;
Expand All @@ -1097,6 +1096,7 @@ mod tests {
assert_eq!(forward(&mut engine, "result1"), "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?");
assert_eq!(forward(&mut engine, "result2"), "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?");
assert_eq!(forward(&mut engine, "regexResult"), "The quick brown fox jumps over the lazy monkey. If the monkey.reacted, was it really lazy?");
assert_eq!(forward(&mut engine, "intResult"), "abcde");
assert_eq!(
forward(&mut engine, "exceptional1"),
"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?"
Expand Down

0 comments on commit 8215057

Please sign in to comment.