Skip to content

Commit

Permalink
feat: Add a new take method
Browse files Browse the repository at this point in the history
  • Loading branch information
WaldoJeffers committed Dec 1, 2018
1 parent 08af214 commit 650158d
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
22 changes: 22 additions & 0 deletions __tests__/take.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const take = require('../src/take')

describe('take', () => {
it('should only keep the first N elements of the elements', () => {
expect(take(2, [1, 2, 3])).toEqual([1, 2])
})

it('should work backwards if N is negative', () => {
expect(take(-2, [1, 2, 3])).toEqual([2, 3])
})

it('should return a copy the entire array if N is greather than the array\'s length', () => {
expect(take(100, [1, 2, 3])).toEqual([1, 2, 3])
})

it('should be a pure function', () => {
const input = [1, 2, 3]
const output = take(3, input)
expect(input).toEqual([1, 2, 3])
expect(output).not.toBe(input)
})
})
41 changes: 41 additions & 0 deletions docs/api-reference/take.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# take

```erlang
take :: (Integer count, Array input) => Array output
```

{% hint style="info" %}
Available since v1.5.0
{% endhint %}

### description

`take` returns a new array only keeping the first `count` elements of the input array. If `count` is _negative_, `take` returns the last `count` elements.

[See source code](https://github.com/WaldoJeffers/conductor/blob/master/src/take.js)

### examples

#### using a positive count argument

```javascript
import { take } from 'conductor'

take(2, [1, 2, 3]) // [1, 2]
```

#### using a negative count argument

```javascript
import { take } from 'conductor'

take(-2, [1, 2, 3]) // [2, 3]
```

#### using a count argument greater than the array's length

```javascript
import { take } from 'conductor'

take(100, [1, 2, 3]) // [1, 2, 3]
```
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const replace = require('./replace')
const slice = require('./slice')
const split = require('./split')
const some = require('./some')
const take = require('./take')
const then = require('./then')
const toLowerCase = require('./toLowerCase')
const transduce = require('./transduce')
Expand Down Expand Up @@ -94,6 +95,7 @@ module.exports = {
slice,
some,
split,
take,
then,
toLowerCase,
transduce,
Expand Down
6 changes: 6 additions & 0 deletions src/take.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const curry = require('./curry')

const take = (count, array) =>
count >= 0 ? array.slice(0, count) : array.slice(count)

module.exports = curry(take)

0 comments on commit 650158d

Please sign in to comment.