Exemplo n.º 1
0
 /**
  * For the current comparator object checks
  * if a given condition is convenient
  * Ex:
  * (new Comparator(10, 20))->expect('!='); returns true because 10 and 20 are different.
  * 
  * @param  Comparation Operator $expect
  * @return boolean
  */
 public function expect($expect)
 {
     $cmp = Comparator::compare($this->itemA, $this->itemB);
     switch ($expect) {
         case '=':
             return $cmp === 0;
             break;
         case '!=':
             return $cmp != 0;
             break;
         case '>=':
             return $cmp >= 0;
             break;
         case '<=':
             return $cmp <= 0;
             break;
         case '>':
             return $cmp > 0;
             break;
         case '<':
             return $cmp < 0;
             break;
         default:
             throw new Exception('Invalid comparator operation.');
     }
     return 0;
 }
Exemplo n.º 2
0
 /**
  * Sort a collection by user preference
  * @param  string/callable $sortBy
  * @param  [string] $sorting
  * @return Collection
  */
 public function sort($sortBy = null, $sorting = 'ascending')
 {
     $tmp = $this->data;
     if (!is_callable($sortBy)) {
         $callback = function ($a, $b) use($sortBy) {
             if (is_array($a) && is_array($b)) {
                 $a = ArrayHelper::path($a, $sortBy);
                 $b = ArrayHelper::path($b, $sortBy);
             }
             return Comparator::compare($a, $b);
         };
     } else {
         $callback = $sortBy;
     }
     uasort($tmp, $callback);
     $newCollection = new Collection($tmp);
     if ($sorting == 'descending') {
         return $newCollection->reverse();
     }
     return $newCollection;
 }
 public static function mergeSortedLists($list1, $list2, Comparator $comparator, $compareValueGetter = null, $limit = null)
 {
     $list1Size = count($list1);
     $list2Size = count($list2);
     $i = $j = $k = 0;
     $newList = array();
     while ($i < $list1Size && $j < $list2Size) {
         if ($limit && $k == $limit) {
             return $newList;
         }
         if (!$compareValueGetter) {
             $compareResult = $comparator->compare($list1[$i], $list2[$j]);
         } else {
             $compareResult = $comparator->compare($list1[$i]->{$compareValueGetter}(), $list2[$j]->{$compareValueGetter}());
         }
         // list1 elt < list2 elt
         if ($compareResult < 0) {
             $newList[$k++] = $list2[$j++];
         } else {
             $newList[$k++] = $list1[$i++];
         }
     }
     while ($i < $list1Size) {
         if ($limit && $k == $limit) {
             return $newList;
         }
         $newList[$k++] = $list1[$i++];
     }
     while ($j < $list2Size) {
         if ($limit && $k == $limit) {
             return $newList;
         }
         $newList[$k++] = $list2[$j++];
     }
     return $newList;
 }