Skip to content

Commit

Permalink
Implemented take() method
Browse files Browse the repository at this point in the history
  • Loading branch information
aimeos committed Aug 25, 2020
1 parent 89e2ea1 commit 56af78e
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ will return:
* [sort()](#sort) : Sorts elements
* [split()](#split) : Splits a string into map elements
* [splice()](#splice) : Replaces a slice by new elements
* [take()](#take) : Returns a new map with the given number of items
* [toArray()](#toarray) : Returns the plain array
* [toJson()](#tojson) : Returns the elements in JSON format
* [toUrl()](#tourl) : Creates a HTTP query string
Expand Down Expand Up @@ -2446,6 +2447,35 @@ Map::split( 'string', '' );
```


### take()

Returns a new map with the given number of items.

```php
public function take( int $size, int $offset = 0 ) : self
```

* @param int `$size` Number of items to return
* @param int `$offset` Number of items to skip
* @return self New map

**Examples:**

```php
Map::from( [1, 2, 3, 4] )->take( 2 );
Map::from( [1, 2, 3, 4] )->take( 2, 1 );
Map::from( [1, 2, 3, 4] )->take( 2, -2 );
```

**Results:**

```php
[1, 2]
[2, 3]
[3, 4]
```


### toArray()

Returns the elements as a plain array.
Expand Down
23 changes: 23 additions & 0 deletions src/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -2137,6 +2137,29 @@ public function splice( int $offset, int $length = null, $replacement = [] ) : s
}


/**
* Returns a new map with the given number of items.
*
* Examples:
* Map::from( [1, 2, 3, 4] )->take( 2 );
* Map::from( [1, 2, 3, 4] )->take( 2, 1 );
* Map::from( [1, 2, 3, 4] )->take( 2, -2 );
*
* Results:
* [1, 2]
* [2, 3]
* [3, 4]
*
* @param int $size Number of items to return
* @param int $offset Number of items to skip
* @return self New map
*/
public function take( int $size, int $offset = 0 ) : self
{
return new static( array_slice( $this->list, $offset, $size, true ) );
}


/**
* Returns the elements as a plain array.
*
Expand Down
18 changes: 18 additions & 0 deletions tests/MapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1717,6 +1717,24 @@ public function testSplitString()
}


public function testTake()
{
$this->assertEquals( [1, 2], Map::from( [1, 2, 3, 4] )->take( 2 )->toArray() );
}


public function testTakeOffset()
{
$this->assertEquals( [1 => 2, 2 => 3], Map::from( [1, 2, 3, 4] )->take( 2, 1 )->toArray() );
}


public function testTakeNegativeOffset()
{
$this->assertEquals( [2 => 3, 3 => 4], Map::from( [1, 2, 3, 4] )->take( 2, -2 )->toArray() );
}


public function testToArray()
{
$m = new Map( ['name' => 'Hello'] );
Expand Down

0 comments on commit 56af78e

Please sign in to comment.