More efficient way to get LTR diffLerp editing.
[string-lerp.git] / string-lerp.js
index 2096a07..3a30488 100644 (file)
         return s;
     }
 
-    function reverse (s) {
-        return s.split("").reverse().join("");
-    }
-
     function diffLerp(a, b, p) {
         /** Interpolate between two strings based on edit distance
 
             compute the edits. It is not recommended for strings
             longer than a few hundred characters.
          */
-        a = reverse(a);
-        b = reverse(b);
-        var edits = diff(a, b);
-        var partial = edits.slice(0, Math.round(p * edits.length));
-        return reverse(patch(partial, a));
+
+        // The edit path works from the string end, forwards, because
+        // that's how Levenshtein edits work. To match LTR reading
+        // direction (and the behavior of fastLerp), swap the strings
+        // and invert the parameter when editing.
+        var edits = diff(b, a);
+        var partial = edits.slice(0, Math.round((1 - p) * edits.length));
+        return patch(partial, b);
     }
 
     var NUMBERS = /(-?\d+(?:\.\d+)?)/g;