Skip to content

Commit

Permalink
🚧 progress: Import existing source from js-itertools.
Browse files Browse the repository at this point in the history
  • Loading branch information
make-github-pseudonymous-again committed Apr 27, 2021
1 parent 5f1ab3a commit d1f1881
Show file tree
Hide file tree
Showing 7 changed files with 10,071 additions and 7 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
},
"dependencies": {},
"devDependencies": {
"@aureooms/js-itertools": "^5.1.1",
"@babel/core": "7.13.15",
"@babel/preset-env": "7.13.15",
"@babel/register": "7.13.14",
Expand Down
27 changes: 27 additions & 0 deletions src/cycle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Cycles through the input iterable.
*
* @example
* // returns [0,1,0,1,0,1,0]
* list(head(cycle(range(2)),7)) ;
*
* @param {Iterable} iterable - The input iterable.
* @returns {IterableIterator}
*
*/
export default function* cycle(iterable) {
const buffer = [];

for (const item of iterable) {
yield item;
buffer.push(item);
}

if (buffer.length === 0) {
return;
}

while (true) {
yield* buffer;
}
}
4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
const answer = 42;
export default answer;
export {default as cycle} from './cycle.js';
export {default as ncycle} from './ncycle.js';
28 changes: 28 additions & 0 deletions src/ncycle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Same as {@link cycle} but only cycles a limited number of times.
*
* @example
* // returns [0,1,0,1,0,1,0,1]
* list(ncycle(range(2),4)) ;
*
* @param {Iterable} iterable - The input iterable.
* @param {Number} n - The number of times to cycle through the input iterable.
* @returns {Iterator}
*
*/
export default function* ncycle(iterable, n) {
const buffer = [];

for (const item of iterable) {
yield item;
buffer.push(item);
}

if (buffer.length === 0) {
return;
}

while (--n > 0) {
yield* buffer;
}
}
5 changes: 0 additions & 5 deletions test/src/api.js

This file was deleted.

27 changes: 27 additions & 0 deletions test/src/cycle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import test from 'ava';

import {next} from '@aureooms/js-itertools';

import {cycle} from '../../src/index.js';

test('cycle (empty)', (t) => {
// The empty use case is very important
// in case of an empty input, cycle must
// stop immediately (no infinite loop)

const it = cycle([]);

t.is(it.next().done, true, 'Cycle on empty list should be empty.');
});

test('cycle', (t) => {
const a = [1, 7, 3];

const it = cycle(a);

for (let i = 0; i < 1000; ++i) {
for (const [j, element] of a.entries()) {
t.deepEqual(next(it), element, i + '.' + j);
}
}
});
Loading

0 comments on commit d1f1881

Please sign in to comment.