From 674e7ee381e9f2b818cbbe28559cf5d032d35108 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Thu, 27 Jul 2023 09:18:26 +0200 Subject: [PATCH 1/2] Enable the `unicorn/prefer-ternary` ESLint plugin rule To limit the readability impact of these changes, the `only-single-line` option was used; please find additional details at https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-ternary.md These changes were done automatically, using the `gulp lint --fix` command. --- .eslintrc | 1 + src/core/annotation.js | 32 ++++++++++++-------------------- src/core/ccitt.js | 15 +++++---------- src/core/cff_parser.js | 6 +----- src/core/colorspace.js | 6 +----- src/core/crypto.js | 12 ++---------- src/core/document.js | 6 +----- src/core/evaluator.js | 23 ++++++++--------------- src/core/fonts.js | 12 ++---------- src/core/function.js | 6 +----- src/core/jpg.js | 9 ++++----- src/core/jpx.js | 6 +----- src/core/operator_list.js | 9 ++++----- src/core/pattern.js | 18 ++++++++---------- src/core/predictor_stream.js | 6 +----- src/core/writer.js | 8 +++----- src/core/xfa/bind.js | 8 +++----- src/core/xfa/html_utils.js | 32 +++++++------------------------- src/core/xfa/som.js | 22 +++++++--------------- src/core/xfa/template.js | 6 +----- src/core/xfa/xfa_object.js | 9 ++++----- src/core/xfa/xhtml.js | 15 +++++---------- src/core/xfa_fonts.js | 8 +++----- src/core/xref.js | 17 +++++++---------- src/display/canvas.js | 15 +++++---------- src/display/pattern_helper.js | 6 +----- src/display/svg.js | 14 ++++---------- src/display/xfa_layer.js | 8 +++----- src/scripting_api/aform.js | 32 ++++++++++++-------------------- src/scripting_api/doc.js | 12 ++---------- src/scripting_api/util.js | 9 ++++----- 31 files changed, 123 insertions(+), 265 deletions(-) diff --git a/.eslintrc b/.eslintrc index 7a8b33b75..8913ec9e4 100644 --- a/.eslintrc +++ b/.eslintrc @@ -78,6 +78,7 @@ "unicorn/prefer-regexp-test": "error", "unicorn/prefer-string-replace-all": "error", "unicorn/prefer-string-starts-ends-with": "error", + "unicorn/prefer-ternary": ["error", "only-single-line"], // Possible errors "for-direction": "error", diff --git a/src/core/annotation.js b/src/core/annotation.js index 4c9e5ba10..715ed567d 100644 --- a/src/core/annotation.js +++ b/src/core/annotation.js @@ -784,11 +784,10 @@ class Annotation { * @param {Array} rectangle - The rectangle array with exactly four entries */ setRectangle(rectangle) { - if (Array.isArray(rectangle) && rectangle.length === 4) { - this.rectangle = Util.normalizeRect(rectangle); - } else { - this.rectangle = [0, 0, 0, 0]; - } + this.rectangle = + Array.isArray(rectangle) && rectangle.length === 4 + ? Util.normalizeRect(rectangle) + : [0, 0, 0, 0]; } /** @@ -841,11 +840,7 @@ class Annotation { setRotation(mk, dict) { this.rotation = 0; let angle; - if (mk instanceof Dict) { - angle = mk.get("R") || 0; - } else { - angle = dict.get("Rotate") || 0; - } + angle = mk instanceof Dict ? mk.get("R") || 0 : dict.get("Rotate") || 0; if (Number.isInteger(angle) && angle !== 0) { angle %= 360; if (angle < 0) { @@ -2815,11 +2810,9 @@ class ButtonWidgetAnnotation extends WidgetAnnotation { if (value === null || value === undefined) { // There is no default appearance so use the one derived // from the field value. - if (this.data.checkBox) { - value = this.data.fieldValue === this.data.exportValue; - } else { - value = this.data.fieldValue === this.data.buttonValue; - } + value = this.data.checkBox + ? this.data.fieldValue === this.data.exportValue + : this.data.fieldValue === this.data.buttonValue; } const appearance = value @@ -3610,11 +3603,10 @@ class PopupAnnotation extends Annotation { } const parentRect = parentItem.getArray("Rect"); - if (Array.isArray(parentRect) && parentRect.length === 4) { - this.data.parentRect = Util.normalizeRect(parentRect); - } else { - this.data.parentRect = null; - } + this.data.parentRect = + Array.isArray(parentRect) && parentRect.length === 4 + ? Util.normalizeRect(parentRect) + : null; const rt = parentItem.get("RT"); if (isName(rt, AnnotationReplyType.GROUP)) { diff --git a/src/core/ccitt.js b/src/core/ccitt.js index 8a341c016..ac204bd80 100644 --- a/src/core/ccitt.js +++ b/src/core/ccitt.js @@ -786,11 +786,10 @@ class CCITTFaxDecoder { } } - if (codingLine[0] > 0) { - this.outputBits = codingLine[(this.codingPos = 0)]; - } else { - this.outputBits = codingLine[(this.codingPos = 1)]; - } + this.outputBits = + codingLine[0] > 0 + ? codingLine[(this.codingPos = 0)] + : codingLine[(this.codingPos = 1)]; this.row++; } @@ -964,11 +963,7 @@ class CCITTFaxDecoder { return 1; } - if (code >> 5 === 0) { - p = whiteTable1[code]; - } else { - p = whiteTable2[code >> 3]; - } + p = code >> 5 === 0 ? whiteTable1[code] : whiteTable2[code >> 3]; if (p[0] > 0) { this._eatBits(p[0]); diff --git a/src/core/cff_parser.js b/src/core/cff_parser.js index ad251baeb..f3f2faaea 100644 --- a/src/core/cff_parser.js +++ b/src/core/cff_parser.js @@ -559,11 +559,7 @@ class CFFParser { validationCommand = CharstringValidationData[value]; } else if (value === 10 || value === 29) { let subrsIndex; - if (value === 10) { - subrsIndex = localSubrIndex; - } else { - subrsIndex = globalSubrIndex; - } + subrsIndex = value === 10 ? localSubrIndex : globalSubrIndex; if (!subrsIndex) { validationCommand = CharstringValidationData[value]; warn("Missing subrsIndex for " + validationCommand.id); diff --git a/src/core/colorspace.js b/src/core/colorspace.js index 9326d56e6..9a0266bde 100644 --- a/src/core/colorspace.js +++ b/src/core/colorspace.js @@ -1306,11 +1306,7 @@ const LabCS = (function LabCSClosure() { // Function g(x) from spec function fn_g(x) { let result; - if (x >= 6 / 29) { - result = x ** 3; - } else { - result = (108 / 841) * (x - 4 / 29); - } + result = x >= 6 / 29 ? x ** 3 : (108 / 841) * (x - 4 / 29); return result; } diff --git a/src/core/crypto.js b/src/core/crypto.js index 01183f84c..1f14179ac 100644 --- a/src/core/crypto.js +++ b/src/core/crypto.js @@ -795,11 +795,7 @@ class AESBaseCipher { this._mixCol = new Uint8Array(256); for (let i = 0; i < 256; i++) { - if (i < 128) { - this._mixCol[i] = i << 1; - } else { - this._mixCol[i] = (i << 1) ^ 0x1b; - } + this._mixCol[i] = i < 128 ? i << 1 : (i << 1) ^ 0x1b; } this.buffer = new Uint8Array(16); @@ -1450,11 +1446,7 @@ const CipherTransformFactory = (function CipherTransformFactoryClosure() { password = []; } let pdfAlgorithm; - if (revision === 6) { - pdfAlgorithm = new PDF20(); - } else { - pdfAlgorithm = new PDF17(); - } + pdfAlgorithm = revision === 6 ? new PDF20() : new PDF17(); if ( pdfAlgorithm.checkUserPassword(password, userValidationSalt, userPassword) diff --git a/src/core/document.js b/src/core/document.js index 0d228d203..b8b3e3d7e 100644 --- a/src/core/document.js +++ b/src/core/document.js @@ -1707,11 +1707,7 @@ class PDFDocument { const field = this.xref.fetchIfRef(fieldRef); if (field.has("T")) { const partName = stringToPDFString(field.get("T")); - if (name === "") { - name = partName; - } else { - name = `${name}.${partName}`; - } + name = name === "" ? partName : `${name}.${partName}`; } if (!field.has("Kids") && /\[\d+\]$/.test(name)) { diff --git a/src/core/evaluator.js b/src/core/evaluator.js index 12130ad3c..600c0d13c 100644 --- a/src/core/evaluator.js +++ b/src/core/evaluator.js @@ -463,11 +463,10 @@ class PartialEvaluator { const dict = xobj.dict; const matrix = dict.getArray("Matrix"); let bbox = dict.getArray("BBox"); - if (Array.isArray(bbox) && bbox.length === 4) { - bbox = Util.normalizeRect(bbox); - } else { - bbox = null; - } + bbox = + Array.isArray(bbox) && bbox.length === 4 + ? Util.normalizeRect(bbox) + : null; let optionalContent, groupOptions; if (dict.has("OC")) { @@ -795,11 +794,9 @@ class PartialEvaluator { if (cacheKey && imageRef && cacheGlobally) { let length = 0; - if (imgData.bitmap) { - length = imgData.width * imgData.height * 4; - } else { - length = imgData.data.length; - } + length = imgData.bitmap + ? imgData.width * imgData.height * 4 + : imgData.data.length; this.globalImageCache.addByteSize(imageRef, length); } @@ -3953,11 +3950,7 @@ class PartialEvaluator { if (!(lookupName in Metrics)) { // Use default fonts for looking up font metrics if the passed // font is not a base font - if (this.isSerifFont(name)) { - lookupName = "Times-Roman"; - } else { - lookupName = "Helvetica"; - } + lookupName = this.isSerifFont(name) ? "Times-Roman" : "Helvetica"; } const glyphWidths = Metrics[lookupName]; diff --git a/src/core/fonts.js b/src/core/fonts.js index da274f912..84e3dd131 100644 --- a/src/core/fonts.js +++ b/src/core/fonts.js @@ -376,17 +376,9 @@ function getFontFileType(file, { type, subtype, composite }) { let fileType, fileSubtype; if (isTrueTypeFile(file) || isTrueTypeCollectionFile(file)) { - if (composite) { - fileType = "CIDFontType2"; - } else { - fileType = "TrueType"; - } + fileType = composite ? "CIDFontType2" : "TrueType"; } else if (isOpenTypeFile(file)) { - if (composite) { - fileType = "CIDFontType2"; - } else { - fileType = "OpenType"; - } + fileType = composite ? "CIDFontType2" : "OpenType"; } else if (isType1File(file)) { if (composite) { fileType = "CIDFontType0"; diff --git a/src/core/function.js b/src/core/function.js index edee2558a..1e1d00336 100644 --- a/src/core/function.js +++ b/src/core/function.js @@ -247,11 +247,7 @@ class PDFFunction { } let decode = toNumberArray(dict.getArray("Decode")); - if (!decode) { - decode = range; - } else { - decode = toMultiArray(decode); - } + decode = !decode ? range : toMultiArray(decode); const samples = this.getSampleArray(size, outputSize, bps, fn); // const mask = 2 ** bps - 1; diff --git a/src/core/jpg.js b/src/core/jpg.js index 71e7b7f9e..9761b67e4 100644 --- a/src/core/jpg.js +++ b/src/core/jpg.js @@ -386,11 +386,10 @@ function decodeScan( let mcu = 0, fileMarker; let mcuExpected; - if (componentsLength === 1) { - mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; - } else { - mcuExpected = mcusPerLine * frame.mcusPerColumn; - } + mcuExpected = + componentsLength === 1 + ? components[0].blocksPerLine * components[0].blocksPerColumn + : mcusPerLine * frame.mcusPerColumn; let h, v; while (mcu <= mcuExpected) { diff --git a/src/core/jpx.js b/src/core/jpx.js index 6dd7c9654..c0acbf378 100644 --- a/src/core/jpx.js +++ b/src/core/jpx.js @@ -1384,11 +1384,7 @@ function copyCoefficients( } nb = bitsDecoded[position]; const pos = interleave ? levelOffset + (offset << 1) : offset; - if (reversible && nb >= mb) { - coefficients[pos] = n; - } else { - coefficients[pos] = n * (1 << (mb - nb)); - } + coefficients[pos] = reversible && nb >= mb ? n : n * (1 << (mb - nb)); } offset++; position++; diff --git a/src/core/operator_list.js b/src/core/operator_list.js index 6791b2401..2fdc1bb91 100644 --- a/src/core/operator_list.js +++ b/src/core/operator_list.js @@ -589,11 +589,10 @@ class OperatorList { this._streamSink = streamSink; this.fnArray = []; this.argsArray = []; - if (streamSink && !(intent & RenderingIntentFlag.OPLIST)) { - this.optimizer = new QueueOptimizer(this); - } else { - this.optimizer = new NullOptimizer(this); - } + this.optimizer = + streamSink && !(intent & RenderingIntentFlag.OPLIST) + ? new QueueOptimizer(this) + : new NullOptimizer(this); this.dependencies = new Set(); this._totalLength = 0; this.weight = 0; diff --git a/src/core/pattern.js b/src/core/pattern.js index ec9b42605..379c2bd65 100644 --- a/src/core/pattern.js +++ b/src/core/pattern.js @@ -116,11 +116,10 @@ class RadialAxialShading extends BaseShading { localColorSpaceCache, }); const bbox = dict.getArray("BBox"); - if (Array.isArray(bbox) && bbox.length === 4) { - this.bbox = Util.normalizeRect(bbox); - } else { - this.bbox = null; - } + this.bbox = + Array.isArray(bbox) && bbox.length === 4 + ? Util.normalizeRect(bbox) + : null; let t0 = 0.0, t1 = 1.0; @@ -458,11 +457,10 @@ class MeshShading extends BaseShading { const dict = stream.dict; this.shadingType = dict.get("ShadingType"); const bbox = dict.getArray("BBox"); - if (Array.isArray(bbox) && bbox.length === 4) { - this.bbox = Util.normalizeRect(bbox); - } else { - this.bbox = null; - } + this.bbox = + Array.isArray(bbox) && bbox.length === 4 + ? Util.normalizeRect(bbox) + : null; const cs = ColorSpace.parse({ cs: dict.getRaw("CS") || dict.getRaw("ColorSpace"), xref, diff --git a/src/core/predictor_stream.js b/src/core/predictor_stream.js index e36920a11..ac807a3b3 100644 --- a/src/core/predictor_stream.js +++ b/src/core/predictor_stream.js @@ -33,11 +33,7 @@ class PredictorStream extends DecodeStream { throw new FormatError(`Unsupported predictor: ${predictor}`); } - if (predictor === 2) { - this.readBlock = this.readBlockTiff; - } else { - this.readBlock = this.readBlockPng; - } + this.readBlock = predictor === 2 ? this.readBlockTiff : this.readBlockPng; this.str = str; this.dict = str.dict; diff --git a/src/core/writer.js b/src/core/writer.js index 009ea4cce..a3b9b8473 100644 --- a/src/core/writer.js +++ b/src/core/writer.js @@ -203,11 +203,9 @@ function writeXFADataForAcroform(str, newRefs) { node = xml.documentElement.searchNode([nodePath.at(-1)], 0); } if (node) { - if (Array.isArray(value)) { - node.childNodes = value.map(val => new SimpleDOMNode("value", val)); - } else { - node.childNodes = [new SimpleDOMNode("#text", value)]; - } + node.childNodes = Array.isArray(value) + ? value.map(val => new SimpleDOMNode("value", val)) + : [new SimpleDOMNode("#text", value)]; } else { warn(`Node not found for path: ${path}`); } diff --git a/src/core/xfa/bind.js b/src/core/xfa/bind.js index 3fb5087c7..462fa89be 100644 --- a/src/core/xfa/bind.js +++ b/src/core/xfa/bind.js @@ -55,11 +55,9 @@ class Binder { constructor(root) { this.root = root; this.datasets = root.datasets; - if (root.datasets?.data) { - this.data = root.datasets.data; - } else { - this.data = new XmlObject(NamespaceIds.datasets.id, "data"); - } + this.data = root.datasets?.data + ? root.datasets.data + : new XmlObject(NamespaceIds.datasets.id, "data"); this.emptyMerge = this.data[$getChildren]().length === 0; this.root.form = this.form = root.template[$clone](); diff --git a/src/core/xfa/html_utils.js b/src/core/xfa/html_utils.js index a03590ef3..71aaf83c1 100644 --- a/src/core/xfa/html_utils.js +++ b/src/core/xfa/html_utils.js @@ -103,17 +103,9 @@ const converters = { } } - if (width !== "") { - style.width = measureToString(width); - } else { - style.width = "auto"; - } + style.width = width !== "" ? measureToString(width) : "auto"; - if (height !== "") { - style.height = measureToString(height); - } else { - style.height = "auto"; - } + style.height = height !== "" ? measureToString(height) : "auto"; }, position(node, style) { const parent = node[$getSubformParent](); @@ -305,11 +297,7 @@ function computeBbox(node, html, availableSpace) { if (width === "") { if (node.maxW === 0) { const parent = node[$getSubformParent](); - if (parent.layout === "position" && parent.w !== "") { - width = 0; - } else { - width = node.minW; - } + width = parent.layout === "position" && parent.w !== "" ? 0 : node.minW; } else { width = Math.min(node.maxW, availableSpace.width); } @@ -320,11 +308,8 @@ function computeBbox(node, html, availableSpace) { if (height === "") { if (node.maxH === 0) { const parent = node[$getSubformParent](); - if (parent.layout === "position" && parent.h !== "") { - height = 0; - } else { - height = node.minH; - } + height = + parent.layout === "position" && parent.h !== "" ? 0 : node.minH; } else { height = Math.min(node.maxH, availableSpace.height); } @@ -510,11 +495,8 @@ function createWrapper(node, html) { } } - if (style.position === "absolute") { - wrapper.attributes.style.position = "absolute"; - } else { - wrapper.attributes.style.position = "relative"; - } + wrapper.attributes.style.position = + style.position === "absolute" ? "absolute" : "relative"; delete style.position; if (style.alignSelf) { diff --git a/src/core/xfa/som.js b/src/core/xfa/som.js index 9d1c7ebb3..205420cb0 100644 --- a/src/core/xfa/som.js +++ b/src/core/xfa/som.js @@ -211,11 +211,9 @@ function searchNode( break; case operators.dotHash: children = node[$getChildrenByClass](name); - if (children.isXFAObjectArray) { - children = children.children; - } else { - children = [children]; - } + children = children.isXFAObjectArray + ? children.children + : [children]; break; default: break; @@ -244,11 +242,9 @@ function searchNode( continue; } - if (isFinite(index)) { - root = nodes.filter(node => index < node.length).map(node => node[index]); - } else { - root = nodes.flat(); - } + root = isFinite(index) + ? nodes.filter(node => index < node.length).map(node => node[index]) + : nodes.flat(); } if (root.length === 0) { @@ -294,11 +290,7 @@ function createDataNode(root, container, expr) { break; case operators.dotHash: children = root[$getChildrenByClass](name); - if (children.isXFAObjectArray) { - children = children.children; - } else { - children = [children]; - } + children = children.isXFAObjectArray ? children.children : [children]; break; default: break; diff --git a/src/core/xfa/template.js b/src/core/xfa/template.js index ebaadddb9..8ec158ff8 100644 --- a/src/core/xfa/template.js +++ b/src/core/xfa/template.js @@ -271,11 +271,7 @@ function applyAssist(obj, attributes) { } else { const parent = obj[$getParent](); if (parent.layout === "row") { - if (parent.assist?.role === "TH") { - attributes.role = "columnheader"; - } else { - attributes.role = "cell"; - } + attributes.role = parent.assist?.role === "TH" ? "columnheader" : "cell"; } } } diff --git a/src/core/xfa/xfa_object.js b/src/core/xfa/xfa_object.js index 00112298d..8de0c17f0 100644 --- a/src/core/xfa/xfa_object.js +++ b/src/core/xfa/xfa_object.js @@ -657,11 +657,10 @@ class XFAObject { continue; } const value = this[name]; - if (value instanceof XFAObjectArray) { - clone[name] = new XFAObjectArray(value[_max]); - } else { - clone[name] = null; - } + clone[name] = + value instanceof XFAObjectArray + ? new XFAObjectArray(value[_max]) + : null; } for (const child of this[_children]) { diff --git a/src/core/xfa/xhtml.js b/src/core/xfa/xhtml.js index aff02378b..3e9847c7b 100644 --- a/src/core/xfa/xhtml.js +++ b/src/core/xfa/xhtml.js @@ -127,18 +127,13 @@ function mapStyle(styleStr, node, richText) { } let newValue = value; if (mapping) { - if (typeof mapping === "string") { - newValue = mapping; - } else { - newValue = mapping(value, original); - } + newValue = + typeof mapping === "string" ? mapping : mapping(value, original); } if (key.endsWith("scale")) { - if (style.transform) { - style.transform = `${style[key]} ${newValue}`; - } else { - style.transform = newValue; - } + style.transform = style.transform + ? `${style[key]} ${newValue}` + : newValue; } else { style[key.replaceAll(/-([a-zA-Z])/g, (_, x) => x.toUpperCase())] = newValue; diff --git a/src/core/xfa_fonts.js b/src/core/xfa_fonts.js index fc32b4231..5904004d7 100644 --- a/src/core/xfa_fonts.js +++ b/src/core/xfa_fonts.js @@ -225,11 +225,9 @@ function getXfaFontWidths(name) { const { baseWidths, baseMapping, factors } = info; let rescaledBaseWidths; - if (!factors) { - rescaledBaseWidths = baseWidths; - } else { - rescaledBaseWidths = baseWidths.map((w, i) => w * factors[i]); - } + rescaledBaseWidths = !factors + ? baseWidths + : baseWidths.map((w, i) => w * factors[i]); let currentCode = -2; let currentArray; diff --git a/src/core/xref.js b/src/core/xref.js index 6dfb2d770..5c9946c96 100644 --- a/src/core/xref.js +++ b/src/core/xref.js @@ -814,11 +814,9 @@ class XRef { this._pendingRefs.put(ref); try { - if (xrefEntry.uncompressed) { - xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption); - } else { - xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption); - } + xrefEntry = xrefEntry.uncompressed + ? this.fetchUncompressed(ref, xrefEntry, suppressEncryption) + : this.fetchCompressed(ref, xrefEntry, suppressEncryption); this._pendingRefs.remove(ref); } catch (ex) { this._pendingRefs.remove(ref); @@ -873,11 +871,10 @@ class XRef { } throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`); } - if (this.encrypt && !suppressEncryption) { - xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen)); - } else { - xrefEntry = parser.getObj(); - } + xrefEntry = + this.encrypt && !suppressEncryption + ? parser.getObj(this.encrypt.createCipherTransform(num, gen)) + : parser.getObj(); if (!(xrefEntry instanceof BaseStream)) { if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) { assert( diff --git a/src/display/canvas.js b/src/display/canvas.js index 821212a5f..39dff0ce9 100644 --- a/src/display/canvas.js +++ b/src/display/canvas.js @@ -855,11 +855,8 @@ function genericComposeSMask( const b0 = hasBackdrop ? backdrop[2] : 0; let composeFn; - if (subtype === "Luminosity") { - composeFn = composeSMaskLuminosity; - } else { - composeFn = composeSMaskAlpha; - } + composeFn = + subtype === "Luminosity" ? composeSMaskLuminosity : composeSMaskAlpha; // processing image in chunks to save memory const PIXELS_TO_PROCESS = 1048576; @@ -2258,11 +2255,9 @@ class CanvasGraphics { } let charWidth; - if (vertical) { - charWidth = width * widthAdvanceScale - spacing * fontDirection; - } else { - charWidth = width * widthAdvanceScale + spacing * fontDirection; - } + charWidth = vertical + ? width * widthAdvanceScale - spacing * fontDirection + : width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { diff --git a/src/display/pattern_helper.js b/src/display/pattern_helper.js index 38f544d29..7a7b5154e 100644 --- a/src/display/pattern_helper.js +++ b/src/display/pattern_helper.js @@ -201,11 +201,7 @@ function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { for (let y = minY; y <= maxY; y++) { if (y < y2) { let k; - if (y < y1) { - k = 0; - } else { - k = (y1 - y) / (y1 - y2); - } + k = y < y1 ? 0 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; diff --git a/src/display/svg.js b/src/display/svg.js index 61ff4e155..a20aa88d9 100644 --- a/src/display/svg.js +++ b/src/display/svg.js @@ -78,11 +78,7 @@ const convertImgDataToPng = (function () { for (let i = 0; i < 256; i++) { let c = i; for (let h = 0; h < 8; h++) { - if (c & 1) { - c = 0xedb88320 ^ ((c >> 1) & 0x7fffffff); - } else { - c = (c >> 1) & 0x7fffffff; - } + c = c & 1 ? 0xedb88320 ^ ((c >> 1) & 0x7fffffff) : (c >> 1) & 0x7fffffff; } crcTable[i] = c; } @@ -862,11 +858,9 @@ class SVGGraphics { } let charWidth; - if (vertical) { - charWidth = width * widthAdvanceScale - spacing * fontDirection; - } else { - charWidth = width * widthAdvanceScale + spacing * fontDirection; - } + charWidth = vertical + ? width * widthAdvanceScale - spacing * fontDirection + : width * widthAdvanceScale + spacing * fontDirection; x += charWidth; } diff --git a/src/display/xfa_layer.js b/src/display/xfa_layer.js index 7d21f7aa8..0ca518483 100644 --- a/src/display/xfa_layer.js +++ b/src/display/xfa_layer.js @@ -213,11 +213,9 @@ class XfaLayer { } let childHtml; - if (child?.attributes?.xmlns) { - childHtml = document.createElementNS(child.attributes.xmlns, name); - } else { - childHtml = document.createElement(name); - } + childHtml = child?.attributes?.xmlns + ? document.createElementNS(child.attributes.xmlns, name) + : document.createElement(name); html.append(childHtml); if (child.attributes) { diff --git a/src/scripting_api/aform.js b/src/scripting_api/aform.js index c0ff4e9ab..dd780d2c2 100644 --- a/src/scripting_api/aform.js +++ b/src/scripting_api/aform.js @@ -147,11 +147,9 @@ class AForm { } catch {} if (!date) { date = Date.parse(cDate); - if (isNaN(date)) { - date = this._tryToGuessDate(cFormat, cDate); - } else { - date = new Date(date); - } + date = isNaN(date) + ? this._tryToGuessDate(cFormat, cDate) + : new Date(date); } return date; } @@ -348,11 +346,7 @@ class AForm { const formatStr = `%,${sepStyle}.${nDec}f`; value = this._util.printf(formatStr, value * 100); - if (percentPrepend) { - event.value = `%${value}`; - } else { - event.value = `${value}%`; - } + event.value = percentPrepend ? `%${value}` : `${value}%`; } AFPercent_Keystroke(nDec, sepStyle) { @@ -541,11 +535,10 @@ class AForm { formatStr = "99999-9999"; break; case 2: - if (this._util.printx("9999999999", event.value).length >= 10) { - formatStr = "(999) 999-9999"; - } else { - formatStr = "999-9999"; - } + formatStr = + this._util.printx("9999999999", event.value).length >= 10 + ? "(999) 999-9999" + : "999-9999"; break; case 3: formatStr = "999-99-9999"; @@ -648,11 +641,10 @@ class AForm { break; case 2: const value = this.AFMergeChange(event); - if (value.length > 8 || value.startsWith("(")) { - formatStr = "(999) 999-9999"; - } else { - formatStr = "999-9999"; - } + formatStr = + value.length > 8 || value.startsWith("(") + ? "(999) 999-9999" + : "999-9999"; break; case 3: formatStr = "999-99-9999"; diff --git a/src/scripting_api/doc.js b/src/scripting_api/doc.js index 6d9097147..e63566614 100644 --- a/src/scripting_api/doc.js +++ b/src/scripting_api/doc.js @@ -1126,17 +1126,9 @@ class Doc extends PDFObject { nEnd = printParams.lastPage; } - if (typeof nStart === "number") { - nStart = Math.max(0, Math.trunc(nStart)); - } else { - nStart = 0; - } + nStart = typeof nStart === "number" ? Math.max(0, Math.trunc(nStart)) : 0; - if (typeof nEnd === "number") { - nEnd = Math.max(0, Math.trunc(nEnd)); - } else { - nEnd = -1; - } + nEnd = typeof nEnd === "number" ? Math.max(0, Math.trunc(nEnd)) : -1; this._send({ command: "print", start: nStart, end: nEnd }); } diff --git a/src/scripting_api/util.js b/src/scripting_api/util.js index b4840fb5b..e807bb4a2 100644 --- a/src/scripting_api/util.js +++ b/src/scripting_api/util.js @@ -148,11 +148,10 @@ class Util extends PDFObject { let decPart = ""; if (cConvChar === "f") { - if (nPrecision !== undefined) { - decPart = Math.abs(arg - intPart).toFixed(nPrecision); - } else { - decPart = Math.abs(arg - intPart).toString(); - } + decPart = + nPrecision !== undefined + ? Math.abs(arg - intPart).toFixed(nPrecision) + : Math.abs(arg - intPart).toString(); if (decPart.length > 2) { decPart = `${decimalSep}${decPart.substring(2)}`; } else { From c0fe96b8fe2fd73450dadbec2be42ccf869c890d Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Thu, 27 Jul 2023 09:38:11 +0200 Subject: [PATCH 2/2] Additional *manual* `unicorn/prefer-ternary` changes Not all cases could be automatically fixed, and the changes also triggered a number of `prefer-const` errors that needed to be handled manually. --- src/core/annotation.js | 3 +-- src/core/cff_parser.js | 3 +-- src/core/colorspace.js | 4 +--- src/core/crypto.js | 3 +-- src/core/evaluator.js | 3 +-- src/core/fonts_utils.js | 24 ++++-------------------- src/core/jpg.js | 3 +-- src/core/xfa/bind.js | 5 ++--- src/core/xfa_fonts.js | 3 +-- src/display/canvas.js | 6 ++---- src/display/pattern_helper.js | 3 +-- src/display/svg.js | 12 +++--------- src/display/xfa_layer.js | 3 +-- 13 files changed, 20 insertions(+), 55 deletions(-) diff --git a/src/core/annotation.js b/src/core/annotation.js index 715ed567d..551f429e4 100644 --- a/src/core/annotation.js +++ b/src/core/annotation.js @@ -839,8 +839,7 @@ class Annotation { setRotation(mk, dict) { this.rotation = 0; - let angle; - angle = mk instanceof Dict ? mk.get("R") || 0 : dict.get("Rotate") || 0; + let angle = mk instanceof Dict ? mk.get("R") || 0 : dict.get("Rotate") || 0; if (Number.isInteger(angle) && angle !== 0) { angle %= 360; if (angle < 0) { diff --git a/src/core/cff_parser.js b/src/core/cff_parser.js index f3f2faaea..446764f0d 100644 --- a/src/core/cff_parser.js +++ b/src/core/cff_parser.js @@ -558,8 +558,7 @@ class CFFParser { stackSize %= 2; validationCommand = CharstringValidationData[value]; } else if (value === 10 || value === 29) { - let subrsIndex; - subrsIndex = value === 10 ? localSubrIndex : globalSubrIndex; + const subrsIndex = value === 10 ? localSubrIndex : globalSubrIndex; if (!subrsIndex) { validationCommand = CharstringValidationData[value]; warn("Missing subrsIndex for " + validationCommand.id); diff --git a/src/core/colorspace.js b/src/core/colorspace.js index 9a0266bde..0da3430ad 100644 --- a/src/core/colorspace.js +++ b/src/core/colorspace.js @@ -1305,9 +1305,7 @@ const CalRGBCS = (function CalRGBCSClosure() { const LabCS = (function LabCSClosure() { // Function g(x) from spec function fn_g(x) { - let result; - result = x >= 6 / 29 ? x ** 3 : (108 / 841) * (x - 4 / 29); - return result; + return x >= 6 / 29 ? x ** 3 : (108 / 841) * (x - 4 / 29); } function decode(value, high1, low2, high2) { diff --git a/src/core/crypto.js b/src/core/crypto.js index 1f14179ac..26c22d80b 100644 --- a/src/core/crypto.js +++ b/src/core/crypto.js @@ -1445,8 +1445,7 @@ const CipherTransformFactory = (function CipherTransformFactoryClosure() { } else { password = []; } - let pdfAlgorithm; - pdfAlgorithm = revision === 6 ? new PDF20() : new PDF17(); + const pdfAlgorithm = revision === 6 ? new PDF20() : new PDF17(); if ( pdfAlgorithm.checkUserPassword(password, userValidationSalt, userPassword) diff --git a/src/core/evaluator.js b/src/core/evaluator.js index 600c0d13c..b380c8960 100644 --- a/src/core/evaluator.js +++ b/src/core/evaluator.js @@ -793,8 +793,7 @@ class PartialEvaluator { ); if (cacheKey && imageRef && cacheGlobally) { - let length = 0; - length = imgData.bitmap + const length = imgData.bitmap ? imgData.width * imgData.height * 4 : imgData.data.length; this.globalImageCache.addByteSize(imageRef, length); diff --git a/src/core/fonts_utils.js b/src/core/fonts_utils.js index f1bbf6762..e5067d8e6 100644 --- a/src/core/fonts_utils.js +++ b/src/core/fonts_utils.js @@ -116,11 +116,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { baseEncoding = builtInEncoding; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); - if (glyphId >= 0) { - charCodeToGlyphId[charCode] = glyphId; - } else { - charCodeToGlyphId[charCode] = 0; // notdef - } + charCodeToGlyphId[charCode] = glyphId >= 0 ? glyphId : /* notdef = */ 0; } } else if (properties.baseEncodingName) { // If a valid base encoding name was used, the mapping is initialized with @@ -128,11 +124,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { baseEncoding = getEncoding(properties.baseEncodingName); for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); - if (glyphId >= 0) { - charCodeToGlyphId[charCode] = glyphId; - } else { - charCodeToGlyphId[charCode] = 0; // notdef - } + charCodeToGlyphId[charCode] = glyphId >= 0 ? glyphId : /* notdef = */ 0; } } else if (isSymbolicFont) { // For a symbolic font the encoding should be the fonts built-in encoding. @@ -145,11 +137,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { baseEncoding = StandardEncoding; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); - if (glyphId >= 0) { - charCodeToGlyphId[charCode] = glyphId; - } else { - charCodeToGlyphId[charCode] = 0; // notdef - } + charCodeToGlyphId[charCode] = glyphId >= 0 ? glyphId : /* notdef = */ 0; } } @@ -170,11 +158,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { glyphId = glyphNames.indexOf(standardGlyphName); } } - if (glyphId >= 0) { - charCodeToGlyphId[charCode] = glyphId; - } else { - charCodeToGlyphId[charCode] = 0; // notdef - } + charCodeToGlyphId[charCode] = glyphId >= 0 ? glyphId : /* notdef = */ 0; } } return charCodeToGlyphId; diff --git a/src/core/jpg.js b/src/core/jpg.js index 9761b67e4..de3673879 100644 --- a/src/core/jpg.js +++ b/src/core/jpg.js @@ -385,8 +385,7 @@ function decodeScan( let mcu = 0, fileMarker; - let mcuExpected; - mcuExpected = + const mcuExpected = componentsLength === 1 ? components[0].blocksPerLine * components[0].blocksPerColumn : mcusPerLine * frame.mcusPerColumn; diff --git a/src/core/xfa/bind.js b/src/core/xfa/bind.js index 462fa89be..4c6752160 100644 --- a/src/core/xfa/bind.js +++ b/src/core/xfa/bind.js @@ -55,9 +55,8 @@ class Binder { constructor(root) { this.root = root; this.datasets = root.datasets; - this.data = root.datasets?.data - ? root.datasets.data - : new XmlObject(NamespaceIds.datasets.id, "data"); + this.data = + root.datasets?.data || new XmlObject(NamespaceIds.datasets.id, "data"); this.emptyMerge = this.data[$getChildren]().length === 0; this.root.form = this.form = root.template[$clone](); diff --git a/src/core/xfa_fonts.js b/src/core/xfa_fonts.js index 5904004d7..7f58a99f7 100644 --- a/src/core/xfa_fonts.js +++ b/src/core/xfa_fonts.js @@ -224,8 +224,7 @@ function getXfaFontWidths(name) { } const { baseWidths, baseMapping, factors } = info; - let rescaledBaseWidths; - rescaledBaseWidths = !factors + const rescaledBaseWidths = !factors ? baseWidths : baseWidths.map((w, i) => w * factors[i]); diff --git a/src/display/canvas.js b/src/display/canvas.js index 39dff0ce9..bae1da84f 100644 --- a/src/display/canvas.js +++ b/src/display/canvas.js @@ -854,8 +854,7 @@ function genericComposeSMask( const g0 = hasBackdrop ? backdrop[1] : 0; const b0 = hasBackdrop ? backdrop[2] : 0; - let composeFn; - composeFn = + const composeFn = subtype === "Luminosity" ? composeSMaskLuminosity : composeSMaskAlpha; // processing image in chunks to save memory @@ -2254,8 +2253,7 @@ class CanvasGraphics { } } - let charWidth; - charWidth = vertical + const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; x += charWidth; diff --git a/src/display/pattern_helper.js b/src/display/pattern_helper.js index 7a7b5154e..ba3e7f93d 100644 --- a/src/display/pattern_helper.js +++ b/src/display/pattern_helper.js @@ -200,8 +200,7 @@ function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { let xb, cbr, cbg, cbb; for (let y = minY; y <= maxY; y++) { if (y < y2) { - let k; - k = y < y1 ? 0 : (y1 - y) / (y1 - y2); + const k = y < y1 ? 0 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; diff --git a/src/display/svg.js b/src/display/svg.js index a20aa88d9..c81084071 100644 --- a/src/display/svg.js +++ b/src/display/svg.js @@ -152,14 +152,9 @@ const convertImgDataToPng = (function () { // Node v0.11.12 zlib.deflateSync is introduced (and returns a Buffer). // Node v3.0.0 Buffer inherits from Uint8Array. // Node v8.0.0 zlib.deflateSync accepts Uint8Array as input. - let input; - // eslint-disable-next-line no-undef - if (parseInt(process.versions.node) >= 8) { - input = literals; - } else { + const input = // eslint-disable-next-line no-undef - input = Buffer.from(literals); - } + parseInt(process.versions.node) >= 8 ? literals : Buffer.from(literals); const output = __non_webpack_require__("zlib").deflateSync(input, { level: 9, }); @@ -857,8 +852,7 @@ class SVGGraphics { // might actually map to a different glyph. } - let charWidth; - charWidth = vertical + const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; diff --git a/src/display/xfa_layer.js b/src/display/xfa_layer.js index 0ca518483..b5c94327f 100644 --- a/src/display/xfa_layer.js +++ b/src/display/xfa_layer.js @@ -212,8 +212,7 @@ class XfaLayer { continue; } - let childHtml; - childHtml = child?.attributes?.xmlns + const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);