serious role position stuff (#1159)

* serious role position stuff

* kill meh

* Update Role.js

* Update Guild.js

* Update Role.js
This commit is contained in:
Gus Caplan
2017-02-01 16:02:16 -06:00
committed by Amish Shah
parent a2d6791cd8
commit 1e94a9e2a4
4 changed files with 39 additions and 23 deletions

View File

@@ -7,6 +7,7 @@ const Constants = require('../util/Constants');
const Collection = require('../util/Collection');
const cloneObject = require('../util/CloneObject');
const arraysEqual = require('../util/ArraysEqual');
const moveElementInArray = require('../util/MoveElementInArray');
/**
* Represents a guild (or a server) on Discord.
@@ -643,9 +644,10 @@ class Guild {
* Set the position of a role in this guild
* @param {string|Role} role the role to edit, can be a role object or a role ID.
* @param {number} position the new position of the role
* @param {boolean} [relative=false] Position moves the role relative to its current position
* @returns {Promise<Guild>}
*/
setRolePosition(role, position) {
setRolePosition(role, position, relative = false) {
if (typeof role === 'string') {
role = this.roles.get(role);
if (!role) return Promise.reject(new Error('Supplied role is not a role or string.'));
@@ -654,27 +656,12 @@ class Guild {
position = Number(position);
if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.'));
const lowestAffected = Math.min(role.position, position);
const highestAffected = Math.max(role.position, position);
let updatedRoles = Object.assign([], this.roles.array()
.sort((r1, r2) => r1.position !== r2.position ? r1.position - r2.position : r1.id - r2.id));
const rolesToUpdate = this.roles.filter(r => r.position >= lowestAffected && r.position <= highestAffected);
// stop role positions getting stupidly inflated
if (position > role.position) {
position = rolesToUpdate.first().position;
} else {
position = rolesToUpdate.last().position;
}
const updatedRoles = [];
for (const uRole of rolesToUpdate.values()) {
updatedRoles.push({
id: uRole.id,
position: uRole.id === role.id ? position : uRole.position + (position < role.position ? 1 : -1),
});
}
moveElementInArray(updatedRoles, role, position, relative);
updatedRoles = updatedRoles.map((r, i) => ({ id: r.id, position: i }));
return this.client.rest.methods.setRolePositions(this.id, updatedRoles);
}