Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Map $callable over the given array. Point is that array_map:
  5. * (1) only works on literal arrays, and
  6. * (2) doesn't pass the key into the callback.
  7. *
  8. * @param $array
  9. * @param \Closure $callable ($value, $key) => mixed
  10. *
  11. * @return array
  12. */
  13. function map($array, $callable)
  14. {
  15. if (!$array) {
  16. return array();
  17. }
  18.  
  19. $result = array();
  20. foreach ($array as $key => $value) {
  21. $result[] = $callable($value, $key);
  22. }
  23.  
  24. return $result;
  25. }
  26.  
  27. /**
  28. * Construct an associative array by returning pairs ([$key, $value]) for each
  29. * element of $array
  30. *
  31. * @param $array
  32. * @param \Closure $callable
  33. *
  34. * @return array
  35. */
  36. function zip($array, $callable)
  37. {
  38. if (!$array) {
  39. return array();
  40. }
  41.  
  42. $zipped = array();
  43. foreach ($array as $key => $value) {
  44. $result = call_user_func($callable, $value, $key, $array);
  45. if (!is_array($result) || count($result) !== 2) {
  46. continue;
  47. }
  48.  
  49. list($zKey, $zValue) = $result;
  50. $zipped[$zKey] = $zValue;
  51. }
  52.  
  53. return $zipped;
  54. }
  55.  
  56. /**
  57. * Find the first value in $array that satisfies $predicate.
  58. *
  59. * @param $array
  60. * @param callable $predicate ($item, $arrayKey, $array) => boolean (true if greater)
  61. *
  62. * @return mixed|null
  63. */
  64. function first($array, $predicate = null)
  65. {
  66.  
  67. foreach ($array as $key => $value) {
  68. $result = $predicate
  69. ? call_user_func($predicate, $value, $key, $array)
  70. : $value;
  71.  
  72. if ($result) {
  73. return $value;
  74. }
  75. }
  76.  
  77. return null;
  78. }
  79.  
  80. /**
  81. * Cycles through array and returns an array with only the items that match $predicate
  82. * @param $array
  83. * @param callable $predicate ($item, $arrayKey, $array) => boolean
  84. * @return array
  85. */
  86. function filter($array, $predicate = null)
  87. {
  88. $result = [];
  89. $predicate = $predicate ?? function($thing) { return $thing; };
  90.  
  91. foreach ($array as $key => $value) {
  92. if (!call_user_func($predicate, $value, $key, $array)) {
  93. continue;
  94. }
  95.  
  96. $result[] = $value;
  97. }
  98.  
  99. return $result;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement