You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 line
1.0 KiB

3 年之前
  1. 'use strict';
  2. const unique = arr => arr.filter((v, i) => arr.lastIndexOf(v) === i);
  3. const compact = arr => unique(arr).filter(Boolean);
  4. module.exports = (action, data = {}, value = '') => {
  5. let { past = [], present = '' } = data;
  6. let rest, prev;
  7. switch (action) {
  8. case 'prev':
  9. case 'undo':
  10. rest = past.slice(0, past.length - 1);
  11. prev = past[past.length - 1] || '';
  12. return {
  13. past: compact([value, ...rest]),
  14. present: prev
  15. };
  16. case 'next':
  17. case 'redo':
  18. rest = past.slice(1);
  19. prev = past[0] || '';
  20. return {
  21. past: compact([...rest, value]),
  22. present: prev
  23. };
  24. case 'save':
  25. return {
  26. past: compact([...past, value]),
  27. present: ''
  28. };
  29. case 'remove':
  30. prev = compact(past.filter(v => v !== value));
  31. present = '';
  32. if (prev.length) {
  33. present = prev.pop();
  34. }
  35. return {
  36. past: prev,
  37. present
  38. };
  39. default: {
  40. throw new Error(`Invalid action: "${action}"`);
  41. }
  42. }
  43. };