Merge pull request #15536 from Snuffleupagus/more-for-of-2

Use more `for...of` loops in the code-base
This commit is contained in:
Jonas Jenwald 2022-10-05 11:32:19 +02:00 committed by GitHub
commit 8c59cc72a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 70 additions and 101 deletions

View File

@ -1343,8 +1343,7 @@ class Catalog {
const kidPromises = []; const kidPromises = [];
let found = false; let found = false;
for (let i = 0, ii = kids.length; i < ii; i++) { for (const kid of kids) {
const kid = kids[i];
if (!(kid instanceof Ref)) { if (!(kid instanceof Ref)) {
throw new FormatError("Kid must be a reference."); throw new FormatError("Kid must be a reference.");
} }

View File

@ -476,10 +476,7 @@ class CFFParser {
createDict(Type, dict, strings) { createDict(Type, dict, strings) {
const cffDict = new Type(strings); const cffDict = new Type(strings);
for (let i = 0, ii = dict.length; i < ii; ++i) { for (const [key, value] of dict) {
const pair = dict[i];
const key = pair[0];
const value = pair[1];
cffDict.setByKey(key, value); cffDict.setByKey(key, value);
} }
return cffDict; return cffDict;
@ -1110,15 +1107,14 @@ class CFFDict {
if (!(key in this.keyToNameMap)) { if (!(key in this.keyToNameMap)) {
return false; return false;
} }
const valueLength = value.length;
// ignore empty values // ignore empty values
if (valueLength === 0) { if (value.length === 0) {
return true; return true;
} }
// Ignore invalid values (fixes bug1068432.pdf and bug1308536.pdf). // Ignore invalid values (fixes bug1068432.pdf and bug1308536.pdf).
for (let i = 0; i < valueLength; i++) { for (const val of value) {
if (isNaN(value[i])) { if (isNaN(val)) {
warn('Invalid CFFDict value: "' + value + '" for key "' + key + '".'); warn(`Invalid CFFDict value: "${value}" for key "${key}".`);
return true; return true;
} }
} }
@ -1166,8 +1162,7 @@ class CFFDict {
opcodes: {}, opcodes: {},
order: [], order: [],
}; };
for (let i = 0, ii = layout.length; i < ii; ++i) { for (const entry of layout) {
const entry = layout[i];
const key = Array.isArray(entry[0]) const key = Array.isArray(entry[0])
? (entry[0][0] << 8) + entry[0][1] ? (entry[0][0] << 8) + entry[0][1]
: entry[0]; : entry[0];
@ -1401,8 +1396,7 @@ class CFFCompiler {
if (cff.topDict.hasName("FontMatrix")) { if (cff.topDict.hasName("FontMatrix")) {
const base = cff.topDict.getByName("FontMatrix"); const base = cff.topDict.getByName("FontMatrix");
cff.topDict.removeByName("FontMatrix"); cff.topDict.removeByName("FontMatrix");
for (let i = 0, ii = cff.fdArray.length; i < ii; i++) { for (const subDict of cff.fdArray) {
const subDict = cff.fdArray[i];
let matrix = base.slice(0); let matrix = base.slice(0);
if (subDict.hasName("FontMatrix")) { if (subDict.hasName("FontMatrix")) {
matrix = Util.transform(matrix, subDict.getByName("FontMatrix")); matrix = Util.transform(matrix, subDict.getByName("FontMatrix"));
@ -1564,8 +1558,7 @@ class CFFCompiler {
compileNameIndex(names) { compileNameIndex(names) {
const nameIndex = new CFFIndex(); const nameIndex = new CFFIndex();
for (let i = 0, ii = names.length; i < ii; ++i) { for (const name of names) {
const name = names[i];
// OTS doesn't allow names to be over 127 characters. // OTS doesn't allow names to be over 127 characters.
const length = Math.min(name.length, 127); const length = Math.min(name.length, 127);
let sanitizedName = new Array(length); let sanitizedName = new Array(length);
@ -1604,8 +1597,7 @@ class CFFCompiler {
compileTopDicts(dicts, length, removeCidKeys) { compileTopDicts(dicts, length, removeCidKeys) {
const fontDictTrackers = []; const fontDictTrackers = [];
let fdArrayIndex = new CFFIndex(); let fdArrayIndex = new CFFIndex();
for (let i = 0, ii = dicts.length; i < ii; ++i) { for (const fontDict of dicts) {
const fontDict = dicts[i];
if (removeCidKeys) { if (removeCidKeys) {
fontDict.removeByName("CIDFontVersion"); fontDict.removeByName("CIDFontVersion");
fontDict.removeByName("CIDFontRevision"); fontDict.removeByName("CIDFontRevision");
@ -1723,8 +1715,8 @@ class CFFCompiler {
compileStringIndex(strings) { compileStringIndex(strings) {
const stringIndex = new CFFIndex(); const stringIndex = new CFFIndex();
for (let i = 0, ii = strings.length; i < ii; ++i) { for (const string of strings) {
stringIndex.add(stringToBytes(strings[i])); stringIndex.add(stringToBytes(string));
} }
return this.compileIndex(stringIndex); return this.compileIndex(stringIndex);
} }
@ -1908,9 +1900,7 @@ class CFFCompiler {
if (trackers[i]) { if (trackers[i]) {
trackers[i].offset(data.length); trackers[i].offset(data.length);
} }
for (let j = 0, jj = objects[i].length; j < jj; j++) { data.push(...objects[i]);
data.push(objects[i][j]);
}
} }
return data; return data;
} }

View File

@ -1407,8 +1407,8 @@ class PDFDocument {
function hexString(hash) { function hexString(hash) {
const buf = []; const buf = [];
for (let i = 0, ii = hash.length; i < ii; i++) { for (const num of hash) {
const hex = hash[i].toString(16); const hex = num.toString(16);
buf.push(hex.padStart(2, "0")); buf.push(hex.padStart(2, "0"));
} }
return buf.join(""); return buf.join("");

View File

@ -112,8 +112,8 @@ const deferred = Promise.resolve();
function normalizeBlendMode(value, parsingArray = false) { function normalizeBlendMode(value, parsingArray = false) {
if (Array.isArray(value)) { if (Array.isArray(value)) {
// Use the first *supported* BM value in the Array (fixes issue11279.pdf). // Use the first *supported* BM value in the Array (fixes issue11279.pdf).
for (let i = 0, ii = value.length; i < ii; i++) { for (const val of value) {
const maybeBM = normalizeBlendMode(value[i], /* parsingArray = */ true); const maybeBM = normalizeBlendMode(val, /* parsingArray = */ true);
if (maybeBM) { if (maybeBM) {
return maybeBM; return maybeBM;
} }
@ -1056,10 +1056,8 @@ class PartialEvaluator {
let isSimpleGState = true; let isSimpleGState = true;
// This array holds the converted/processed state data. // This array holds the converted/processed state data.
const gStateObj = []; const gStateObj = [];
const gStateKeys = gState.getKeys();
let promise = Promise.resolve(); let promise = Promise.resolve();
for (let i = 0, ii = gStateKeys.length; i < ii; i++) { for (const key of gState.getKeys()) {
const key = gStateKeys[i];
const value = gState.get(key); const value = gState.get(key);
switch (key) { switch (key) {
case "Type": case "Type":
@ -3419,8 +3417,8 @@ class PartialEvaluator {
if (encoding.has("Differences")) { if (encoding.has("Differences")) {
const diffEncoding = encoding.get("Differences"); const diffEncoding = encoding.get("Differences");
let index = 0; let index = 0;
for (let j = 0, jj = diffEncoding.length; j < jj; j++) { for (const entry of diffEncoding) {
const data = xref.fetchIfRef(diffEncoding[j]); const data = xref.fetchIfRef(entry);
if (typeof data === "number") { if (typeof data === "number") {
index = data; index = data;
} else if (data instanceof Name) { } else if (data instanceof Name) {
@ -4150,8 +4148,8 @@ class PartialEvaluator {
if (widths) { if (widths) {
const glyphWidths = []; const glyphWidths = [];
let j = firstChar; let j = firstChar;
for (let i = 0, ii = widths.length; i < ii; i++) { for (const width of widths) {
glyphWidths[j++] = this.xref.fetchIfRef(widths[i]); glyphWidths[j++] = this.xref.fetchIfRef(width);
} }
newProperties.widths = glyphWidths; newProperties.widths = glyphWidths;
} else { } else {

View File

@ -2795,7 +2795,6 @@ class Font {
const cmapPlatformId = cmapTable.platformId; const cmapPlatformId = cmapTable.platformId;
const cmapEncodingId = cmapTable.encodingId; const cmapEncodingId = cmapTable.encodingId;
const cmapMappings = cmapTable.mappings; const cmapMappings = cmapTable.mappings;
const cmapMappingsLength = cmapMappings.length;
let baseEncoding = [], let baseEncoding = [],
forcePostTable = false; forcePostTable = false;
if ( if (
@ -2860,18 +2859,18 @@ class Font {
} }
} }
for (let i = 0; i < cmapMappingsLength; ++i) { for (const mapping of cmapMappings) {
if (cmapMappings[i].charCode !== unicodeOrCharCode) { if (mapping.charCode !== unicodeOrCharCode) {
continue; continue;
} }
charCodeToGlyphId[charCode] = cmapMappings[i].glyphId; charCodeToGlyphId[charCode] = mapping.glyphId;
break; break;
} }
} }
} else if (cmapPlatformId === 0) { } else if (cmapPlatformId === 0) {
// Default Unicode semantics, use the charcodes as is. // Default Unicode semantics, use the charcodes as is.
for (let i = 0; i < cmapMappingsLength; ++i) { for (const mapping of cmapMappings) {
charCodeToGlyphId[cmapMappings[i].charCode] = cmapMappings[i].glyphId; charCodeToGlyphId[mapping.charCode] = mapping.glyphId;
} }
// Always prefer the BaseEncoding/Differences arrays, when they exist // Always prefer the BaseEncoding/Differences arrays, when they exist
// (fixes issue13433.pdf). // (fixes issue13433.pdf).
@ -2888,8 +2887,8 @@ class Font {
// special range since some PDFs have char codes outside of this range // special range since some PDFs have char codes outside of this range
// (e.g. 0x2013) which when masked would overwrite other values in the // (e.g. 0x2013) which when masked would overwrite other values in the
// cmap. // cmap.
for (let i = 0; i < cmapMappingsLength; ++i) { for (const mapping of cmapMappings) {
let charCode = cmapMappings[i].charCode; let charCode = mapping.charCode;
if ( if (
cmapPlatformId === 3 && cmapPlatformId === 3 &&
charCode >= 0xf000 && charCode >= 0xf000 &&
@ -2897,7 +2896,7 @@ class Font {
) { ) {
charCode &= 0xff; charCode &= 0xff;
} }
charCodeToGlyphId[charCode] = cmapMappings[i].glyphId; charCodeToGlyphId[charCode] = mapping.glyphId;
} }
} }
@ -3093,8 +3092,7 @@ class Font {
// to begin with. // to begin with.
continue; continue;
} }
for (let i = 0, ii = charCodes.length; i < ii; i++) { for (const charCode of charCodes) {
const charCode = charCodes[i];
// Find a fontCharCode that maps to the base and accent glyphs. // Find a fontCharCode that maps to the base and accent glyphs.
// If one doesn't exists, create it. // If one doesn't exists, create it.
const charCodeToGlyphId = newMapping.charCodeToGlyphId; const charCodeToGlyphId = newMapping.charCodeToGlyphId;
@ -3212,8 +3210,7 @@ class Font {
// trying to estimate space character width // trying to estimate space character width
const possibleSpaceReplacements = ["space", "minus", "one", "i", "I"]; const possibleSpaceReplacements = ["space", "minus", "one", "i", "I"];
let width; let width;
for (let i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) { for (const glyphName of possibleSpaceReplacements) {
const glyphName = possibleSpaceReplacements[i];
// if possible, getting width by glyph name // if possible, getting width by glyph name
if (glyphName in this.widths) { if (glyphName in this.widths) {
width = this.widths[glyphName]; width = this.widths[glyphName];

View File

@ -187,9 +187,9 @@ class PDFFunction {
} }
const fnArray = []; const fnArray = [];
for (let j = 0, jj = fnObj.length; j < jj; j++) { for (const fn of fnObj) {
fnArray.push( fnArray.push(
this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnObj[j]) }) this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fn) })
); );
} }
return function (src, srcOffset, dest, destOffset) { return function (src, srcOffset, dest, destOffset) {
@ -364,12 +364,9 @@ class PDFFunction {
throw new FormatError("Bad domain for stiched function"); throw new FormatError("Bad domain for stiched function");
} }
const fnRefs = dict.get("Functions");
const fns = []; const fns = [];
for (let i = 0, ii = fnRefs.length; i < ii; ++i) { for (const fn of dict.get("Functions")) {
fns.push( fns.push(this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fn) }));
this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnRefs[i]) })
);
} }
const bounds = toNumberArray(dict.getArray("Bounds")); const bounds = toNumberArray(dict.getArray("Bounds"));

View File

@ -774,8 +774,7 @@ class JpegImage {
function prepareComponents(frame) { function prepareComponents(frame) {
const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH); const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
const mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV); const mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
for (let i = 0, ii = frame.components.length; i < ii; i++) { for (const component of frame.components) {
const component = frame.components[i];
const blocksPerLine = Math.ceil( const blocksPerLine = Math.ceil(
(Math.ceil(frame.samplesPerLine / 8) * component.h) / frame.maxH (Math.ceil(frame.samplesPerLine / 8) * component.h) / frame.maxH
); );
@ -1080,9 +1079,7 @@ class JpegImage {
this.jfif = jfif; this.jfif = jfif;
this.adobe = adobe; this.adobe = adobe;
this.components = []; this.components = [];
for (let i = 0, ii = frame.components.length; i < ii; i++) { for (const component of frame.components) {
const component = frame.components[i];
// Prevent errors when DQT markers are placed after SOF{n} markers, // Prevent errors when DQT markers are placed after SOF{n} markers,
// by assigning the `quantizationTable` entry after the entire image // by assigning the `quantizationTable` entry after the entire image
// has been parsed (fixes issue7406.pdf). // has been parsed (fixes issue7406.pdf).
@ -1391,11 +1388,9 @@ class JpegImage {
const data = this._getLinearizedBlockData(width, height, isSourcePDF); const data = this._getLinearizedBlockData(width, height, isSourcePDF);
if (this.numComponents === 1 && forceRGB) { if (this.numComponents === 1 && forceRGB) {
const dataLength = data.length; const rgbData = new Uint8ClampedArray(data.length * 3);
const rgbData = new Uint8ClampedArray(dataLength * 3);
let offset = 0; let offset = 0;
for (let i = 0; i < dataLength; i++) { for (const grayColor of data) {
const grayColor = data[i];
rgbData[offset++] = grayColor; rgbData[offset++] = grayColor;
rgbData[offset++] = grayColor; rgbData[offset++] = grayColor;
rgbData[offset++] = grayColor; rgbData[offset++] = grayColor;

View File

@ -71,8 +71,8 @@ class ObjectLoader {
this.refSet = new RefSet(); this.refSet = new RefSet();
// Setup the initial nodes to visit. // Setup the initial nodes to visit.
const nodesToVisit = []; const nodesToVisit = [];
for (let i = 0, ii = keys.length; i < ii; i++) { for (const key of keys) {
const rawValue = dict.getRaw(keys[i]); const rawValue = dict.getRaw(key);
// Skip nodes that are guaranteed to be empty. // Skip nodes that are guaranteed to be empty.
if (rawValue !== undefined) { if (rawValue !== undefined) {
nodesToVisit.push(rawValue); nodesToVisit.push(rawValue);

View File

@ -37,8 +37,8 @@ function writeData(dest, offset, data) {
} }
} else { } else {
// treating everything else as array // treating everything else as array
for (let i = 0, ii = data.length; i < ii; i++) { for (const num of data) {
dest[offset++] = data[i] & 0xff; dest[offset++] = num & 0xff;
} }
} }
} }

View File

@ -291,8 +291,8 @@ class Type1Font {
getType2Charstrings(type1Charstrings) { getType2Charstrings(type1Charstrings) {
const type2Charstrings = []; const type2Charstrings = [];
for (let i = 0, ii = type1Charstrings.length; i < ii; i++) { for (const type1Charstring of type1Charstrings) {
type2Charstrings.push(type1Charstrings[i].charstring); type2Charstrings.push(type1Charstring.charstring);
} }
return type2Charstrings; return type2Charstrings;
} }

View File

@ -498,8 +498,8 @@ class SimpleXMLParser extends XMLParserBase {
if (!lastElement) { if (!lastElement) {
return null; return null;
} }
for (let i = 0, ii = lastElement.childNodes.length; i < ii; i++) { for (const childNode of lastElement.childNodes) {
lastElement.childNodes[i].parentNode = lastElement; childNode.parentNode = lastElement;
} }
return lastElement; return lastElement;
} }

View File

@ -551,14 +551,14 @@ class XRef {
} }
} }
// reading XRef streams // reading XRef streams
for (let i = 0, ii = xrefStms.length; i < ii; ++i) { for (const xrefStm of xrefStms) {
this.startXRefQueue.push(xrefStms[i]); this.startXRefQueue.push(xrefStm);
this.readXRef(/* recoveryMode */ true); this.readXRef(/* recoveryMode */ true);
} }
// finding main trailer // finding main trailer
let trailerDict; let trailerDict;
for (let i = 0, ii = trailers.length; i < ii; ++i) { for (const trailer of trailers) {
stream.pos = trailers[i]; stream.pos = trailer;
const parser = new Parser({ const parser = new Parser({
lexer: new Lexer(stream), lexer: new Lexer(stream),
xref: this, xref: this,

View File

@ -844,8 +844,7 @@ function copyCtxState(sourceCtx, destCtx) {
"globalCompositeOperation", "globalCompositeOperation",
"font", "font",
]; ];
for (let i = 0, ii = properties.length; i < ii; i++) { for (const property of properties) {
const property = properties[i];
if (sourceCtx[property] !== undefined) { if (sourceCtx[property] !== undefined) {
destCtx[property] = sourceCtx[property]; destCtx[property] = sourceCtx[property];
} }
@ -1538,11 +1537,7 @@ class CanvasGraphics {
} }
setGState(states) { setGState(states) {
for (let i = 0, ii = states.length; i < ii; i++) { for (const [key, value] of states) {
const state = states[i];
const key = state[0];
const value = state[1];
switch (key) { switch (key) {
case "LW": case "LW":
this.setLineWidth(value); this.setLineWidth(value);
@ -1569,11 +1564,11 @@ class CanvasGraphics {
this.setFont(value[0], value[1]); this.setFont(value[0], value[1]);
break; break;
case "CA": case "CA":
this.current.strokeAlpha = state[1]; this.current.strokeAlpha = value;
break; break;
case "ca": case "ca":
this.current.fillAlpha = state[1]; this.current.fillAlpha = value;
this.ctx.globalAlpha = state[1]; this.ctx.globalAlpha = value;
break; break;
case "BM": case "BM":
this.ctx.globalCompositeOperation = value; this.ctx.globalCompositeOperation = value;

View File

@ -299,8 +299,7 @@ class FreeTextEditor extends AnnotationEditor {
return this.editorDiv.innerText; return this.editorDiv.innerText;
} }
const buffer = []; const buffer = [];
for (let i = 0, ii = divs.length; i < ii; i++) { for (const div of divs) {
const div = divs[i];
const first = div.firstChild; const first = div.firstChild;
if (first?.nodeName === "#text") { if (first?.nodeName === "#text") {
buffer.push(first.data); buffer.push(first.data);

View File

@ -214,8 +214,8 @@ function render(task) {
} }
if (!task._textContentStream) { if (!task._textContentStream) {
for (let i = 0; i < textDivsLength; i++) { for (const textDiv of textDivs) {
task._layoutText(textDivs[i]); task._layoutText(textDiv);
} }
} }
@ -304,26 +304,26 @@ class TextLayerRenderTask {
* @private * @private
*/ */
_processItems(items, styleCache) { _processItems(items, styleCache) {
for (let i = 0, len = items.length; i < len; i++) { for (const item of items) {
if (items[i].str === undefined) { if (item.str === undefined) {
if ( if (
items[i].type === "beginMarkedContentProps" || item.type === "beginMarkedContentProps" ||
items[i].type === "beginMarkedContent" item.type === "beginMarkedContent"
) { ) {
const parent = this._container; const parent = this._container;
this._container = document.createElement("span"); this._container = document.createElement("span");
this._container.classList.add("markedContent"); this._container.classList.add("markedContent");
if (items[i].id !== null) { if (item.id !== null) {
this._container.setAttribute("id", `${items[i].id}`); this._container.setAttribute("id", `${item.id}`);
} }
parent.append(this._container); parent.append(this._container);
} else if (items[i].type === "endMarkedContent") { } else if (item.type === "endMarkedContent") {
this._container = this._container.parentNode; this._container = this._container.parentNode;
} }
continue; continue;
} }
this._textContentItemsStr.push(items[i].str); this._textContentItemsStr.push(item.str);
appendText(this, items[i], styleCache, this._layoutTextCtx); appendText(this, item, styleCache, this._layoutTextCtx);
} }
} }

View File

@ -273,8 +273,7 @@ class TextHighlighter {
let clearedUntilDivIdx = -1; let clearedUntilDivIdx = -1;
// Clear all current matches. // Clear all current matches.
for (let i = 0, ii = matches.length; i < ii; i++) { for (const match of matches) {
const match = matches[i];
const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (let n = begin, end = match.end.divIdx; n <= end; n++) { for (let n = begin, end = match.end.divIdx; n <= end; n++) {
const div = textDivs[n]; const div = textDivs[n];