Skip to content

Commit

Permalink
chore: Prefer for...of loops over forEach methods where appropriate
Browse files Browse the repository at this point in the history
  • Loading branch information
AverageHelper committed Aug 28, 2024
1 parent 418c7eb commit b4aa071
Show file tree
Hide file tree
Showing 13 changed files with 39 additions and 32 deletions.
2 changes: 1 addition & 1 deletion .vscode/i18n-ally-custom-framework.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ languageIds:
# To help with this, you can use https://www.freeformatter.com/json-escape.html
usageMatchRegex:
# Detect `localizations("your.i18n.keys")`
- "[^\\w\\d]localizations\\(['\"`]({key})['\"`]\\)"
- "[^\\w\\d]localizations\\([\r\n\t]*['\"`]({key})['\"`][\r\n\t,]*\\)"
# Detect `t("your.i18n.keys"`
- "[^\\w\\d]t\\(\\s*['\"`]({key})['\"`]"
# Detect `translate("your.i18n.keys"`
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"baseline": "./node_modules/.bin/prisma migrate resolve --applied 20220915022732_initial_state",
"migrate": "./node_modules/.bin/prisma migrate deploy",
"prisma:introspect": "./node_modules/.bin/prisma db pull",
"prisma:generate": "./node_modules/.bin/prisma generate --schema ./prisma/schema.prisma",
"prisma:generate": "./node_modules/.bin/prisma generate --no-hints --schema ./prisma/schema.prisma",
"migrations:generate": "./node_modules/.bin/prisma migrate dev --create-only",
"lint": "npm run export-version && npm run lintonly",
"lint:fix": "npm run export-version && npm run lintonly -- --fix",
Expand Down
8 changes: 4 additions & 4 deletions src/actions/messages/editMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function stopEscapingUriInString(content: string): string {

let freed = content.slice(0);

uris.reverse().forEach(range => {
for (const range of uris.reverse()) {
// Remove tails
if (freed[range.end] === ">") {
freed = freed.slice(0, range.end) + freed.slice(range.end + 1);
Expand All @@ -87,7 +87,7 @@ export function stopEscapingUriInString(content: string): string {
if (freed[range.start - 1] === "<") {
freed = freed.slice(0, range.start - 1) + freed.slice(range.start);
}
});
}

return freed;
}
Expand All @@ -105,7 +105,7 @@ export function escapeUriInString(content: string): string {
let suppressed = content.slice(0);
let delta = 0;

uris.forEach(range => {
for (const range of uris) {
// Add heads
if (suppressed[range.start - 1 + delta] !== "<") {
suppressed = `${suppressed.slice(0, range.start + delta)}<${suppressed.slice(
Expand All @@ -121,7 +121,7 @@ export function escapeUriInString(content: string): string {
)}`;
delta += 1;
}
});
}

return suppressed;
}
Expand Down
20 changes: 9 additions & 11 deletions src/actions/queue/useQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,31 +85,29 @@ function queueMessageFromEntry(
export async function playtimeRemainingInQueue(queueChannel: TextChannel): Promise<number> {
const queue = await getAllStoredEntries(queueChannel);
let duration = 0;
queue
.filter(e => !e.isDone)
.forEach(e => {
duration += e.seconds;
});
for (const e of queue.filter(e => !e.isDone)) {
duration += e.seconds;
}
return duration;
}

/** Retrieves the total playtime (in seconds) of the queue's entries. */
export async function playtimeTotalInQueue(queueChannel: TextChannel): Promise<number> {
const queue = await getAllStoredEntries(queueChannel);
let duration = 0;
queue.forEach(e => {
for (const e of queue) {
duration += e.seconds;
});
}
return duration;
}

/** Retrieves the average playtime (in seconds) of the queue's entries. */
export async function playtimeAverageInQueue(queueChannel: TextChannel): Promise<number> {
const queue = await getAllStoredEntries(queueChannel);
let average = 0;
queue.forEach(e => {
for (const e of queue) {
average += e.seconds;
});
}
average /= queue.length;
return average;
}
Expand Down Expand Up @@ -157,9 +155,9 @@ export async function averageSubmissionPlaytimeForUser(
const entries = await getAllStoredEntriesFromSender(userId, queueChannel);
let average = 0;

entries.forEach(entry => {
for (const entry of entries) {
average += entry.seconds;
});
}
average /= entries.length;

return average;
Expand Down
4 changes: 3 additions & 1 deletion src/commands/CommandContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
InteractionReplyOptions,
LocaleString,
Message,
MessageMentionOptions,
MessageReplyOptions,
User,
} from "discord.js";
Expand Down Expand Up @@ -102,9 +103,10 @@ interface BaseCommandContext {
readonly followUp: (
options:
| string
| Omit<MessageReplyOptions, "flags">
| (Omit<MessageReplyOptions, "flags"> & { readonly allowedMentions?: MessageMentionOptions })
| (Omit<InteractionReplyOptions, "flags"> & {
readonly reply?: boolean;
readonly allowedMentions?: MessageMentionOptions;
}),
) => Promise<Message | boolean>;
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/__mocks__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ function addMock(command: Command): void {
}

// Add all commands to our mock commands list
_allCommands.forEach(cmd => addMock(cmd));
_allCommands.forEach(addMock);
4 changes: 2 additions & 2 deletions src/commands/languages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ export const languages: GlobalCommand = {
}

let totalUse = 0;
Object.values(languages).forEach(val => {
for (const val of Object.values(languages)) {
totalUse += val ?? 0;
});
}

const stats = Object.entries(languages).map(([languageName, languageUse]) => {
const use = (languageUse ?? 0) / totalUse;
Expand Down
4 changes: 2 additions & 2 deletions src/commands/limits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const limits: Command = {
),
);

allLimits(locale).forEach(key => {
for (const key of allLimits(locale)) {
let value: string;
switch (key.value) {
case "cooldown":
Expand Down Expand Up @@ -84,7 +84,7 @@ export const limits: Command = {
}

embed.addFields({ name: `${key.name}:\t${value}`, value: key.description });
});
}

await reply({ embeds: [embed], ephemeral: true });
},
Expand Down
4 changes: 2 additions & 2 deletions src/commands/queue/blacklist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ export const blacklist: Subcommand = {
pushNewLine(replyMsg);
}

blacklistedUsers.forEach(userId => {
for (const userId of blacklistedUsers) {
push(` - ${userMention(userId)}`, replyMsg);
pushNewLine(replyMsg);
});
}

pushNewLine(replyMsg);
push("To add a user to the blacklist, run ", replyMsg);
Expand Down
4 changes: 3 additions & 1 deletion src/commands/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ export const test: Command = {

embed.setTitle(t("commands.test.responses.results-header", userLocale));
embed.setDescription(ti("commands.test.responses.see-on-forge", { list }, userLocale));
results.forEach(result => addResult(result, embed));
for (const result of results) {
addResult(result, embed);
}

const anyFailures = results.some(result => result.error !== undefined);
const content = anyFailures
Expand Down
9 changes: 7 additions & 2 deletions src/handleInteraction.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { CommandContext } from "./commands/index.js";
import type { CommandInteraction, DMChannel, GuildMember, GuildTextBasedChannel } from "discord.js";
import type {
ChatInputCommandInteraction,
DMChannel,
GuildMember,
GuildTextBasedChannel,
} from "discord.js";
import type { Logger } from "./logger.js";
import { allCommands } from "./commands/index.js";
import { ChannelType } from "discord.js";
Expand All @@ -18,7 +23,7 @@ import { richErrorMessage } from "./helpers/richErrorMessage.js";
* @param logger The place to write system messages.
*/
export async function handleInteraction(
interaction: CommandInteraction,
interaction: ChatInputCommandInteraction,
logger: Logger,
): Promise<void> {
// Don't respond to bots unless we're being tested
Expand Down
4 changes: 2 additions & 2 deletions src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,13 +249,13 @@ export function localizations<K extends string>(
// Get all localizations for the given keypath
const result: Partial<Record<SupportedLocale, string>> = {};

locales.forEach(locale => {
for (const locale of locales) {
const translation = t(keypath, locale);
if (translation !== undefined) {
// only add the translation if there is one to add
result[locale] = translation;
}
});
}

// Return undefined if there were no results
if (Object.keys(result).length === 0) return undefined;
Expand Down
4 changes: 2 additions & 2 deletions tests/discordUtils/dispatchLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export function useDispatchLoop<T>(
});

// remove marked keys
keysToRemove.forEach(id => {
for (const id of keysToRemove) {
waiterCollection.delete(id);
});
}
logger.debug(`Removed ${keysToRemove.length} finished waiters.`);
};
}

0 comments on commit b4aa071

Please sign in to comment.