From 517d92a1213c46224f1cc66ad49b6a7b5bf8ef5f Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Mon, 15 Jun 2020 13:18:43 +0200 Subject: [PATCH 1/2] Simplify the "is integer" checks in `CFFCompiler.encodeNumber` The `isNaN` check is obviously redundant, since `NaN` is the only value that isn't equal to itself; see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN#Examples The `parseFloat`/`parseInt` comparison would make sense if the `value` ever contains a String, which however is never actually the case. Besides looking through the code, I've also run the entire test-suite locally with `assert(typeof value === "number", "encodeNumber");` added at the top of the method and there were no failures. Hence we can simplify the "is integer" check a bit in the `CFFCompiler.encodeNumber` method. --- src/core/cff_parser.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/core/cff_parser.js b/src/core/cff_parser.js index cf1f1c4bb..f8c48b612 100644 --- a/src/core/cff_parser.js +++ b/src/core/cff_parser.js @@ -1483,8 +1483,7 @@ var CFFCompiler = (function CFFCompilerClosure() { return output.data; }, encodeNumber: function CFFCompiler_encodeNumber(value) { - if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { - // isInt + if (Number.isInteger(value)) { return this.encodeInteger(value); } return this.encodeFloat(value); From 87b089ba42ccd6c2069b328586c9f2153c2e9491 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Mon, 15 Jun 2020 13:24:20 +0200 Subject: [PATCH 2/2] Lazily initialize, and cache, the regular expression used in `CFFCompiler.encodeFloat` There's no particular reason for re-creating the regular expression over and over for every `encodeFloat` invocation, as far as I can tell. --- src/core/cff_parser.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/cff_parser.js b/src/core/cff_parser.js index f8c48b612..0ed2c9a09 100644 --- a/src/core/cff_parser.js +++ b/src/core/cff_parser.js @@ -1366,6 +1366,8 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() { // Takes a CFF and converts it to the binary representation. var CFFCompiler = (function CFFCompilerClosure() { + let EncodeFloatRegExp = null; // Lazily initialized by `encodeFloat`. + // eslint-disable-next-line no-shadow function CFFCompiler(cff) { this.cff = cff; @@ -1491,8 +1493,11 @@ var CFFCompiler = (function CFFCompilerClosure() { encodeFloat: function CFFCompiler_encodeFloat(num) { var value = num.toString(); - // rounding inaccurate doubles - var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); + if (!EncodeFloatRegExp) { + EncodeFloatRegExp = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/; + } + // Rounding inaccurate doubles. + var m = EncodeFloatRegExp.exec(value); if (m) { var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); value = (Math.round(num * epsilon) / epsilon).toString();