Added ratio function to changelog and added empty test case
This commit is contained in:
parent
1ba57dd21a
commit
7603aeb708
2 changed files with 30 additions and 0 deletions
|
|
@ -6,6 +6,7 @@ All notable changes to similar are documented here.
|
||||||
|
|
||||||
* Added grapheme and character level diffing utilities.
|
* Added grapheme and character level diffing utilities.
|
||||||
* `DiffOp::as_tag_tuple` is now taking the argument by reference.
|
* `DiffOp::as_tag_tuple` is now taking the argument by reference.
|
||||||
|
* Added `TextDiff::ratio`.
|
||||||
|
|
||||||
## 0.2.0
|
## 0.2.0
|
||||||
|
|
||||||
|
|
|
||||||
29
src/text.rs
29
src/text.rs
|
|
@ -303,6 +303,27 @@ impl<'old, 'new, 'bufs> TextDiff<'old, 'new, 'bufs> {
|
||||||
&self.new
|
&self.new
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Return a measure of the sequences' similarity in the range `0..=1`.
|
||||||
|
pub fn ratio(&self) -> f32 {
|
||||||
|
let matches = self
|
||||||
|
.ops()
|
||||||
|
.iter()
|
||||||
|
.map(|op| {
|
||||||
|
if let DiffOp::Equal { len, .. } = *op {
|
||||||
|
len
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.sum::<usize>();
|
||||||
|
let len = self.old.len() + self.new.len();
|
||||||
|
if len == 0 {
|
||||||
|
1.0
|
||||||
|
} else {
|
||||||
|
2.0 * matches as f32 / len as f32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Iterates over the changes the op expands to.
|
/// Iterates over the changes the op expands to.
|
||||||
///
|
///
|
||||||
/// This method is a convenient way to automatically resolve the different
|
/// This method is a convenient way to automatically resolve the different
|
||||||
|
|
@ -639,3 +660,11 @@ fn test_char_diff() {
|
||||||
let diff = TextDiff::from_chars("Hello World", "Hallo Welt");
|
let diff = TextDiff::from_chars("Hello World", "Hallo Welt");
|
||||||
insta::assert_debug_snapshot!(diff.ops());
|
insta::assert_debug_snapshot!(diff.ops());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ratio() {
|
||||||
|
let diff = TextDiff::from_chars("abcd", "bcde");
|
||||||
|
assert_eq!(diff.ratio(), 0.75);
|
||||||
|
let diff = TextDiff::from_chars("", "");
|
||||||
|
assert_eq!(diff.ratio(), 1.0);
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue