Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. import Immutable from 'immutable';
  2.  
  3. const { isIterable } = Immutable.Iterable;
  4. const { isMap } = Immutable.Map;
  5. const { isList } = Immutable.List;
  6.  
  7. const isLeafNode = (node) => {
  8. if (!isIterable(node)) {
  9. return true;
  10. }
  11.  
  12. if (node.size === 0) {
  13. return true;
  14. }
  15.  
  16. return false;
  17. };
  18.  
  19. /**
  20. * Like Immutable.Map.filter except traverses all Maps in a data structure
  21. * of deeply nested Maps and Lists. For example:
  22. *
  23. * ```
  24. * import Immutable from 'immutable';
  25. * import { immutableDeepFilter } from 'nl-react/state/utils';
  26. *
  27. * const KEY_TO_DELETE = 'some-key';
  28. * const iterable = Immutable.fromJS({
  29. * [KEY_TO_DELETE]: '',
  30. * foo: {
  31. * [KEY_TO_DELETE]: '',
  32. * bar: [
  33. * {
  34. * [KEY_TO_DELETE]: '',
  35. * foo: 'bar'
  36. * }
  37. * ]
  38. * }
  39. * });
  40. *
  41. * const filteredIterable = immutableDeepFilter(
  42. * iterable,
  43. * (value, key) => key === KEY_TO_DELETE
  44. * );
  45. *
  46. * console.log(filteredIterable.toJS());
  47. * // => {
  48. * foo: {
  49. * bar: [
  50. * { foo: 'bar' }
  51. * ]
  52. * }
  53. * }
  54. * ```
  55. *
  56. * @author istorz
  57. * @param {Iterable} node - the Map or List to deeply filter
  58. * @param {String} predicate - filtering function
  59. * @return {Iterable} the deeply filtered iterable
  60. * @see ./deep-filter.spec.js
  61. */
  62. const deepFilter = (node, predicate) => {
  63. if (isLeafNode(node)) {
  64. return node;
  65. }
  66.  
  67. return node.withMutations((mutableNode) => {
  68. if (isList(mutableNode)) {
  69. mutableNode.forEach((value, index) => {
  70. mutableNode.update(
  71. index,
  72. currentValue => deepFilter(currentValue, predicate)
  73. );
  74. });
  75. }
  76.  
  77. if (isMap(mutableNode)) {
  78. mutableNode.forEach((value, key) => {
  79. if (predicate(value, key)) {
  80. mutableNode.delete(key);
  81. } else {
  82. mutableNode.update(
  83. key,
  84. currentValue => deepFilter(currentValue, predicate)
  85. );
  86. }
  87. });
  88. }
  89. });
  90. };
  91.  
  92. export default deepFilter;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement