Skip to content

Commit

Permalink
Enable all Set-like iterator methods
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey committed Sep 11, 2018
1 parent e2eb0cb commit 4f5fe10
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 11 deletions.
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,21 @@ npm install @blakeembrey/deque --save
* `delete(i)` Delete the value at position `i`.
* `reverse()` Reverse the elements of the deque in-place.
* `rotate(n=1)` Rotate the deque `n` steps to the right.
* `entries()` Return an iterable of deque.
* `@@iterator()` Return an iterable of deque.

```js
import { Deque } from '@blakeembrey/deque'

const d = new Deque('ghi')

for (const elem of d) {
console.log(elem.toUpperCase()) //=> G H I
for (const value of d) {
console.log(value.toUpperCase()) //=> G H I
}

d.push('j')
d.pushleft('f')
d //=> deque(['f', 'g', 'h', 'i', 'j'])
d //=> Deque(['f', 'g', 'h', 'i', 'j'])

d.pop() //=> 'j'
d.popleft() //=> 'f'
Expand All @@ -53,13 +55,17 @@ d.peek(0) //=> 'g'
d.peek(-1) //=> 'i'

d.extend('jkl')
d //=> deque(['g', 'h', 'i', 'j', 'k', 'l'])
d //=> Deque(['g', 'h', 'i', 'j', 'k', 'l'])

d.rotate(1)
d //=> deque(['l', 'g', 'h', 'i', 'j', 'k'])
d //=> Deque(['l', 'g', 'h', 'i', 'j', 'k'])

d.rotate(-1)
d //=> deque(['g', 'h', 'i', 'j', 'k', 'l'])
d //=> Deque(['g', 'h', 'i', 'j', 'k', 'l'])

const d2 = new Deque(d)

d2 //=> Deque(['g', 'h', 'i', 'j', 'k', 'l'])
```

## TypeScript
Expand Down
7 changes: 4 additions & 3 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ describe('values', () => {
expect(values).toEqual(Array.from('abc'))
})

it('should support values method', () => {
it('should support `Set`-like iterable methods', () => {
const d = new Deque('abc')
const values = Array.from(d.values())

expect(values).toEqual(Array.from('abc'))
expect(Array.from(d.entries())).toEqual(Array.from('abc'))
expect(Array.from(d.keys())).toEqual(Array.from('abc'))
expect(Array.from(d.values())).toEqual(Array.from('abc'))
})
})

Expand Down
12 changes: 10 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,13 +204,21 @@ export class Deque<T> {
return this
}

*values() {
*entries(): IterableIterator<T> {
const { head, size, list, mask } = this

for (let i = 0; i < size; i++) yield list[(head + i) & mask]
}

keys() {
return this.entries()
}

values() {
return this.entries()
}

[Symbol.iterator]() {
return this.values()
return this.entries()
}
}

0 comments on commit 4f5fe10

Please sign in to comment.