Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace .forEach() with for-of #39691

Merged
merged 2 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 6 additions & 15 deletions docs/fiddles/features/web-hid/renderer.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
async function testIt () {
const grantedDevices = await navigator.hid.getDevices()
let grantedDeviceList = ''
grantedDevices.forEach(device => {
grantedDeviceList += `<hr>${device.productName}</hr>`
})
document.getElementById('granted-devices').innerHTML = grantedDeviceList
const grantedDevices2 = await navigator.hid.requestDevice({
filters: []
})
function formatDevices (devices) {
return devices.map(device => device.productName).join('<hr>')
}

grantedDeviceList = ''
grantedDevices2.forEach(device => {
grantedDeviceList += `<hr>${device.productName}</hr>`
})
document.getElementById('granted-devices2').innerHTML = grantedDeviceList
async function testIt () {
document.getElementById('granted-devices').innerHTML = formatDevices(await navigator.hid.getDevices())
document.getElementById('granted-devices2').innerHTML = formatDevices(await navigator.hid.requestDevice({ filters: [] }))
}

document.getElementById('clickme').addEventListener('click', testIt)
4 changes: 2 additions & 2 deletions docs/fiddles/features/web-usb/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ async function testIt () {
const grantedDevices = await navigator.usb.getDevices()
let grantedDeviceList = ''
if (grantedDevices.length > 0) {
grantedDevices.forEach(device => {
for (const device of grantedDevices) {
grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>`
})
}
} else {
grantedDeviceList = noDevicesFoundMsg
}
Expand Down
16 changes: 8 additions & 8 deletions docs/fiddles/menus/customize-menus/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ const template = [
// on reload, start fresh and close any old
// open secondary windows
if (focusedWindow.id === 1) {
BrowserWindow.getAllWindows().forEach(win => {
for (const win of BrowserWindow.getAllWindows()) {
if (win.id > 1) win.close()
})
}
}
focusedWindow.reload()
}
Expand Down Expand Up @@ -209,15 +209,15 @@ function findReopenMenuItem () {
if (!menu) return

let reopenMenuItem
menu.items.forEach(item => {
for (const item of menu.items) {
if (item.submenu) {
item.submenu.items.forEach(item => {
if (item.key === 'reopenMenuItem') {
reopenMenuItem = item
for (const subitem of item.submenu.items) {
if (subitem.key === 'reopenMenuItem') {
reopenMenuItem = subitem
}
})
}
}
})
}
return reopenMenuItem
}

Expand Down
4 changes: 2 additions & 2 deletions docs/tutorial/code-signing.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,11 @@ const supportBinaries = await msiCreator.create()

// 🆕 Step 2a: optionally sign support binaries if you
// sign you binaries as part of of your packaging script
supportBinaries.forEach(async (binary) => {
for (const binary of supportBinaries) {
// Binaries are the new stub executable and optionally
// the Squirrel auto updater.
await signFile(binary)
})
}

// Step 3: Compile the template to a .msi file
await msiCreator.compile()
Expand Down
8 changes: 4 additions & 4 deletions docs/tutorial/in-app-purchases.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ inAppPurchase.on('transactions-updated', (event, transactions) => {
}

// Check each transaction.
transactions.forEach((transaction) => {
for (const transaction of transactions) {
const payment = transaction.payment

switch (transaction.transactionState) {
Expand Down Expand Up @@ -95,7 +95,7 @@ inAppPurchase.on('transactions-updated', (event, transactions) => {
default:
break
}
})
}
})

// Check if the user is allowed to make in-app purchase.
Expand All @@ -112,9 +112,9 @@ inAppPurchase.getProducts(PRODUCT_IDS).then(products => {
}

// Display the name and price of each product.
products.forEach(product => {
for (const product of products) {
console.log(`The price of ${product.localizedTitle} is ${product.formattedPrice}.`)
})
}

// Ask the user which product they want to purchase.
const selectedProduct = products[0]
Expand Down
21 changes: 13 additions & 8 deletions lib/browser/api/menu-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,17 @@ function sortTopologically<T> (originalOrder: T[], edgesById: Map<T, T[]>) {
marked.add(mark);
const edges = edgesById.get(mark);
if (edges != null) {
edges.forEach(visit);
for (const edge of edges) {
visit(edge);
}
}
sorted.push(mark);
};

originalOrder.forEach(visit);
for (const edge of originalOrder) {
visit(edge);
}

return sorted;
}

Expand Down Expand Up @@ -98,24 +103,24 @@ function sortItemsInGroup<T> (group: {before?: T[], after?: T[], id?: T}[]) {
const edges = new Map();
const idToIndex = new Map(group.map((item, i) => [item.id, i]));

group.forEach((item, i) => {
for (const [i, item] of group.entries()) {
if (item.before) {
item.before.forEach(toID => {
for (const toID of item.before) {
const to = idToIndex.get(toID);
if (to != null) {
pushOntoMultiMap(edges, to, i);
}
});
}
}
if (item.after) {
item.after.forEach(toID => {
for (const toID of item.after) {
const to = idToIndex.get(toID);
if (to != null) {
pushOntoMultiMap(edges, i, to);
}
});
}
}
});
}

const sortedNodes = sortTopologically(originalOrder, edges);
return sortedNodes.map(i => group[i]);
Expand Down
12 changes: 6 additions & 6 deletions lib/browser/api/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@ Menu.prototype.insert = function (pos, item) {

Menu.prototype._callMenuWillShow = function () {
if (this.delegate) this.delegate.menuWillShow(this);
this.items.forEach(item => {
for (const item of this.items) {
if (item.submenu) item.submenu._callMenuWillShow();
});
}
};

/* Static Methods */
Expand Down Expand Up @@ -196,13 +196,13 @@ Menu.buildFromTemplate = function (template) {
const filtered = removeExtraSeparators(sorted);

const menu = new Menu();
filtered.forEach(item => {
for (const item of filtered) {
if (item instanceof MenuItem) {
menu.append(item);
} else {
menu.append(new MenuItem(item));
}
});
}

return menu;
};
Expand Down Expand Up @@ -280,9 +280,9 @@ function insertItemByType (this: MenuType, item: MenuItem, pos: number) {
enumerable: true,
get: () => checked.get(item),
set: () => {
this.groupsMap[item.groupId].forEach(other => {
for (const other of this.groupsMap[item.groupId]) {
if (other !== item) checked.set(other, false);
});
}
checked.set(item, true);
}
});
Expand Down
4 changes: 2 additions & 2 deletions lib/browser/api/net-client-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ class IncomingMessage extends Readable {
get rawHeaders () {
const rawHeadersArr: string[] = [];
const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => {
for (const header of rawHeaders) {
rawHeadersArr.push(header.key, header.value);
});
}
return rawHeadersArr;
}

Expand Down
4 changes: 3 additions & 1 deletion lib/browser/api/net-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ export function fetchWithSession (input: RequestInfo, init: (RequestInit & {bypa
r.on('response', (resp: IncomingMessage) => {
if (locallyAborted) return;
const headers = new Headers();
for (const [k, v] of Object.entries(resp.headers)) { headers.set(k, Array.isArray(v) ? v.join(', ') : v); }
for (const [k, v] of Object.entries(resp.headers)) {
headers.set(k, Array.isArray(v) ? v.join(', ') : v);
}
const nullBodyStatus = [101, 204, 205, 304];
const body = nullBodyStatus.includes(resp.statusCode) || req.method === 'HEAD' ? null : Readable.toWeb(resp as unknown as Readable) as ReadableStream;
const rResp = new Response(body, {
Expand Down
8 changes: 5 additions & 3 deletions lib/browser/api/touch-bar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,15 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
this.items.set(item.id, item);
item.on('change', this.changeListener);
if (item.child instanceof TouchBar) {
item.child.orderedItems.forEach(registerItem);
for (const child of item.child.orderedItems) {
registerItem(child);
}
}
};

let hasOtherItemsProxy = false;
const idSet = new Set();
items.forEach((item) => {
for (const item of items) {
if (!(item instanceof TouchBarItem)) {
throw new TypeError('Each item must be an instance of TouchBarItem');
}
Expand All @@ -347,7 +349,7 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
} else {
throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar');
}
});
}

// register in separate loop after all items are validated
for (const item of (items as TouchBarItem<any>[])) {
Expand Down
4 changes: 2 additions & 2 deletions lib/browser/guest-view-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,9 @@ const createGuest = function (embedder: Electron.WebContents, embedderFrameId: n

const makeProps = (eventKey: string, args: any[]) => {
const props: Record<string, any> = {};
webViewEvents[eventKey].forEach((prop, index) => {
for (const [index, prop] of webViewEvents[eventKey].entries()) {
props[prop] = args[index];
});
}
return props;
};

Expand Down
6 changes: 3 additions & 3 deletions lib/browser/parse-features-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,11 @@ export function parseFeatures (features: string) {
const parsed = parseCommaSeparatedKeyValue(features);

const webPreferences: { [K in AllowedWebPreference]?: any } = {};
allowedWebPreferences.forEach((key) => {
if (parsed[key] === undefined) return;
for (const key of allowedWebPreferences) {
if (parsed[key] === undefined) continue;
webPreferences[key] = parsed[key];
delete parsed[key];
});
}

if (parsed.left !== undefined) parsed.x = parsed.left;
if (parsed.top !== undefined) parsed.y = parsed.top;
Expand Down
4 changes: 3 additions & 1 deletion script/prepare-appveyor.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ function useAppVeyorImage (targetBranch, options) {
assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`);
callAppVeyorBuildJobs(targetBranch, options.job, options);
} else {
validJobs.forEach((job) => callAppVeyorBuildJobs(targetBranch, job, options));
for (const job of validJobs) {
callAppVeyorBuildJobs(targetBranch, job, options);
}
}
}

Expand Down
8 changes: 6 additions & 2 deletions script/release/ci-release-build.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ function buildAppVeyor (targetBranch, options) {
assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`);
callAppVeyor(targetBranch, options.job, options);
} else {
validJobs.forEach((job) => callAppVeyor(targetBranch, job, options));
for (const job of validJobs) {
callAppVeyor(targetBranch, job, options);
}
}
}

Expand Down Expand Up @@ -243,7 +245,9 @@ function buildCircleCI (targetBranch, options) {
} else {
assert(!options.arch, 'Cannot provide a single architecture while building all workflows, please specify a single workflow via --workflow');
options.runningPublishWorkflows = true;
circleCIPublishWorkflows.forEach((job) => circleCIcall(targetBranch, job, options));
for (const job of circleCIPublishWorkflows) {
circleCIcall(targetBranch, job, options);
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions script/release/notes/notes.js
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ const getNotes = async (fromRef, toRef, newVersion) => {
toBranch
};

pool.commits.forEach(commit => {
for (const commit of pool.commits) {
const str = commit.semanticType;
if (commit.isBreakingChange) {
notes.breaking.push(commit);
Expand All @@ -478,7 +478,7 @@ const getNotes = async (fromRef, toRef, newVersion) => {
} else {
notes.unknown.push(commit);
}
});
}

return notes;
};
Expand Down
8 changes: 4 additions & 4 deletions script/release/publish-to-npm.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,18 +58,18 @@ new Promise((resolve, reject) => {
.then((dirPath) => {
tempDir = dirPath;
// copy files from `/npm` to temp directory
files.forEach((name) => {
for (const name of files) {
const noThirdSegment = name === 'README.md' || name === 'LICENSE';
fs.writeFileSync(
path.join(tempDir, name),
fs.readFileSync(path.join(ELECTRON_DIR, noThirdSegment ? '' : 'npm', name))
);
});
}
// copy from root package.json to temp/package.json
const packageJson = require(path.join(tempDir, 'package.json'));
jsonFields.forEach((fieldName) => {
for (const fieldName of jsonFields) {
packageJson[fieldName] = rootPackageJson[fieldName];
});
}
packageJson.version = currentElectronVersion;
fs.writeFileSync(
path.join(tempDir, 'package.json'),
Expand Down
4 changes: 2 additions & 2 deletions script/release/release.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ async function validateReleaseAssets (release, validatingRelease) {
const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file));

failureCount = 0;
requiredAssets.forEach(asset => {
for (const asset of requiredAssets) {
check(extantAssets.includes(asset), asset);
});
}
check((failureCount === 0), 'All required GitHub assets exist for release', true);

if (!validatingRelease || !release.draft) {
Expand Down
4 changes: 2 additions & 2 deletions spec/api-app-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1229,9 +1229,9 @@ describe('app module', () => {
'http://',
'https://'
];
protocols.forEach((protocol) => {
for (const protocol of protocols) {
expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
});
}
});

it('returns an empty string for a bogus protocol', () => {
Expand Down