Skip to content

Commit 1f37846

Browse files
committed
Improved avg(), min(), max() and sum() implementation
1 parent b020a29 commit 1f37846

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

src/Map.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -659,15 +659,14 @@ public function avg( $col = null ) : float
659659
if( $col instanceof \Closure ) {
660660
$vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
661661
} elseif( is_string( $col ) ) {
662-
$vals = $this->col( $col )->toArray();
662+
$vals = array_map( $this->mapper( $col ), $this->list() );
663663
} elseif( is_null( $col ) ) {
664664
$vals = $this->list();
665665
} else {
666666
throw new \InvalidArgumentException( 'Parameter is no closure or string' );
667667
}
668668

669-
$cnt = count( $vals );
670-
return $cnt > 0 ? array_sum( $vals ) / $cnt : 0;
669+
return !empty( $vals ) ? array_sum( $vals ) / count( $vals ) : 0;
671670
}
672671

673672

@@ -3147,7 +3146,7 @@ public function max( $col = null )
31473146
if( $col instanceof \Closure ) {
31483147
$vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
31493148
} elseif( is_string( $col ) ) {
3150-
$vals = $this->col( $col )->toArray();
3149+
$vals = array_map( $this->mapper( $col ), $this->list() );
31513150
} elseif( is_null( $col ) ) {
31523151
$vals = $this->list();
31533152
} else {
@@ -3227,7 +3226,7 @@ public function min( $col = null )
32273226
if( $col instanceof \Closure ) {
32283227
$vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
32293228
} elseif( is_string( $col ) ) {
3230-
$vals = $this->col( $col )->toArray();
3229+
$vals = array_map( $this->mapper( $col ), $this->list() );
32313230
} elseif( is_null( $col ) ) {
32323231
$vals = $this->list();
32333232
} else {
@@ -5124,7 +5123,7 @@ public function sum( $col = null ) : float
51245123
if( $col instanceof \Closure ) {
51255124
$vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
51265125
} elseif( is_string( $col ) ) {
5127-
$vals = $this->col( $col )->toArray();
5126+
$vals = array_map( $this->mapper( $col ), $this->list() );
51285127
} elseif( is_null( $col ) ) {
51295128
$vals = $this->list();
51305129
} else {

0 commit comments

Comments
 (0)