Skip to content

Commit

Permalink
fix: don't mutate user provided array (#10014)
Browse files Browse the repository at this point in the history
* fix(builders): don't mutate user provided array

* test: add normalize array tests

* chore: revert vscode autochange

* Update util.test.ts

* refactor: remove unnecessary clone

---------

Co-authored-by: Vlad Frangu <me@vladfrangu.dev>
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Almeida <github@almeidx.dev>
  • Loading branch information
4 people committed Apr 30, 2024
1 parent 798f28c commit 7ea3638
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
18 changes: 17 additions & 1 deletion packages/builders/__tests__/util.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest';
import { enableValidators, disableValidators, isValidationEnabled } from '../src/index.js';
import { enableValidators, disableValidators, isValidationEnabled, normalizeArray } from '../src/index.js';

describe('validation', () => {
test('enables validation', () => {
Expand All @@ -12,3 +12,19 @@ describe('validation', () => {
expect(isValidationEnabled()).toBeFalsy();
});
});

describe('normalizeArray', () => {
test('normalizes an array or array (when input is an array)', () => {
expect(normalizeArray([[1, 2, 3]])).toEqual([1, 2, 3]);
});

test('normalizes an array (when input is rest parameter)', () => {
expect(normalizeArray([1, 2, 3])).toEqual([1, 2, 3]);
});

test('always returns a clone', () => {
const arr = [1, 2, 3];
expect(normalizeArray([arr])).toEqual(arr);
expect(normalizeArray([arr])).not.toBe(arr);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder<APIMenti
) {
const normalizedValues = normalizeArray(values);
optionsLengthValidator.parse(normalizedValues.length);
this.data.default_values = normalizedValues.slice();
this.data.default_values = normalizedValues;
return this;
}
}
2 changes: 1 addition & 1 deletion packages/builders/src/util/normalizeArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @param arr - The (possibly variadic) data to normalize
*/
export function normalizeArray<ItemType>(arr: RestOrArray<ItemType>): ItemType[] {
if (Array.isArray(arr[0])) return arr[0];
if (Array.isArray(arr[0])) return [...arr[0]];
return arr as ItemType[];
}

Expand Down

0 comments on commit 7ea3638

Please sign in to comment.