Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
refactor: use proper variable names in callbacks (#9840)
* refactor: use proper variable names in callbacks

* refactor: change parameter names

* refactor: change remaining parameter names

* refactor: change remaining variable names

* refactor(GuildAuditLogsEntry): abstract reduce logic into a new function

* chore: undo unrelated changes

This undoes commit b2d93dc as it's unrelated

* refactor: more name changes

* chore: fix tests failing

* refactor: use option instead of opt

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
  • Loading branch information
sdanialraza and Jiralite committed Oct 9, 2023
1 parent 2aa3250 commit 11f6955
Show file tree
Hide file tree
Showing 34 changed files with 104 additions and 79 deletions.
2 changes: 1 addition & 1 deletion packages/discord.js/src/client/Client.js
Expand Up @@ -369,7 +369,7 @@ class Client extends BaseClient {
*/
async fetchStickerPacks() {
const data = await this.rest.get(Routes.stickerPacks());
return new Collection(data.sticker_packs.map(p => [p.id, new StickerPack(this, p)]));
return new Collection(data.sticker_packs.map(stickerPack => [stickerPack.id, new StickerPack(this, stickerPack)]));
}

/**
Expand Down
Expand Up @@ -364,7 +364,7 @@ class WebSocketManager extends EventEmitter {
*/
checkShardsReady() {
if (this.status === Status.Ready) return;
if (this.shards.size !== this.totalShards || this.shards.some(s => s.status !== Status.Ready)) {
if (this.shards.size !== this.totalShards || this.shards.some(shard => shard.status !== Status.Ready)) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/client/websocket/WebSocketShard.js
Expand Up @@ -140,7 +140,7 @@ class WebSocketShard extends EventEmitter {
*/
this.emit(WebSocketShardEvents.Ready);

this.expectedGuilds = new Set(packet.guilds.map(d => d.id));
this.expectedGuilds = new Set(packet.guilds.map(guild => guild.id));
this.status = Status.WaitingForGuilds;
}

Expand Down
9 changes: 6 additions & 3 deletions packages/discord.js/src/managers/ApplicationCommandManager.js
Expand Up @@ -169,9 +169,12 @@ class ApplicationCommandManager extends CachedManager {
*/
async set(commands, guildId) {
const data = await this.client.rest.put(this.commandPath({ guildId }), {
body: commands.map(c => this.constructor.transformCommand(c)),
body: commands.map(command => this.constructor.transformCommand(command)),
});
return data.reduce((coll, command) => coll.set(command.id, this._add(command, true, guildId)), new Collection());
return data.reduce(
(collection, command) => collection.set(command.id, this._add(command, true, guildId)),
new Collection(),
);
}

/**
Expand Down Expand Up @@ -253,7 +256,7 @@ class ApplicationCommandManager extends CachedManager {
nsfw: command.nsfw,
description_localizations: command.descriptionLocalizations ?? command.description_localizations,
type: command.type,
options: command.options?.map(o => ApplicationCommand.transformOption(o)),
options: command.options?.map(option => ApplicationCommand.transformOption(option)),
default_member_permissions,
dm_permission: command.dmPermission ?? command.dm_permission,
};
Expand Down
Expand Up @@ -210,17 +210,17 @@ class ApplicationCommandPermissionsManager extends BaseManager {
);
}

let existing = [];
let existingPermissions = [];
try {
existing = await this.fetch({ guild: guildId, command: commandId });
existingPermissions = await this.fetch({ guild: guildId, command: commandId });
} catch (error) {
if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) throw error;
}

const newPermissions = permissions.slice();
for (const perm of existing) {
if (!newPermissions.some(x => x.id === perm.id)) {
newPermissions.push(perm);
for (const existingPermission of existingPermissions) {
if (!newPermissions.some(newPermission => newPermission.id === existingPermission.id)) {
newPermissions.push(existingPermission);
}
}

Expand Down
Expand Up @@ -23,7 +23,7 @@ class CategoryChannelChildManager extends DataManager {
* @readonly
*/
get cache() {
return this.guild.channels.cache.filter(c => c.parentId === this.channel.id);
return this.guild.channels.cache.filter(channel => channel.parentId === this.channel.id);
}

/**
Expand Down
24 changes: 13 additions & 11 deletions packages/discord.js/src/managers/GuildChannelManager.js
Expand Up @@ -166,7 +166,7 @@ class GuildChannelManager extends CachedManager {
reason,
}) {
parent &&= this.client.channels.resolveId(parent);
permissionOverwrites &&= permissionOverwrites.map(o => PermissionOverwrites.resolve(o, this.guild));
permissionOverwrites &&= permissionOverwrites.map(overwrite => PermissionOverwrites.resolve(overwrite, this.guild));

const data = await this.client.rest.post(Routes.guildChannels(this.guild.id), {
body: {
Expand Down Expand Up @@ -281,19 +281,21 @@ class GuildChannelManager extends CachedManager {
await this.setPosition(channel, options.position, { position: options.position, reason: options.reason });
}

let permission_overwrites = options.permissionOverwrites?.map(o => PermissionOverwrites.resolve(o, this.guild));
let permission_overwrites = options.permissionOverwrites?.map(overwrite =>
PermissionOverwrites.resolve(overwrite, this.guild),
);

if (options.lockPermissions) {
if (parent) {
const newParent = this.guild.channels.resolve(parent);
if (newParent?.type === ChannelType.GuildCategory) {
permission_overwrites = newParent.permissionOverwrites.cache.map(o =>
PermissionOverwrites.resolve(o, this.guild),
permission_overwrites = newParent.permissionOverwrites.cache.map(overwrite =>
PermissionOverwrites.resolve(overwrite, this.guild),
);
}
} else if (channel.parent) {
permission_overwrites = channel.parent.permissionOverwrites.cache.map(o =>
PermissionOverwrites.resolve(o, this.guild),
permission_overwrites = channel.parent.permissionOverwrites.cache.map(overwrite =>
PermissionOverwrites.resolve(overwrite, this.guild),
);
}
}
Expand Down Expand Up @@ -438,11 +440,11 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error);
*/
async setPositions(channelPositions) {
channelPositions = channelPositions.map(r => ({
id: this.client.channels.resolveId(r.channel),
position: r.position,
lock_permissions: r.lockPermissions,
parent_id: r.parent !== undefined ? this.resolveId(r.parent) : undefined,
channelPositions = channelPositions.map(channelPosition => ({
id: this.client.channels.resolveId(channelPosition.channel),
position: channelPosition.position,
lock_permissions: channelPosition.lockPermissions,
parent_id: channelPosition.parent !== undefined ? this.resolveId(channelPosition.parent) : undefined,
}));

await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: channelPositions });
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/managers/GuildEmojiManager.js
Expand Up @@ -130,7 +130,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
async edit(emoji, options) {
const id = this.resolveId(emoji);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
const roles = options.roles?.map(r => this.guild.roles.resolveId(r));
const roles = options.roles?.map(role => this.guild.roles.resolveId(role));
const newData = await this.client.rest.patch(Routes.guildEmoji(this.guild.id, id), {
body: {
name: options.name,
Expand Down
3 changes: 2 additions & 1 deletion packages/discord.js/src/managers/MessageManager.js
Expand Up @@ -86,7 +86,8 @@ class MessageManager extends CachedManager {
* @example
* // Fetch messages and filter by a user id
* channel.messages.fetch()
* .then(messages => console.log(`${messages.filter(m => m.author.id === '84484653687267328').size} messages`))
* .then(messages => console.log(`${messages.filter(message =>
* message.author.id === '84484653687267328').size} messages`))
* .catch(console.error);
*/
fetch(options) {
Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/managers/RoleManager.js
Expand Up @@ -280,9 +280,9 @@ class RoleManager extends CachedManager {
*/
async setPositions(rolePositions) {
// Make sure rolePositions are prepared for API
rolePositions = rolePositions.map(o => ({
id: this.resolveId(o.role),
position: o.position,
rolePositions = rolePositions.map(rolePosition => ({
id: this.resolveId(rolePosition.role),
position: rolePosition.position,
}));

// Call the API to update role positions
Expand Down
5 changes: 4 additions & 1 deletion packages/discord.js/src/managers/UserManager.js
Expand Up @@ -40,7 +40,10 @@ class UserManager extends CachedManager {
* @private
*/
dmChannel(userId) {
return this.client.channels.cache.find(c => c.type === ChannelType.DM && c.recipientId === userId) ?? null;
return (
this.client.channels.cache.find(channel => channel.type === ChannelType.DM && channel.recipientId === userId) ??
null
);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/discord.js/src/structures/ActionRow.js
Expand Up @@ -18,7 +18,7 @@ class ActionRow extends Component {
* @type {Component[]}
* @readonly
*/
this.components = components.map(c => createComponent(c));
this.components = components.map(component => createComponent(component));
}

/**
Expand All @@ -39,7 +39,7 @@ class ActionRow extends Component {
* @returns {APIActionRowComponent}
*/
toJSON() {
return { ...this.data, components: this.components.map(c => c.toJSON()) };
return { ...this.data, components: this.components.map(component => component.toJSON()) };
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/ActionRowBuilder.js
Expand Up @@ -13,7 +13,7 @@ class ActionRowBuilder extends BuildersActionRow {
constructor({ components, ...data } = {}) {
super({
...toSnakeCase(data),
components: components?.map(c => createComponentBuilder(c)),
components: components?.map(component => createComponentBuilder(component)),
});
}

Expand Down
4 changes: 2 additions & 2 deletions packages/discord.js/src/structures/ApplicationCommand.js
Expand Up @@ -123,7 +123,7 @@ class ApplicationCommand extends Base {
* The options of this command
* @type {ApplicationCommandOption[]}
*/
this.options = data.options.map(o => this.constructor.transformOption(o, true));
this.options = data.options.map(option => this.constructor.transformOption(option, true));
} else {
this.options ??= [];
}
Expand Down Expand Up @@ -577,7 +577,7 @@ class ApplicationCommand extends Base {
[nameLocalizationsKey]: choice.nameLocalizations ?? choice.name_localizations,
value: choice.value,
})),
options: option.options?.map(o => this.transformOption(o, received)),
options: option.options?.map(opt => this.transformOption(opt, received)),
[channelTypesKey]: option.channelTypes ?? option.channel_types,
[minValueKey]: option.minValue ?? option.min_value,
[maxValueKey]: option.maxValue ?? option.max_value,
Expand Down
Expand Up @@ -32,7 +32,7 @@ class ChatInputCommandInteraction extends CommandInteraction {
this.commandName,
this.options._group,
this.options._subcommand,
...this.options._hoistedOptions.map(o => `${o.name}:${o.value}`),
...this.options._hoistedOptions.map(option => `${option.name}:${option.value}`),
];
return `/${properties.filter(Boolean).join(' ')}`;
}
Expand Down
10 changes: 5 additions & 5 deletions packages/discord.js/src/structures/ClientPresence.js
Expand Up @@ -68,11 +68,11 @@ class ClientPresence extends Presence {
}
} else if (!activities && (status || afk || since) && this.activities.length) {
data.activities.push(
...this.activities.map(a => ({
name: a.name,
state: a.state ?? undefined,
type: a.type,
url: a.url ?? undefined,
...this.activities.map(activity => ({
name: activity.name,
state: activity.state ?? undefined,
type: activity.type,
url: activity.url ?? undefined,
})),
);
}
Expand Down
6 changes: 4 additions & 2 deletions packages/discord.js/src/structures/Guild.js
Expand Up @@ -1263,7 +1263,7 @@ class Guild extends AnonymousGuild {
* @example
* // Delete a guild
* guild.delete()
* .then(g => console.log(`Deleted the guild ${g}`))
* .then(guild => console.log(`Deleted the guild ${guild}`))
* .catch(console.error);
*/
async delete() {
Expand Down Expand Up @@ -1365,7 +1365,9 @@ class Guild extends AnonymousGuild {
const channelIsCategory = channel.type === ChannelType.GuildCategory;
const types = getSortableGroupTypes(channel.type);
return discordSort(
this.channels.cache.filter(c => types.includes(c.type) && (channelIsCategory || c.parentId === channel.parentId)),
this.channels.cache.filter(
({ parentId, type }) => types.includes(type) && (channelIsCategory || parentId === channel.parentId),
),
);
}
}
Expand Down
10 changes: 6 additions & 4 deletions packages/discord.js/src/structures/GuildAuditLogsEntry.js
Expand Up @@ -164,7 +164,8 @@ class GuildAuditLogsEntry {
* Specific property changes
* @type {AuditLogChange[]}
*/
this.changes = data.changes?.map(c => ({ key: c.key, old: c.old_value, new: c.new_value })) ?? [];
this.changes =
data.changes?.map(change => ({ key: change.key, old: change.old_value, new: change.new_value })) ?? [];

/**
* The entry's id
Expand Down Expand Up @@ -302,10 +303,11 @@ class GuildAuditLogsEntry {
}),
);
} else if (targetType === Targets.Invite) {
let change = this.changes.find(c => c.key === 'code');
change = change.new ?? change.old;
const inviteChange = this.changes.find(({ key }) => key === 'code');

this.target = guild.invites.cache.get(change) ?? new Invite(guild.client, changesReduce(this.changes, { guild }));
this.target =
guild.invites.cache.get(inviteChange.new ?? inviteChange.old) ??
new Invite(guild.client, changesReduce(this.changes, { guild }));
} else if (targetType === Targets.Message) {
// Discord sends a channel id for the MessageBulkDelete action type.
this.target =
Expand Down
4 changes: 3 additions & 1 deletion packages/discord.js/src/structures/GuildChannel.js
Expand Up @@ -279,7 +279,9 @@ class GuildChannel extends BaseChannel {
* @readonly
*/
get members() {
return this.guild.members.cache.filter(m => this.permissionsFor(m).has(PermissionFlagsBits.ViewChannel, false));
return this.guild.members.cache.filter(member =>
this.permissionsFor(member).has(PermissionFlagsBits.ViewChannel, false),
);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/GuildEmoji.js
Expand Up @@ -91,7 +91,7 @@ class GuildEmoji extends BaseGuildEmoji {
* @example
* // Edit an emoji
* emoji.edit({ name: 'newemoji' })
* .then(e => console.log(`Edited emoji ${e}`))
* .then(emoji => console.log(`Edited emoji ${emoji}`))
* .catch(console.error);
*/
edit(options) {
Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/structures/Message.js
Expand Up @@ -141,7 +141,7 @@ class Message extends Base {
* in a guild for messages that do not mention the client.</info>
* @type {Embed[]}
*/
this.embeds = data.embeds.map(e => new Embed(e));
this.embeds = data.embeds.map(embed => new Embed(embed));
} else {
this.embeds = this.embeds?.slice() ?? [];
}
Expand All @@ -153,7 +153,7 @@ class Message extends Base {
* in a guild for messages that do not mention the client.</info>
* @type {ActionRow[]}
*/
this.components = data.components.map(c => createComponent(c));
this.components = data.components.map(component => createComponent(component));
} else {
this.components = this.components?.slice() ?? [];
}
Expand Down Expand Up @@ -181,7 +181,7 @@ class Message extends Base {
* @type {Collection<Snowflake, Sticker>}
*/
this.stickers = new Collection(
(data.sticker_items ?? data.stickers)?.map(s => [s.id, new Sticker(this.client, s)]),
(data.sticker_items ?? data.stickers)?.map(sticker => [sticker.id, new Sticker(this.client, sticker)]),
);
} else {
this.stickers = new Collection(this.stickers);
Expand Down
12 changes: 6 additions & 6 deletions packages/discord.js/src/structures/MessageMentions.js
Expand Up @@ -167,12 +167,12 @@ class MessageMentions {
this.crosspostedChannels = new Collection(crosspostedChannels);
} else {
this.crosspostedChannels = new Collection();
for (const d of crosspostedChannels) {
this.crosspostedChannels.set(d.id, {
channelId: d.id,
guildId: d.guild_id,
type: d.type,
name: d.name,
for (const crosspostedChannel of crosspostedChannels) {
this.crosspostedChannels.set(crosspostedChannel.id, {
channelId: crosspostedChannel.id,
guildId: crosspostedChannel.guild_id,
type: crosspostedChannel.type,
name: crosspostedChannel.name,
});
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/discord.js/src/structures/MessagePayload.js
Expand Up @@ -133,7 +133,9 @@ class MessagePayload {
}
}

const components = this.options.components?.map(c => (isJSONEncodable(c) ? c : new ActionRowBuilder(c)).toJSON());
const components = this.options.components?.map(component =>
(isJSONEncodable(component) ? component : new ActionRowBuilder(component)).toJSON(),
);

let username;
let avatarURL;
Expand Down
4 changes: 3 additions & 1 deletion packages/discord.js/src/structures/ModalBuilder.js
Expand Up @@ -12,7 +12,9 @@ class ModalBuilder extends BuildersModal {
constructor({ components, ...data } = {}) {
super({
...toSnakeCase(data),
components: components?.map(c => (c instanceof ComponentBuilder ? c : toSnakeCase(c))),
components: components?.map(component =>
component instanceof ComponentBuilder ? component : toSnakeCase(component),
),
});
}

Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/ModalSubmitFields.js
Expand Up @@ -20,7 +20,7 @@ class ModalSubmitFields {
* @type {Collection<string, ModalData>}
*/
this.fields = components.reduce((accumulator, next) => {
next.components.forEach(c => accumulator.set(c.customId, c));
next.components.forEach(component => accumulator.set(component.customId, component));
return accumulator;
}, new Collection());
}
Expand Down

0 comments on commit 11f6955

Please sign in to comment.