array-utils.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { range } from 'lodash';
  2. // NOTE: All the array operations defined here should be non-mutating.
  3. export function uniformSelect(array, size) {
  4. if (size > array.length) {
  5. return array;
  6. }
  7. return range(size)
  8. .map(index => array[parseInt(index * (array.length / (size - (1 - 1e-9))), 10)]);
  9. }
  10. export function insertElement(array, index, element) {
  11. return array.slice(0, index).concat([element], array.slice(index));
  12. }
  13. export function removeElement(array, index) {
  14. return array.slice(0, index).concat(array.slice(index + 1));
  15. }
  16. export function moveElement(array, from, to) {
  17. if (from === to) {
  18. return array;
  19. }
  20. return insertElement(removeElement(array, from), to, array[from]);
  21. }
  22. export function intersperse(items, value) {
  23. //
  24. // intersperse([1, 2, 3], 'a') => [1, 'a', 2, 'a', 3]
  25. //
  26. // Useful for when you wanna do: [<MyReactListItem />, <MyReactListItem />].join(' ')
  27. // But you can't because React Components aren't strings.
  28. //
  29. // intersperse([<MyReactListItem />, <MyReactListItem />], ' ')
  30. // Will get you there!
  31. //
  32. return [].concat(...items.map(e => [value, e])).slice(1);
  33. }