[feat] add diffLines function

This commit is contained in:
Jay
2020-09-14 11:24:45 +08:00
parent a8f36b2923
commit 0dbb651a74
7 changed files with 115 additions and 8 deletions
+29 -1
View File
@@ -17,6 +17,7 @@ register_module!(example, init);
fn init(module: &mut Module) -> Result<()> {
module.create_named_method("diffChars", diff_char)?;
module.create_named_method("diffLines", diff_line)?;
Ok(())
}
@@ -32,7 +33,34 @@ fn diff_char(ctx: CallContext) -> Result<JsObject> {
let mut idx = 0;
for it in res.iter() {
let mut item = ctx.env.create_object().unwrap();
item.set_named_property(
"count",
ctx.env.create_int64(it.count.try_into().unwrap()).unwrap(),
)?;
item.set_named_property("value", ctx.env.create_string(&it.value).unwrap())?;
item.set_named_property("added", ctx.env.get_boolean(it.added).unwrap())?;
item.set_named_property("removed", ctx.env.get_boolean(it.removed).unwrap())?;
obj.set_element(idx, item)?;
idx += 1;
}
Ok(obj)
}
#[js_function(2)]
fn diff_line(ctx: CallContext) -> Result<JsObject> {
let str1: String = ctx.get::<JsString>(0)?.try_into()?;
let str2: String = ctx.get::<JsString>(1)?.try_into()?;
let res = mdiff::diff_lines(str1.as_str(), str2.as_str());
let mut obj = ctx.env.create_array_with_length(res.len()).unwrap();
let mut idx = 0;
for it in res.iter() {
let mut item = ctx.env.create_object().unwrap();
item.set_named_property(
"count",
ctx.env.create_int64(it.count.try_into().unwrap()).unwrap(),
+59
View File
@@ -13,6 +13,14 @@ pub enum Mode {
RIGHT,
}
fn get_line_res(s: &String, mode: Mode) -> Res {
Res {
count: s.split('\n').count(),
added: if mode == Mode::RIGHT { true } else { false },
removed: if mode == Mode::LEFT { true } else { false },
value: s.clone(),
}
}
fn get_res(s: &String, mode: Mode) -> Res {
Res {
count: s.chars().count(),
@@ -64,3 +72,54 @@ pub fn diff_chars(s1: &str, s2: &str) -> Vec<Res> {
result
}
pub fn diff_lines(s1: &str, s2: &str) -> Vec<Res> {
let mut result: Vec<Res> = Vec::new();
let mut mode = Mode::INIT;
let mut s: String = String::new();
for d in diff::lines(s1, s2) {
match d {
diff::Result::Left(l) => {
if mode != Mode::LEFT && mode != Mode::INIT {
result.push(get_line_res(&s, mode));
s.clear();
}
mode = Mode::LEFT;
if s.len() > 0 {
s.push('\n')
}
s.push_str(l);
}
diff::Result::Right(r) => {
if mode != Mode::RIGHT && mode != Mode::INIT {
result.push(get_line_res(&s, mode));
s.clear();
}
mode = Mode::RIGHT;
if s.len() > 0 {
s.push('\n')
}
s.push_str(r);
}
diff::Result::Both(l, _) => {
if mode != Mode::BOTH && mode != Mode::INIT {
result.push(get_line_res(&s, mode));
s.clear()
}
mode = Mode::BOTH;
if s.len() > 0 {
s.push('\n')
}
s.push_str(l);
}
}
}
if s.len() > 0 {
result.push(get_line_res(&s, mode));
s.clear();
}
result
}