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: compare with undefined directly #9191

Merged
merged 3 commits into from
Mar 12, 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
34 changes: 17 additions & 17 deletions packages/collection/src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class Collection<K, V> extends Map<K, V> {
public first(): V | undefined;
public first(amount: number): V[];
public first(amount?: number): V | V[] | undefined {
if (typeof amount === 'undefined') return this.values().next().value;
if (amount === undefined) return this.values().next().value;
if (amount < 0) return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
Expand All @@ -101,7 +101,7 @@ export class Collection<K, V> extends Map<K, V> {
public firstKey(): K | undefined;
public firstKey(amount: number): K[];
public firstKey(amount?: number): K | K[] | undefined {
if (typeof amount === 'undefined') return this.keys().next().value;
if (amount === undefined) return this.keys().next().value;
if (amount < 0) return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
Expand All @@ -119,7 +119,7 @@ export class Collection<K, V> extends Map<K, V> {
public last(amount: number): V[];
public last(amount?: number): V | V[] | undefined {
const arr = [...this.values()];
if (typeof amount === 'undefined') return arr[arr.length - 1];
if (amount === undefined) return arr[arr.length - 1];
if (amount < 0) return this.first(amount * -1);
if (!amount) return [];
return arr.slice(-amount);
Expand All @@ -136,7 +136,7 @@ export class Collection<K, V> extends Map<K, V> {
public lastKey(amount: number): K[];
public lastKey(amount?: number): K | K[] | undefined {
const arr = [...this.keys()];
if (typeof amount === 'undefined') return arr[arr.length - 1];
if (amount === undefined) return arr[arr.length - 1];
if (amount < 0) return this.firstKey(amount * -1);
if (!amount) return [];
return arr.slice(-amount);
Expand Down Expand Up @@ -178,7 +178,7 @@ export class Collection<K, V> extends Map<K, V> {
public random(amount: number): V[];
public random(amount?: number): V | V[] | undefined {
const arr = [...this.values()];
if (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];
if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount) return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
Expand All @@ -196,7 +196,7 @@ export class Collection<K, V> extends Map<K, V> {
public randomKey(amount: number): K[];
public randomKey(amount?: number): K | K[] | undefined {
const arr = [...this.keys()];
if (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];
if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount) return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
Expand Down Expand Up @@ -238,7 +238,7 @@ export class Collection<K, V> extends Map<K, V> {
public find<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;
public find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this)) return val;
}
Expand Down Expand Up @@ -267,7 +267,7 @@ export class Collection<K, V> extends Map<K, V> {
public findKey<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;
public findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this)) return key;
}
Expand All @@ -286,7 +286,7 @@ export class Collection<K, V> extends Map<K, V> {
public sweep<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;
public sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const previousSize = this.size;
for (const [key, val] of this) {
if (fn(val, key, this)) this.delete(key);
Expand Down Expand Up @@ -321,7 +321,7 @@ export class Collection<K, V> extends Map<K, V> {
public filter<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection<K, V>;
public filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection<K, V> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]<K, V>();
for (const [key, val] of this) {
if (fn(val, key, this)) results.set(key, val);
Expand Down Expand Up @@ -365,7 +365,7 @@ export class Collection<K, V> extends Map<K, V> {
thisArg?: unknown,
): [Collection<K, V>, Collection<K, V>] {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const results: [Collection<K, V>, Collection<K, V>] = [
new this.constructor[Symbol.species]<K, V>(),
new this.constructor[Symbol.species]<K, V>(),
Expand Down Expand Up @@ -418,7 +418,7 @@ export class Collection<K, V> extends Map<K, V> {
public map<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];
public map<T>(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, (): T => {
const [key, value] = iter.next().value;
Expand All @@ -441,7 +441,7 @@ export class Collection<K, V> extends Map<K, V> {
public mapValues<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection<K, T>;
public mapValues<T>(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection<K, T> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]<K, T>();
for (const [key, val] of this) coll.set(key, fn(val, key, this));
return coll;
Expand All @@ -462,7 +462,7 @@ export class Collection<K, V> extends Map<K, V> {
public some<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;
public some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this)) return true;
}
Expand Down Expand Up @@ -495,7 +495,7 @@ export class Collection<K, V> extends Map<K, V> {
public every<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;
public every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (!fn(val, key, this)) return false;
}
Expand All @@ -519,7 +519,7 @@ export class Collection<K, V> extends Map<K, V> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
let accumulator!: T;

if (typeof initialValue !== 'undefined') {
if (initialValue !== undefined) {
accumulator = initialValue;
for (const [key, val] of this) accumulator = fn(accumulator, val, key, this);
return accumulator;
Expand Down Expand Up @@ -585,7 +585,7 @@ export class Collection<K, V> extends Map<K, V> {
public tap<T>(fn: (this: T, collection: this) => void, thisArg: T): this;
public tap(fn: (collection: this) => void, thisArg?: unknown): this {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
if (thisArg !== undefined) fn = fn.bind(thisArg);
fn(this);
return this;
}
Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/client/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ class Client extends BaseClient {
* .catch(console.error);
*/
async fetchWebhook(id, token) {
const data = await this.rest.get(Routes.webhook(id, token), { auth: typeof token === 'undefined' });
const data = await this.rest.get(Routes.webhook(id, token), { auth: token === undefined });
return new Webhook(this, { token, ...data });
}

Expand Down Expand Up @@ -411,7 +411,7 @@ class Client extends BaseClient {
if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link');

const { scopes } = options;
if (typeof scopes === 'undefined') {
if (scopes === undefined) {
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
if (!Array.isArray(scopes)) {
Expand Down Expand Up @@ -485,7 +485,7 @@ class Client extends BaseClient {
* @private
*/
_validateOptions(options = this.options) {
if (typeof options.intents === 'undefined') {
if (options.intents === undefined) {
throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
} else {
options.intents = new IntentsBitField(options.intents).freeze();
Expand Down
4 changes: 2 additions & 2 deletions packages/discord.js/src/managers/GuildBanManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ class GuildBanManager extends CachedManager {
const resolvedUser = this.client.users.resolveId(user ?? options);
if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force });

if (!before && !after && !limit && typeof cache === 'undefined') {
if (!before && !after && !limit && cache === undefined) {
return Promise.reject(new DiscordjsError(ErrorCodes.FetchBanResolveId));
}

Expand Down Expand Up @@ -156,7 +156,7 @@ class GuildBanManager extends CachedManager {
const id = this.client.users.resolveId(user);
if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId, true);

if (typeof options.deleteMessageDays !== 'undefined' && !deprecationEmittedForDeleteMessageDays) {
if (options.deleteMessageDays !== undefined && !deprecationEmittedForDeleteMessageDays) {
process.emitWarning(
// eslint-disable-next-line max-len
'The deleteMessageDays option for GuildBanManager#create() is deprecated. Use the deleteMessageSeconds option instead.',
Expand Down
4 changes: 2 additions & 2 deletions packages/discord.js/src/managers/GuildChannelManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ class GuildChannelManager extends CachedManager {

const parent = options.parent && this.client.channels.resolveId(options.parent);

if (typeof options.position !== 'undefined') {
if (options.position !== undefined) {
await this.setPosition(channel, options.position, { position: options.position, reason: options.reason });
}

Expand Down Expand Up @@ -440,7 +440,7 @@ class GuildChannelManager extends CachedManager {
id: this.client.channels.resolveId(r.channel),
position: r.position,
lock_permissions: r.lockPermissions,
parent_id: typeof r.parent !== 'undefined' ? this.resolveId(r.parent) : undefined,
parent_id: r.parent !== undefined ? this.resolveId(r.parent) : undefined,
}));

await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: channelPositions });
Expand Down
11 changes: 4 additions & 7 deletions packages/discord.js/src/managers/GuildManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,7 @@ class GuildManager extends CachedManager {
roles: roles.map(({ color, permissions, ...options }) => ({
...options,
color: color && resolveColor(color),
permissions:
typeof permissions === 'undefined' ? undefined : PermissionsBitField.resolve(permissions).toString(),
permissions: permissions === undefined ? undefined : PermissionsBitField.resolve(permissions).toString(),
})),
channels: channels.map(
({
Expand All @@ -205,8 +204,8 @@ class GuildManager extends CachedManager {
video_quality_mode: videoQualityMode,
permission_overwrites: permissionOverwrites?.map(({ allow, deny, ...permissionOverwriteOptions }) => ({
...permissionOverwriteOptions,
allow: typeof allow === 'undefined' ? undefined : PermissionsBitField.resolve(allow).toString(),
deny: typeof deny === 'undefined' ? undefined : PermissionsBitField.resolve(deny).toString(),
allow: allow === undefined ? undefined : PermissionsBitField.resolve(allow).toString(),
deny: deny === undefined ? undefined : PermissionsBitField.resolve(deny).toString(),
})),
rate_limit_per_user: rateLimitPerUser,
}),
Expand All @@ -215,9 +214,7 @@ class GuildManager extends CachedManager {
afk_timeout: afkTimeout,
system_channel_id: systemChannelId,
system_channel_flags:
typeof systemChannelFlags === 'undefined'
? undefined
: SystemChannelFlagsBitField.resolve(systemChannelFlags),
systemChannelFlags === undefined ? undefined : SystemChannelFlagsBitField.resolve(systemChannelFlags),
},
});

Expand Down
4 changes: 2 additions & 2 deletions packages/discord.js/src/managers/GuildMemberManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -358,15 +358,15 @@ class GuildMemberManager extends CachedManager {
}
options.roles &&= options.roles.map(role => (role instanceof Role ? role.id : role));

if (typeof options.communicationDisabledUntil !== 'undefined') {
if (options.communicationDisabledUntil !== undefined) {
options.communication_disabled_until =
// eslint-disable-next-line eqeqeq
options.communicationDisabledUntil != null
? new Date(options.communicationDisabledUntil).toISOString()
: options.communicationDisabledUntil;
}

if (typeof options.flags !== 'undefined') {
if (options.flags !== undefined) {
options.flags = GuildMemberFlagsBitField.resolve(options.flags);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,12 @@ class GuildScheduledEventManager extends CachedManager {

let entity_metadata, channel_id;
if (entityType === GuildScheduledEventEntityType.External) {
channel_id = typeof channel === 'undefined' ? channel : null;
channel_id = channel === undefined ? channel : null;
entity_metadata = { location: entityMetadata?.location };
} else {
channel_id = this.guild.channels.resolveId(channel);
if (!channel_id) throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve);
entity_metadata = typeof entityMetadata === 'undefined' ? entityMetadata : null;
entity_metadata = entityMetadata === undefined ? entityMetadata : null;
}

const data = await this.client.rest.post(Routes.guildScheduledEvents(this.guild.id), {
Expand Down Expand Up @@ -214,7 +214,7 @@ class GuildScheduledEventManager extends CachedManager {

const data = await this.client.rest.patch(Routes.guildScheduledEvent(this.guild.id, guildScheduledEventId), {
body: {
channel_id: typeof channel === 'undefined' ? channel : this.guild.channels.resolveId(channel),
channel_id: channel === undefined ? channel : this.guild.channels.resolveId(channel),
name,
privacy_level: privacyLevel,
scheduled_start_time: scheduledStartTime ? new Date(scheduledStartTime).toISOString() : undefined,
Expand Down
7 changes: 3 additions & 4 deletions packages/discord.js/src/managers/RoleManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class RoleManager extends CachedManager {
async create(options = {}) {
let { name, color, hoist, permissions, position, mentionable, reason, icon, unicodeEmoji } = options;
color &&= resolveColor(color);
if (typeof permissions !== 'undefined') permissions = new PermissionsBitField(permissions);
if (permissions !== undefined) permissions = new PermissionsBitField(permissions);
if (icon) {
const guildEmojiURL = this.guild.emojis.resolve(icon)?.url;
icon = guildEmojiURL ? await DataResolver.resolveImage(guildEmojiURL) : await DataResolver.resolveImage(icon);
Expand Down Expand Up @@ -198,10 +198,9 @@ class RoleManager extends CachedManager {

const body = {
name: options.name,
color: typeof options.color === 'undefined' ? undefined : resolveColor(options.color),
color: options.color === undefined ? undefined : resolveColor(options.color),
hoist: options.hoist,
permissions:
typeof options.permissions === 'undefined' ? undefined : new PermissionsBitField(options.permissions),
permissions: options.permissions === undefined ? undefined : new PermissionsBitField(options.permissions),
mentionable: options.mentionable,
icon,
unicode_emoji: options.unicodeEmoji,
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/managers/ThreadManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ class ThreadManager extends CachedManager {
let timestamp;
let id;
const query = makeURLSearchParams({ limit });
if (typeof before !== 'undefined') {
if (before !== undefined) {
if (before instanceof ThreadChannel || /^\d{17,19}$/.test(String(before))) {
id = this.resolveId(before);
timestamp = this.resolve(before)?.archivedAt?.toISOString();
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/ApplicationCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ class ApplicationCommand extends Base {
// TODO: remove ?? 0 on each when nullable
(command.options?.length ?? 0) !== (this.options?.length ?? 0) ||
defaultMemberPermissions !== (this.defaultMemberPermissions?.bitfield ?? null) ||
(typeof dmPermission !== 'undefined' && dmPermission !== this.dmPermission) ||
(dmPermission !== undefined && dmPermission !== this.dmPermission) ||
!isEqual(command.nameLocalizations ?? command.name_localizations ?? {}, this.nameLocalizations ?? {}) ||
!isEqual(
command.descriptionLocalizations ?? command.description_localizations ?? {},
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/ClientPresence.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ClientPresence extends Presence {
set(presence) {
const packet = this._parse(presence);
this._patch(packet);
if (typeof presence.shardId === 'undefined') {
if (presence.shardId === undefined) {
this.client.ws.broadcast({ op: GatewayOpcodes.PresenceUpdate, d: packet });
} else if (Array.isArray(presence.shardId)) {
for (const shardId of presence.shardId) {
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/ClientUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class ClientUser extends User {
* @returns {Promise<ClientUser>}
*/
async edit(options) {
if (typeof options.avatar !== 'undefined') options.avatar = await DataResolver.resolveImage(options.avatar);
if (options.avatar !== undefined) options.avatar = await DataResolver.resolveImage(options.avatar);
const newData = await this.client.rest.patch(Routes.user(), { body: options });
this.client.token = newData.token;
this.client.rest.setToken(newData.token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ class CommandInteractionOptionResolver {
return null;
} else if (!allowedTypes.includes(option.type)) {
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionType, name, option.type, allowedTypes.join(', '));
} else if (required && properties.every(prop => option[prop] === null || typeof option[prop] === 'undefined')) {
} else if (required && properties.every(prop => option[prop] === null || option[prop] === undefined)) {
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionEmpty, name, option.type);
}
return option;
Expand Down
2 changes: 1 addition & 1 deletion packages/discord.js/src/structures/DMChannel.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class DMChannel extends BaseChannel {
* @readonly
*/
get partial() {
return typeof this.lastMessageId === 'undefined';
return this.lastMessageId === undefined;
}

/**
Expand Down