Skip to content

Commit

Permalink
perf(Channel): linear speed position getter
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranet committed May 1, 2023
1 parent e262df9 commit e0c74a8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
9 changes: 5 additions & 4 deletions packages/discord.js/src/structures/Guild.js
Original file line number Diff line number Diff line change
Expand Up @@ -1304,13 +1304,14 @@ class Guild extends AnonymousGuild {
* @private
*/
_sortedChannels(channel) {
const category = channel.type === ChannelType.GuildCategory;
const channelTypes = [ChannelType.GuildText, ChannelType.GuildAnnouncement];
const channelIsCategory = channel.type === ChannelType.GuildCategory;
const movableTypes = [ChannelType.GuildText, ChannelType.GuildAnnouncement, ChannelType.GuildForum];
const movableChannel = movableTypes.includes(channel.type);
return discordSort(
this.channels.cache.filter(
c =>
(channelTypes.includes(channel.type) ? channelTypes.includes(c.type) : c.type === channel.type) &&
(category || c.parent === channel.parent),
(movableChannel ? movableTypes.includes(c.type) : c.type === channel.type) &&
(channelIsCategory || c.parent === channel.parent),
),
);
}
Expand Down
18 changes: 15 additions & 3 deletions packages/discord.js/src/structures/GuildChannel.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const { PermissionFlagsBits } = require('discord-api-types/v10');
const { PermissionFlagsBits, ChannelType } = require('discord-api-types/v10');
const { BaseChannel } = require('./BaseChannel');
const { DiscordjsError, ErrorCodes } = require('../errors');
const PermissionOverwriteManager = require('../managers/PermissionOverwriteManager');
Expand Down Expand Up @@ -145,8 +145,20 @@ class GuildChannel extends BaseChannel {
* @readonly
*/
get position() {
const sorted = this.guild._sortedChannels(this);
return [...sorted.values()].indexOf(sorted.get(this.id));
const selfIsCategory = this.type === ChannelType.GuildCategory;
const movableTypes = [ChannelType.GuildText, ChannelType.GuildAnnouncement, ChannelType.GuildForum];
const movableSelf = movableTypes.includes(this.type);
return this.guild.channels.cache.reduce(
(acc, channel) =>
acc +
((movableSelf ? movableTypes.includes(channel.type) : channel.type === this.type) &&
(selfIsCategory || channel.parent === this.parent))
? this.rawPosition === channel.rawPosition
? BigInt(this.id) < BigInt(channel.id)
: this.rawPosition > channel.rawPosition
: 0,
0,
);
}

/**
Expand Down

0 comments on commit e0c74a8

Please sign in to comment.