refactor(api, curriculum): use the shared shuffleArray util (#56444)

Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
This commit is contained in:
Huyen Nguyen
2024-10-02 06:55:38 -07:00
committed by GitHub
parent 52ea949997
commit 0ba9eeff43
4 changed files with 8 additions and 42 deletions

View File

@@ -1,18 +1,4 @@
function shuffleArray(arr) {
let currentIndex = arr.length,
randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[arr[currentIndex], arr[randomIndex]] = [
arr[randomIndex],
arr[currentIndex]
];
}
return arr;
}
import { shuffleArray } from '../../../../shared/utils/shuffle-array';
function filterDeprecated(arr) {
return arr.filter(i => !i.deprecated);

View File

@@ -1,23 +1,7 @@
import { Exam, Question } from '@prisma/client';
import { shuffleArray } from './../../../shared/utils/shuffle-array';
import { UserExam, GeneratedExam } from './exam-types';
function shuffleArray<T>(arr: T[]): T[] {
let currentIndex: number = arr.length;
let randomIndex: number;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[arr[currentIndex], arr[randomIndex]] = [
arr[randomIndex] as T,
arr[currentIndex] as T
];
}
return arr;
}
/**
* Remove objects from array with deprecated: true.
*

View File

@@ -1,3 +1,4 @@
const { shuffleArray } = require('../../../shared/utils/shuffle-array');
const { sortChallenges } = require('./sort-challenges');
const challenges = [
@@ -222,7 +223,7 @@ const challenges = [
describe('sortChallenges', () => {
it('sorts challenges by superblock, block and challenge order', () => {
const copyOfChallenges = [...challenges];
shuffle(copyOfChallenges);
shuffleArray(copyOfChallenges);
const actualChallenges = sortChallenges(copyOfChallenges);
expect(actualChallenges).toEqual(challenges);
@@ -241,11 +242,3 @@ describe('sortChallenges', () => {
expect(actualChallenges[0]).not.toEqual(copyOfChallenges[0]);
});
});
// Use the FisherYates shuffle algorithm to shuffle array
const shuffle = arr => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
};

View File

@@ -4,7 +4,10 @@ export const shuffleArray = <T>(arrToShuffle: Array<T>) => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
// We know that i and j are within the bounds of the array, TS doesn't
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
[arr[i], arr[j]] = [arr[j]!, arr[i]!];
}
return arr;