Skip to content

Commit

Permalink
String.replace: Deal with missing arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagoarrais committed Oct 25, 2019
1 parent f5a513c commit a72479b
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/lib/builtins/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
object::{Object, ObjectKind, PROTOTYPE},
property::Property,
regexp::{make_regexp, match_all as regexp_match_all, r#match as regexp_match},
value::{from_value, to_value, ResultValue, Value, ValueData},
value::{from_value, to_value, undefined, ResultValue, Value, ValueData},
},
exec::Interpreter,
};
Expand Down Expand Up @@ -738,8 +738,13 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal
let this_str: &str = &ctx.value_to_rust_string(this);
// We then do the same thing for the other args
// TODO: what if there are missing arguments?
let pattern_str: &str = &ctx.value_to_rust_string(&args[0]);
let replacement_str: &str = &ctx.value_to_rust_string(&args[1]);
let pattern = get_argument(args, 0);
if undefined() == pattern {
return Ok(to_value(this_str));
}
let replacement = get_argument(args, 1);
let pattern_str: &str = &ctx.value_to_rust_string(&pattern);
let replacement_str: &str = &ctx.value_to_rust_string(&replacement);
// 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 = Regex::new(pattern_str)
Expand All @@ -748,6 +753,13 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal
Ok(to_value(result_str.into_owned()))
}

fn get_argument(args: &[Value], idx: usize) -> Value {
match args.get(idx) {
Some(arg) => arg.clone(),
None => undefined(),
}
}

/// Create a new `String` object
pub fn create_constructor(global: &Value) -> Value {
// Create constructor function object
Expand Down Expand Up @@ -1070,9 +1082,16 @@ mod tests {
let init = r#"
var str = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
var result = str.replace('dog', 'monkey');
var exceptional1 = str.replace();
var exceptional2 = str.replace('dog');
"#;

forward(&mut engine, init);
assert_eq!(forward(&mut engine, "result"), "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?");
assert_eq!(
forward(&mut engine, "exceptional1"),
"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?"
);
assert_eq!(forward(&mut engine, "exceptional2"), "The quick brown fox jumps over the lazy undefined. If the undefined reacted, was it really lazy?");
}
}

0 comments on commit a72479b

Please sign in to comment.