Guest User

Untitled

a guest
Jan 24th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.93 KB | None | 0 0
  1. While attempting to explain JavaScript's `reduce` method on arrays, conceptually, I came up with the following - hopefully it's helpful; happy to tweak it if anyone has suggestions.
  2.  
  3. ## Intro
  4. JavaScript Arrays have lots of built in methods on their prototype. Some of them *mutate* - ie, they change the underlying array in-place. Luckily, most of them do not - they instead return an entirely distinct array. Since arrays are conceptually a contiguous list of items, it helps code clarity and maintainability a lot to be able to operate on them in a "functional" way. (I'll also insist on referring to an array as a "list" - although in some languages, `List` is a native data type, in JS and this post, I'm referring to the concept. Everywhere I use the word "list" you can assume I'm talking about a JS Array) This means, to perform a single operation on the list as a whole ("atomically"), and to return a *new* list - thus making it much simpler to think about both the old list and the new one, what they contain, and what happened during the operation.
  5.  
  6. Below are some of the methods that *iterate* - in other words, that operate on the entire list, one item at a time. When you call them, you provide a *callback function* - a single function that expects to operate on one item at a time. Based on the Array method you've chosen, the callback gets specific arguments, and may be expected to return a certain kind of value - and (except for `forEach`) the return value determines the final return value of the overarching array operation. Although most of the methods are guaranteed to execute for *each* item in the array - for all of them - some of the methods can stop iterating partway through; when applicable, this is indicated below.
  7.  
  8. All array methods iterate in what is traditionally called "left to right" - more accurately (and less ethnocentrically) from index `0`, to index `length - 1` - also called "start" to "end". `reduceRight` is an exception in that it iterates in reverse - from `end` to `start`.
  9.  
  10. -------
  11.  
  12. `forEach`:
  13. - _callback answers_: here’s an item. do something nutty with it, i don't care what.
  14. - _callback gets these arguments_: `item`, `index`, `list`
  15. - _final return value_: nothing - in other words, `undefined`
  16. - _example use case_:
  17. ```js
  18. [1, 2, 3].forEach(function (item, index) {
  19. console.log(item, index);
  20. });
  21. ```
  22.  
  23. `map`:
  24. - _callback answers_: here’s an item. what should i put in the new list in its place?
  25. - _callback gets these arguments_: `item`, `index`, `list`
  26. - _final return value_: list of new items
  27. - _example use case_:
  28. ```js
  29. const three = [1, 2, 3];
  30. const doubled = three.map(function (item) {
  31. return item * 2;
  32. });
  33. console.log(three === doubled, doubled); // false, [2, 4, 6]
  34. ```
  35.  
  36. `filter`:
  37. - _callback is a predicate_ - it should return a truthy or falsy value
  38. - _callback answers_: should i keep this item?
  39. - _callback gets these arguments_: `item`, `index`, `list`
  40. - _final return value_: list of kept items
  41. - _example use case_:
  42. ```js
  43. const ints = [1, 2, 3];
  44. const evens = ints.filter(function (item) {
  45. return item % 2 === 0;
  46. });
  47. console.log(ints === evens, evens); // false, [2]
  48. ```
  49.  
  50. `reduce`:
  51. - _callback answers_: here’s the result from the previous iteration. what should i pass to the next iteration?
  52. - _callback gets these arguments_: `result`, `item`, `index`, `list`
  53. - _final return value_: result of last iteration
  54. - _example use case_:
  55. ```js
  56. // NOTE: `reduce` and `reduceRight` take an optional "initialValue" argument, after the reducer callback.
  57. // if omitted, it will default to the first item.
  58. const sum = [1, 2, 3].reduce(function (result, item) {
  59. return result + item;
  60. }, 0); // if the `0` is omitted, `1` will be the first `result`, and `2` will be the first `item`
  61. ```
  62.  
  63. `reduceRight`: (same as `reduce`, but in reversed order: last-to-first)
  64.  
  65. `some`:
  66. - _callback is a predicate_ - it should return a truthy or falsy value
  67. - _callback answers_: does this item meet your criteria?
  68. - _callback gets these arguments_: `item`, `index`, `list`
  69. - _final return value_: `true` after the first item that meets your criteria, else `false`
  70. - **note**: stops iterating once it receives a truthy value from your callback.
  71. - _example use case_:
  72. ```js
  73. const hasNegativeNumbers = [1, 2, 3, -1, 4].some(function (item) {
  74. return item < 0;
  75. });
  76. console.log(hasNegativeNumbers); // true
  77. ```
  78.  
  79. `every`:
  80. - _callback is a predicate_ - it should return a truthy or falsy value
  81. - _callback answers_: does this item meet your criteria?
  82. - _callback gets these arguments_: `item`, `index`, `list`
  83. - _final return value_: `false` after the first item that failed to meet your criteria, else `true`
  84. - **note**: stops iterating once it receives a falsy value from your callback.
  85. - _example use case_:
  86. ```js
  87. const allPositiveNumbers = [1, 2, 3].every(function (item) {
  88. return item > 0;
  89. });
  90. console.log(allPositiveNumbers); // true
  91. ```
  92.  
  93. `find`:
  94. - _callback is a predicate_ - it should return a truthy or falsy value
  95. - _callback answers_: is this item what you’re looking for?
  96. - _callback gets these arguments_: `item`, `index`, `list`
  97. - _final return value_: the item you’re looking for, or undefined
  98. - **note**: stops iterating once it receives a truthy value from your callback.
  99. - _example use case_:
  100. ```js
  101. const objects = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
  102. const found = objects.find(function (item) {
  103. return item.id === 'b';
  104. });
  105. console.log(found === objects[1]); // true
  106. ```
  107.  
  108. `findIndex`:
  109. - _callback is a predicate_ - it should return a truthy or falsy value
  110. - _callback answers_: is this item what you’re looking for?
  111. - _callback gets these arguments_: `item`, `index`, `list`
  112. - _final return value_: the index of the item you’re looking for, or `-1`
  113. - **note**: stops iterating once it receives a truthy value from your callback.
  114. - _example use case_:
  115. ```js
  116. const objects = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
  117. const foundIndex = objects.findIndex(function (item) {
  118. return item.id === 'b';
  119. });
  120. console.log(foundIndex === 1); // true
  121. ```
Add Comment
Please, Sign In to add comment