From: Joe Wreschnig Date: Mon, 19 May 2014 01:40:40 +0000 (+0200) Subject: Have numericLerp work in fixed point based on the longest operand. X-Git-Tag: 1.0.0~11 X-Git-Url: https://git.yukkurigames.com/?a=commitdiff_plain;h=d9344ccd68dbe21eb5af6d0575b5b84b9f8513aa;p=string-lerp.git Have numericLerp work in fixed point based on the longest operand. Restrict the set of strings considered numbers to those JS reasonable can treat as numbers. --- diff --git a/demo.html b/demo.html index 81941dc..de1902d 100644 --- a/demo.html +++ b/demo.html @@ -17,7 +17,7 @@ ["Do you like green eggs and ham?", "I do not like them, Sam-I-am."], ["apple core", "core dump"], ["rgb(255, 0, 0)", "rgb(0, 128, 255)"], - ["1.5 + 1.5 = 3.0", "3 + 7 = 10"], + ["1.50 + 1.50 = 3.0", "3 + 7 = 10"], ["ZALGO̸", "ZA̢LG͜O"], ["", "Typing, one letter at a time."], ["( ノ゚▽゚)ノ", "( ╯︵╰)"] diff --git a/string-lerp.js b/string-lerp.js index 607abc1..46a55bf 100644 --- a/string-lerp.js +++ b/string-lerp.js @@ -154,7 +154,7 @@ return patch(partial, target); } - var NUMBERS = /(-?\d+(?:\.\d+)?)/g; + var NUMBERS = /(-?\d{1,20}(?:\.\d{1,20})?)/g; function areNumericTwins(source, target) { /** Check if a and b differ only in numerals */ @@ -184,7 +184,6 @@ numerals gives undefined results. */ - // TODO: Try to preserve precision of the original numbers. var sourceParts = source.split(NUMBERS); var targetParts = target.split(NUMBERS); var destParts = targetParts; @@ -194,9 +193,10 @@ var part = nlerp(+sourcePart, +targetPart, amount); var sourcePoint = sourcePart.indexOf("."); var targetPoint = targetPart.indexOf("."); - if (sourcePoint === -1 && targetPoint === -1) - part = Math.round(part); - targetParts[i] = part.toString(); + var point = Math.max( + sourcePoint >= 0 ? (sourcePart.length - 1) - sourcePoint : 0, + targetPoint >= 0 ? (targetPart.length - 1) - targetPoint : 0); + targetParts[i] = part.toFixed(point); } return targetParts.join(""); } diff --git a/tests/string-lerp.js b/tests/string-lerp.js index 0a68921..2eccba6 100644 --- a/tests/string-lerp.js +++ b/tests/string-lerp.js @@ -157,6 +157,12 @@ JS.Test.describe('numeric lerp', function () { with (this) { assertEqual("12.3", lerp("0.0", "100.0", 0.123)); }}); + it("thinks about precision", function () { with (this) { + assertEqual("12.30", lerp("0", "100.00", 0.123)); + assertEqual("12.30", lerp("0.00", "100", 0.123)); + assertEqual("12.300", lerp("0.000", "100.000", 0.123)); + }}); + it("computes parameters outside [0, 1]", function () { with (this) { assertEqual("Giving 110%", lerp("Giving 0%", "Giving 100%", 1.1)); }});