utils.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. }