utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Even-probability shuffle
  2. // https://en.m.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
  3. export function shuffle(array) {
  4. for (let i = array.length - 1; i > 0; i--) {
  5. let j = Math.floor(Math.random() * (i + 1));
  6. [array[i], array[j]] = [array[j], array[i]];
  7. }
  8. return array;
  9. }
  10. export function checkRemovedCount(oldArray, newArray, removedItems) {
  11. const expectedLength = oldArray.length - removedItems.length
  12. return newArray.length === expectedLength
  13. }
  14. export function splitArray(array, numPieces) {
  15. return array.reduce((splitArrays, item, index) => {
  16. const position = index % numPieces;
  17. return [
  18. ...splitArrays.slice(0, position),
  19. [...(splitArrays[position] || []), item],
  20. ...splitArrays.slice(position + 1)
  21. ];
  22. }, Array.from({ length: numPieces }, () => []));
  23. }
  24. export function annotateArray(labels, data) {
  25. return labels.reduce((zipped, label, index) => {
  26. return {...zipped, [label]: data[index]}
  27. }, {})
  28. }
  29. export function getRandomItem(array) {
  30. const index = Math.floor(Math.random() * array.length)
  31. return array[index]
  32. }
  33. export function removeFromArray(array, numToRemove) {
  34. return numToRemove ? array.slice(0, -numToRemove) : array
  35. }
  36. export function insertEntriesRandomlyIntoArray(array, count, entry = {}) {
  37. return Array.from({ length: count }).reduce((acc, _) => {
  38. // Generate a random index to insert the value
  39. const randomIndex = Math.floor(Math.random() * (array.length + 1));
  40. // Insert the value into the array at the random index
  41. return [...acc.slice(0, randomIndex), entry, ...acc.slice(randomIndex)];
  42. }, array)
  43. }