function sum($collection) { $sum = reduce($collection, function ($sum, $value) { return $sum += $value; }, 0); return $sum; }
function reduce($fn, $list, $value = null) { if (empty($list)) { return $value; } $value = $fn(car($list), $value); return reduce($fn, cdr($list), $value); }
/** * Takes a set of functions and returns a new one that is the composition of those `$fns`. * The result from the first function execution is piped in to the second function and so on. * * @since 0.1 * * @param callable[] $fns functions to be piped * * @return mixed */ function pipe(...$fns) { $compose = function ($composition, $fn) { return function (...$args) use($composition, $fn) { return null === $composition ? $fn(...$args) : $fn($composition(...$args)); }; }; return reduce($compose, $fns); }
function test_reduce() { $a = function ($acc, $x) { return $acc + $x; }; $range = range(0, 5); return is_identical(reduce($a, 1, $range), 16); // 1+0+1+2+3+4+5 }
function test_reduce_basic() { $input = [1, 2, 3]; $initial = 0; $expect = 6; $combining_function = reduce($initial); $reduce = $combining_function($this->sum()); $actual = $reduce($input); $this->assertEquals($expect, $actual); }
function max($initial) { return function (callable $maxer = null) use($initial) { if ($maxer === NULL) { $maxer = "max"; } $r = reduce($initial); return $r($maxer); }; }
function max($collection) { if (isEmpty($collection)) { return null; } $max = reduce($collection, function ($max, $value) { return \max($max, $value); }, -INF); return $max; }
function min($collection) { if (isEmpty($collection)) { return null; } $min = reduce($collection, function ($min, $value) { return \min($min, $value); }, +INF); return $min; }
/** * Computes the product of an array of numbers. * ```php * product([1, 2, 3, 4]) // 24 * product([]) // 1 * ``` * * @signature [Number] -> Number * @param array $numbers * @return int|float */ function product() { return apply(curry(function ($numbers) { return reduce(multiply(), 1, $numbers); }), func_get_args()); }
?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="3.php" method="post"> <input type="number" name="num" id="num"><label for="num">Введите максимальное количество символов для файла</label> <input type="submit" name="submit" value="Submit"> </form> </body> </html> <?php function reduce($a) { $f = explode(" ", file_get_contents('3-text.txt')); foreach ($f as $key => $item) { if (mb_strlen($item) > $a) { unset($f[$key]); } } echo "<pre>"; $f = array_values($f); file_put_contents("3-text.txt", implode(' ', $f)); } if (!empty($_POST['num'])) { reduce($_POST['num']); }
if (strlen($_POST['scanned_barcode']) == $db->barcode_length && substr($_POST['scanned_barcode'], 0, 1) == $db->barcode_scan_prefix) { header("location:" . $db->url_root . "/link_cover_scans.php/" . $_POST['scanned_barcode']); exit; } // end if if (strlen($_POST['scanned_barcode']) == $db->barcode_length && substr($_POST['scanned_barcode'], 0, 1) == $db->barcode_item_prefix) { $item_sql = "\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\t`" . $db->table_library_item . "`\n\t\t\tWHERE\n\t\t\t\t`barcode`='" . mysql_escape_string($_POST['scanned_barcode']) . "'\n\t\t\t\tAND `enabled`='Y'\n\t\t"; $item_result = mysql_query($item_sql, $mysql->link); if (mysql_num_rows($item_result) > 0) { $item_record = mysql_fetch_object($item_result); $insert_sql = "\n\t\t\t\tINSERT INTO\n\t\t\t\t\t`" . $db->table_library_image . "`\n\t\t\t\tSET\n\t\t\t\t\t`" . $db->field_library_item_ID . "`='" . $item_record->ID . "'\n\t\t\t"; $insert_result = mysql_query($insert_sql, $mysql->link); $new_image_ID = mysql_insert_id($mysql->link); $update_item_sql = "\n\t\t\t\tUPDATE\n\t\t\t\t\t`" . $db->table_library_item . "`\n\t\t\t\tSET\n\t\t\t\t\t`" . $db->field_image_ID . "`='" . $new_image_ID . "'\n\t\t\t\tWHERE\n\t\t\t\t\t`ID`='" . $item_record->ID . "'\n\t\t\t"; mysql_query($update_item_sql, $mysql->link); reduce($db->import_image_dir . "/" . $barcode . ".jpg", $db->cover_thumbs_image_dir . "/" . substr($new_image_ID, 0, 1) . "/" . $new_image_ID . ".jpg", 200, 200); if (copy($db->import_image_dir . "/" . $barcode . ".jpg", $db->cover_image_dir . "/" . substr($new_image_ID, 0, 1) . "/" . $new_image_ID . ".jpg")) { unlink($db->import_image_dir . "/" . $barcode . ".jpg"); } // end if header("location:" . $db->url_root . "/item_details.php/barcode/" . $_POST['scanned_barcode']); exit; } else { exit_error("Item Not Found", "And item with the barcode you entered could not be found!"); } // end if } else { exit_error("Try Again", "Scan top barcode again."); } // end if }
function near($residence, $no) { if ($residence > 0) { $marks = reduce(50, $no, 5); if ($marks > 0) { return $marks; } } return 0; }
/** @test */ public function shouldProvideCorrectBasisValue() { $insertIntoArray = function ($arr, $val, $i) { $arr[$i] = $val; return $arr; }; $d1 = new Deferred(); $d2 = new Deferred(); $d3 = new Deferred(); $mock = $this->createCallableMock(); $mock->expects($this->once())->method('__invoke')->with($this->identicalTo([1, 2, 3])); reduce([$d1->promise(), $d2->promise(), $d3->promise()], $insertIntoArray, [])->then($mock); $d3->resolve(3); $d1->resolve(1); $d2->resolve(2); }
echo $dir . "/" . $file . "\n"; } } } //look at the next dir $dir = array_pop($dirstack); } //check the entire set if (runs($filelist)) { echo "I can not detect a problem. \n"; exit; } //check half of the set and discard if that half is okay $res = $filelist; $i = 0; do { $i = count($res); echo $i . "/" . count($fileset) . " elements remaining. \n"; $res = reduce($res, count($res) / 2); shuffle($res); } while (count($res) < $i); //check one file after another $needed = array(); while (count($res) != 0) { $file = array_pop($res); if (runs(array_merge($res, $needed))) { echo "needs: " . $file . " and file count " . count($needed); array_push($needed, $file); } } echo "\nSmallest Set is: " . namesList($needed) . " with " . count($needed) . " files. ";
/** * Gets a value from an array/object using a path of keys/attributes. * ```php * $data = [ * ['name' => 'foo', 'type' => 'test'], * ['name' => 'bar', 'type' => 'test'], * (object) ['name' => 'baz', 'scores' => [1, 2, 3]] * ]; * $nameOfFirst = getPath([0, 'name']); * $nameOfFirst($data); // 'foo' * getPath([2, 'scores', 1]); // 2 * ``` * * @signature [k] -> {k: v} -> v * @param array $path * @param mixed $object * @return mixed */ function getPath() { $getPath = function ($path, $object) { return reduce(function ($result, $name) { if ($result !== null) { $result = get($name, $result); } return $result; }, $object, $path); }; return apply(curry($getPath), func_get_args()); }
public function reduce($callback, $initial = NULL) { return reduce($this, $callback, $initial); }
function frequencies($arr) { return reduce(function ($frequencies, $item) { if (isset($frequencies[$item])) { $frequencies[$item]++; } else { $frequencies[$item] = 1; } return $frequencies; }, $arr, []); }
<?php if (version_compare(PHP_VERSION, '5.5.0') <= 0) { die('This example requires at least PHP version 5.5.0' . PHP_EOL . ' but you are only running version ' . PHP_VERSION . PHP_EOL); } include __DIR__ . '/classes/Bootstrap.php'; include __DIR__ . '/functions/map.php'; include __DIR__ . '/functions/reduce.php'; // Create our initial Generator to read the gpx file $gpxFilename = __DIR__ . '/data/Roman_2015-11-23.gpx'; $gpxReader = new GpxReader\GpxHandler($gpxFilename); // Set the mapper to calculate the distance between a trackpoint and the previous trackpoint $distanceCalculator = new GpxReader\Helpers\DistanceCalculator(); // Reduce our trackpoint set from the gpx file (mapping the distance as we go) and summing the results to calculate the total distance travelled $totalDistance = reduce(map([$distanceCalculator, 'setDistance'], $gpxReader->getElements('trkpt')), function ($runningTotal, $value) { $runningTotal += $value->distance; return $runningTotal; }, 0.0); // Display the results of our reduce printf('Total distance travelled is %5.2f km' . PHP_EOL, $totalDistance / 1000);
/** * @param callable $fn * @param mixed|null $initial * * @return mixed */ public function reduce(callable $fn, $initial = null) { return reduce($fn, $this->xs, $initial); }
function reduce($combiner, $in, $identity) { if (!empty($in)) { return $combiner(first($in), reduce($combiner, rest($in), $identity)); } else { $identity; } }
public function testReduce() { $this->assertSame(15, reduce(fn\operator('+'), range(1, 5), 0)); $this->assertSame(120, reduce(fn\operator('*'), range(1, 5), 1)); }
/** * Converts an array to an associative array, based on the result of calling `$fn` * on each element, and grouping the results according to values returned. * Note that `$fn` should take an item from the list and return a string. * ```php * $persons = [ * ['name' => 'foo', 'age' => 11], * ['name' => 'bar', 'age' => 9], * ['name' => 'baz', 'age' => 16], * ['name' => 'zeta', 'age' => 33], * ['name' => 'beta', 'age' => 25] * ]; * $phase = function($person) { * $age = $person['age']; * if ($age < 13) return 'child'; * if ($age < 19) return 'teenager'; * return 'adult'; * }; * groupBy($phase, $persons); * // [ * // 'child' => [['name' => 'foo', 'age' => 11], ['name' => 'bar', 'age' => 9]], * // 'teenager' => [['name' => 'baz', 'age' => 16]], * // 'adult' => [['name' => 'zeta', 'age' => 33], ['name' => 'beta', 'age' => 25]] * // ] * ``` * * @signature (a -> String) -> [a] -> {String: a} * @param callable $fn * @param array $list * @return array */ function groupBy() { $groupBy = function ($fn, $list) { return reduce(function ($result, $item) use($fn) { $index = $fn($item); if (!isset($result[$index])) { $result[$index] = []; } $result[$index][] = $item; return $result; }, [], $list); }; return apply(curry($groupBy), func_get_args()); }
/** @test */ public function shouldCancelInputArrayPromises() { $mock1 = $this->getMock('React\\Promise\\CancellablePromiseInterface'); $mock1->expects($this->once())->method('cancel'); $mock2 = $this->getMock('React\\Promise\\CancellablePromiseInterface'); $mock2->expects($this->once())->method('cancel'); reduce([$mock1, $mock2], $this->plus(), 1)->cancel(); }
public function dropTabs($selected_tab = 0) { global $IconPath; //get all sections for current tab $q = "SELECT sec.*\n \t\t FROM section sec\n \t\t INNER JOIN tab t\n \t\t ON sec.tab_id = t.tab_id\n \t\t INNER JOIN subject s\n \t\t ON t.subject_id = s.subject_id\n \t\t WHERE t.tab_index = {$selected_tab}\n \t\t AND s.subject_id = '{$this->_subject_id}'\n \t\t ORDER BY section_index ASC"; $db = new Querier(); $lobjSections = $db->query($q); foreach ($lobjSections as $lobjSection) { print "<div id=\"section_{$lobjSection['section_id']}\" class=\"sp_section pure-g\" data-layout=\"{$lobjSection['layout']}\">"; if ($this->_isAdmin) { print "<div class=\"sp_section_controls\">\n \t\t\t\t\t\t<i class=\"fa fa-arrows section_sort\" title=\"Move Section\"></i>\n <i class=\"fa fa-trash-o section_remove\" title=\"Delete Section\"></i>\n\n \t\t\t\t\t\t<div id=\"slider_section_{$lobjSection['section_id']}\" class=\"sp_section_slider\"></div>\n \t\t\t\t </div>"; } $qc = "SELECT p.pluslet_id, p.title, p.body, ps.pcolumn, p.type, p.extra\n\t\t FROM pluslet p\n\t\t INNER JOIN pluslet_section ps\n\t\t ON p.pluslet_id = ps.pluslet_id\n\t\t INNER JOIN section sec\n\t\t ON ps.section_id = sec.section_id\n\t\t WHERE sec.section_id = {$lobjSection['section_id']}\n\t\t ORDER BY prow ASC"; $rc = $db->query($qc); //init $left_col_pluslets = ""; $main_col_pluslets = ""; $sidebar_pluslets = ""; foreach ($rc as $myrow) { // Get our guide type // Make sure it's not blank, as that will throw an error if ($myrow["type"] != "") { if ($myrow["type"] == "Special") { $obj = __NAMESPACE__ . "\\Pluslet_" . $myrow[0]; } else { $obj = __NAMESPACE__ . "\\Pluslet_" . $myrow[4]; } //global $obj; $record = new $obj($myrow[0], "", $this->_subject_id); $view = $this->_isAdmin ? "admin" : "public"; switch ($myrow[3]) { case 0: # code... $left_col_pluslets .= $record->output("view", $view); break; case 1: default: # code... $main_col_pluslets .= $record->output("view", $view); break; case 2: # code... $sidebar_pluslets .= $record->output("view", $view); break; } } unset($record); } if ($this->_isAdmin) { print $this->dropBoxes(0, 'left', $left_col_pluslets); print $this->dropBoxes(1, 'center', $main_col_pluslets); print $this->dropBoxes(2, 'sidebar', $sidebar_pluslets); print '<div id="clearblock" style="clear:both;"></div> <!-- this just seems to allow the space to grow to fit dropbox areas -->'; } else { $col_widths = explode("-", $lobjSection['layout']); $purified = ""; // init if (isset($col_widths[0]) && $col_widths[0] > 0) { $purified = reduce($col_widths[0], 12); $pure_left = "pure-u-1 pure-u-md-" . $purified[0] . "-" . $purified[1]; $left_width = $col_widths[0]; } else { $left_width = 0; } if (isset($col_widths[1])) { $purified = reduce($col_widths[1], 12); $pure_center = "pure-u-1 pure-u-md-" . $purified[0] . "-" . $purified[1]; $main_width = $col_widths[1]; } else { $main_width = 0; } if (isset($col_widths[2]) && $col_widths[2] > 0) { $purified = reduce($col_widths[2], 12); $pure_right = "pure-u-1 pure-u-md-" . $purified[0] . "-" . $purified[1]; $side_width = $col_widths[2]; } else { $side_width = 0; } // make sure they aren't 0 if ($left_width > 0) { /*print "<div class='span$left_width'> $left_col_pluslets </div>";*/ print "<div class='{$pure_left}'>\n \t\t\t\t\t{$left_col_pluslets}\n \t\t\t\t\t</div>"; } if ($main_width > 0) { print "<div class='{$pure_center}'>\n \t\t\t\t\t{$main_col_pluslets}\n \t\t\t\t\t</div>"; /*print "<div class='span$main_width'> $main_col_pluslets </div>";*/ } if ($side_width > 0) { print "<div class='{$pure_right}'>\n \t\t\t\t\t{$sidebar_pluslets}\n \t\t\t\t\t</div>"; /*print "<div class='span$side_width'> $sidebar_pluslets </div>";*/ } } print "</div>"; } }
private function doInvoke(BytesIO $stream, stdClass $context) { $results = array(); $reader = new Reader($stream); do { $reader->reset(); $name = $reader->readString(); $alias = strtolower($name); $cc = new stdClass(); $cc->isMissingMethod = false; foreach ($context as $key => $value) { $cc->{$key} = $value; } if (isset($this->calls[$alias])) { $call = $this->calls[$alias]; } else { if (isset($this->calls['*'])) { $call = $this->calls['*']; $cc->isMissingMethod = true; } } if ($call) { foreach ($call as $key => $value) { $cc->{$key} = $value; } } $args = array(); $cc->byref = false; $tag = $stream->getc(); if ($tag === Tags::TagList) { $reader->reset(); $args = $reader->readListWithoutTag(); $tag = $stream->getc(); if ($tag === Tags::TagTrue) { $cc->byref = true; $tag = $stream->getc(); } } if ($tag !== Tags::TagEnd && $tag !== Tags::TagCall) { $data = $stream->toString(); throw new Exception("Unknown tag: {$tag}\r\nwith following data: {$data}"); } if ($call) { $results[] = $this->beforeInvoke($name, $args, $cc); } else { $results[] = $this->sendError(new Exception("Can\\'t find this function {$name}()."), $cc); } } while ($tag === Tags::TagCall); return reduce($results, function ($stream, $result) { $stream->write($result); return $stream; }, new BytesIO())->then(function ($stream) { $stream->write(Tags::TagEnd); $data = $stream->toString(); $stream->close(); return $data; }); }
if (count($errors) < 1) { if ($_FILES['upload_cover_art']['type'] == "image/jpeg") { if ($item_ID != "") { $image_sql = "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t*\n\t\t\t\t\tFROM\n\t\t\t\t\t\t`" . $db->table_library_image . "`\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t`" . $db->field_library_item_ID . "`='" . mysql_escape_string($item_ID) . "'\n\t\t\t\t\t\tAND `type`='A'\n\t\t\t\t\t\tAND `enabled`='Y'\n\t\t\t\t"; $image_result = mysql_query($image_sql, $mysql->link); if (mysql_num_rows($image_result) > 0) { $image_record = mysql_fetch_object($image_result); $cover_art_image_ID = $image_record->ID; echo $find_art_sql; } else { $insert_image_sql = "\n\t\t\t\t\t\tINSERT INTO\n\t\t\t\t\t\t\t`" . $db->table_library_image . "`\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\t`" . $db->field_library_item_ID . "`='" . mysql_escape_string($item_ID) . "',\n\t\t\t\t\t\t\t`type`='A'\n\t\t\t\t\t"; mysql_query($insert_image_sql, $mysql->link); $cover_art_image_ID = mysql_insert_id($mysql->link); } // end if reduce($_FILES['upload_cover_art']['tmp_name'], $db->cover_thumbs_image_dir . "/" . substr($cover_art_image_ID, 0, 1) . "/" . $cover_art_image_ID . ".jpg", 200, 200); copy($_FILES['upload_cover_art']['tmp_name'], $db->cover_image_dir . "/" . substr($cover_art_image_ID, 0, 1) . "/" . $cover_art_image_ID . ".jpg"); } // end if } // end if $sorting_title = preg_replace("/^(The|A)\\s/i", "", $_POST['title']); $update_sql = "\n\t\t\t\t`title`='" . mysql_escape_string(stripslashes($_POST['title'])) . "',\n\t\t\t\t`sorting_title`='" . mysql_escape_string(stripslashes($sorting_title)) . "',\n\t\t\t\t`author_ID`='" . $_POST['author_ID'][0] . "',\n\t\t\t\t`author_type_ID`='" . $_POST['author_type'][0] . "',\n\t\t\t\t`edition`='" . mysql_escape_string(stripslashes($_POST['edition'])) . "',\n\t\t\t\t`compilation`='" . (trim(implode("", $_POST['section_title'])) != "" ? "Y" : "N") . "',\n\t\t\t\t`extra_search_text`='" . mysql_escape_string(implode(", ", $_POST['section_title']) . ", " . implode(", ", $_POST['section_author'])) . "',\n\t\t\t\t`parallel_title`='" . mysql_escape_string(stripslashes($_POST['parallel_title'])) . "',\n\t\t\t\t`" . $db->field_library_series_ID . "`='" . mysql_escape_string($_POST[$db->field_library_series_ID]) . "',\n\t\t\t\t`series_number`='" . mysql_escape_string(stripslashes($_POST['series_number'])) . "',\n\t\t\t\t`notes`='" . mysql_escape_string(stripslashes($_POST['notes'])) . "',\n\t\t\t\t`" . $db->field_library_type_ID . "`='" . mysql_escape_string($_POST[$db->field_library_type_ID]) . "',\n\t\t\t\t`" . $db->field_style_ID . "`='" . mysql_escape_string($_POST[$db->field_style_ID]) . "',\n\t\t\t\t`summary`='" . mysql_escape_string(stripslashes($_POST['summary'])) . "',\n\t\t\t\t`" . $db->field_age_ID . "`='" . mysql_escape_string($_POST[$db->field_age_ID]) . "',\n\t\t\t\t`" . $db->field_category_ID . "`='" . mysql_escape_string($_POST[$db->field_category_ID]) . "',\n\t\t\t\t`" . $db->field_publisher_ID . "`='" . mysql_escape_string($_POST[$db->field_publisher_ID]) . "',\n\t\t\t\t`length`='" . mysql_escape_string(strtoupper(stripslashes($_POST['length']))) . "',\n\t\t\t\t`height`='" . mysql_escape_string(strtoupper(stripslashes($_POST['height']))) . "',\n\t\t\t\t`call_number`='" . mysql_escape_string(strtoupper(stripslashes($_POST['call_number']))) . "',\n\t\t\t\t`isbn`='" . mysql_escape_string(stripslashes($_POST['isbn'])) . "',\n\t\t\t\t`isbn13`='" . mysql_escape_string(stripslashes($_POST['isbn13'])) . "',\n\t\t\t\t`lc_control_number`='" . mysql_escape_string(stripslashes($_POST['lc_control_number'])) . "',\n\t\t\t\t`updated_account_ID`='" . $accounts->account_record->ID . "',\n\t\t\t\t`allow_checkout`='" . mysql_escape_string(stripslashes($_POST['allow_checkout'])) . "',\n\t\t"; $unique_update_sql = "\n\t\t\t\t`" . $db->field_location_ID . "`='" . mysql_escape_string($_POST[$db->field_location_ID]) . "',\n\t\t\t\t`copy_number`='" . mysql_escape_string(stripslashes($_POST['copy_number'])) . "',\n\t\t\t\t`barcode`='" . mysql_escape_string(stripslashes($_POST['barcode'])) . "',\n\t\t"; if ($is_item_copy) { $update_duplicate_sql = "\n\t\t\t\tUPDATE\n\t\t\t\t\t`" . $db->table_library_item . "`\n\t\t\t\tSET\n\t\t\t\t\t`" . $db->field_library_copy_item_ID . "`='" . mysql_escape_string($duplicate_prefill_ID) . "'\n\t\t\t\tWHERE\n\t\t\t\t\t`ID`='" . mysql_escape_string($duplicate_prefill_ID) . "'\n\t\t\t"; //echo $update_duplicate_sql . "<br><br>"; mysql_query($update_duplicate_sql, $mysql->link); $update_sql .= "\n\t\t\t\t`" . $db->field_library_copy_item_ID . "`='" . mysql_escape_string($duplicate_prefill_ID) . "',\n\t\t\t"; } // end if
/** * Splits a string into chunks without spliting any group surrounded with some * specified characters. `$surrounders` is a string where each pair of characters * specifies the starting and ending characters of a group that should not be split. * ```php * $groups = chunks('(){}', ','); * $groups('1,2,(3,4,5),{6,(7,8)},9'); // ['1', '2', '(3,4,5)', '{6,(7,8)}', '9'] * * $names = chunks('()""', ' '); * $names('Foo "Bar Baz" (Some other name)'); // ['Foo', 'Bar Baz', 'Some other name'] * ``` * * @signature String -> String -> String -> [String] * @param string $surrounders * @param string $separator * @param sring $text * @return array */ function chunks() { $chunks = function ($surrounders, $separator, $text) { // Let's assume some values to understand how this function works // surrounders = '""{}()' // separator = ' ' // $text = 'foo ("bar baz" alpha) beta' $surrounders = map(slices(1), slices(2, $surrounders)); // [['"'. '"'], ['{'. '}'], ['(', ')']] $openings = map(get(0), $surrounders); // ['"', '{', '('] $closings = map(get(1), $surrounders); // ['"', '}', ')'] $numOfSurrounders = length($surrounders); // 3 $indexes = keys($surrounders); // [0, 1, 2] $items = split($separator, $text); // ['foo', '("bar', 'baz"', 'alpha)', 'beta'] // The initial state $state = (object) ['chunks' => [], 'counts' => array_fill(0, $numOfSurrounders, 0), 'total' => 0]; // We will iterate over $items and update the $state while adding them // For each item we need to update counts and chunks // Updates count for a single surrender (the surrender at $index) // $item : the item we are adding // $counts : the previous counts $updateCountAt = curry(function ($item, $counts, $index) use($openings, $closings) { $count = occurences(__(), $item); return $openings[$index] == $closings[$index] ? ($counts[$index] + $count($openings[$index])) % 2 : $counts[$index] + $count($openings[$index]) - $count($closings[$index]); }); // Updates counts for all surrenders $updateCounts = curry(function ($item, $counts) use($indexes, $updateCountAt) { return map($updateCountAt($item, $counts), $indexes); }); // Adds an item to the state and returns a new state $addItem = function ($state, $item) use($separator, $updateCounts) { $counts = $updateCounts($item, get('counts', $state)); $newChunks = 0 == $state->total ? append($item, $state->chunks) : append(last($state->chunks) . $separator . $item, init($state->chunks)); return (object) ['chunks' => $newChunks, 'counts' => $counts, 'total' => sum($counts)]; }; // Returns the chunks of the resulting state after adding all items return get('chunks', reduce($addItem, $state, $items)); }; return apply(curry($chunks), func_get_args()); }
public function testComplexReduce() { $this->assertSame('abcdef', reduce(function ($acc, $value, $key) { return $acc . $key . $value; }, ['a' => 'b', 'c' => 'd', 'e' => 'f'], '')); }
<?php if (version_compare(PHP_VERSION, '5.5.0') <= 0) { die('This example requires at least PHP version 5.5.0' . PHP_EOL . ' but you are only running version ' . PHP_VERSION . PHP_EOL); } include __DIR__ . '/classes/Bootstrap.php'; include __DIR__ . '/functions/reduce.php'; // Create our initial Generator to read the gpx file $gpxFilename = __DIR__ . '/data/Roman_2015-11-23.gpx'; $gpxReader = new GpxReader\GpxHandler($gpxFilename); // Set our bounding box callback $boundaries = new GpxReader\Helpers\BoundingBox(); // Reduce our trackpoint set from the gpx file against the bounding box callback $boundingBox = reduce($gpxReader->getElements('trkpt'), [$boundaries, 'calculate']); // Display the results of our reduce echo 'Bounding box co-ordinates:', PHP_EOL; printf('Top: %7.4f Bottom: %7.4f' . PHP_EOL . 'Left: %7.4f Right: %7.4f' . PHP_EOL, $boundingBox->top, $boundingBox->bottom, $boundingBox->left, $boundingBox->right);