Skip to content
This repository has been archived by the owner on May 15, 2021. It is now read-only.

Commit

Permalink
✨ Enumerable: added last, clear, inspect, findAll, reject, equal
Browse files Browse the repository at this point in the history
  • Loading branch information
codemasher committed Jan 13, 2018
1 parent 8ea5bba commit 8262c7e
Showing 1 changed file with 102 additions and 1 deletion.
103 changes: 102 additions & 1 deletion src/Enumerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

namespace chillerlan\Traits;

use Closure;

/**
* @link http://api.prototypejs.org/language/Enumerable/
*/
Expand Down Expand Up @@ -81,10 +83,109 @@ public function __map($callback):array {
* @return $this
*/
public function __reverse(){
$this->array = array_reverse($this->array);
$this->array = array_reverse($this->array);
$this->offset = 0;

return $this;
}

/**
* @return mixed
*/
public function __last(){
return $this->array[count($this->array) - 1];
}

/**
* @return $this
*/
public function __clear(){
$this->array = [];

return $this;
}

/**
* @link http://api.prototypejs.org/language/Array/prototype/inspect/
*
* @return string
*/
public function __inspect():string {
return print_r($this->array, true);
}

/**
* @link http://api.prototypejs.org/language/Enumerable/prototype/findAll/
*
* @param \Closure $callback
*
* @return array
* @throws \chillerlan\Traits\TraitException
*/
public function __findAll(Closure $callback):array{

if(!is_callable($callback)){
throw new TraitException('invalid callback');
}

$return = [];

foreach($this->array as $index => $element){

if(call_user_func_array($callback, [$element, $index]) === true){
$return[] = $element;
}

}

return $return;
}

/**
* @link http://api.prototypejs.org/language/Enumerable/prototype/reject/
*
* @param \Closure $callback
*
* @return array
* @throws \chillerlan\Traits\TraitException
*/
public function __reject(Closure $callback):array{

if(!is_callable($callback)){
throw new TraitException('invalid callback');
}

$return = [];

foreach($this->array as $index => $element){

if(call_user_func_array($callback, [$element, $index]) !== true){
$return[] = $element;
}

}

return $return;
}

/**
* @param array $y
*
* @return bool
*/
public function __equal(array $y):bool{

if(count($this->array) !== count($y)){
return false;
}

$diff = 0;

foreach($this->array as $kx => $vx){
$diff |= $vx ^ $y[$kx];
}

return ((($diff - 1) >> 31) & 1) === 1;
}

}

0 comments on commit 8262c7e

Please sign in to comment.