Skip to content

Commit

Permalink
Add Cycled#peek() method (#12)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
Richienb and sindresorhus authored Jul 16, 2020
1 parent ca82649 commit e83061f
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ declare class Cycled<T> extends Array<T> {
*/
step(steps: number): T;

/**
Returns the item that is located in the given amount of `steps` through the array. For example, calling `peek(2)` would get the item 2 items after the current one. You go backward by specifying a negative number.
This method is similar to `.step()` but without changing the current item.
*/
peek(steps: number): T;

/**
Returns an iterable that will cycle through the array indefinitely.
*/
Expand Down
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ module.exports = class Cycled extends Array {
return this[this._index];
}

peek(steps) {
return this[(this.length + this._index + steps) % this.length];
}

current() {
return this.step(0);
}
Expand Down
1 change: 1 addition & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ expectType<number>(cycled.current());
expectType<number>(cycled.next());
expectType<number>(cycled.previous());
expectType<number>(cycled.step(10));
expectType<number>(cycled.peek(10));
expectType<IterableIterator<number>>(cycled.indefinitely());
expectType<IterableIterator<number>>(cycled.indefinitelyReversed());
expectType<number[]>([...cycled]);
Expand Down
6 changes: 6 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ Returns the previous item.

Returns the item by going the given amount of `steps` through the array. For example, calling `step(2)` is like calling `next()` twice. You go backward by specifying a negative number.

#### peek(steps)

Returns the item that is located in the given amount of `steps` through the array. For example, calling `peek(2)` would get the item 2 items after the current one. You go backward by specifying a negative number.

This method is similar to `.step()` but without changing the current item.

#### index

Get or set the current index.
Expand Down
6 changes: 6 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ test('.step()', t => {
t.is(c.step(-2), 1);
});

test('.peek()', t => {
const c = new Cycled(fixture);
t.is(c.peek(1), 2);
t.is(c.peek(-2), 2);
});

test('.index', t => {
const c = new Cycled(fixture);
t.is(c.index, 0);
Expand Down

0 comments on commit e83061f

Please sign in to comment.