Skip to content

Commit

Permalink
feat: add repeat() (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
unional committed Jun 10, 2019
1 parent 763c7fe commit 8419d51
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions README.md
Expand Up @@ -29,6 +29,11 @@ assertron.throws(() => Promise.reject(new Error('foo')))
assertron.pathEqual('dir/sub-dir/file.txt', 'dir\\sub-dir\\file.txt')
```

### assertron.repeat(fn, times)

Repeat the specified function n times and return the last result.
If the result is a promise, it will run the function sequentially.

### assertron.satisfies(actual, expected)

`assertron.satisfies()` checks if `actual` meets the requirements specified by `expected`.
Expand Down
3 changes: 2 additions & 1 deletion src/assertron/assertron.ts
Expand Up @@ -2,12 +2,12 @@ import AssertionError from 'assertion-error';
import { falsy } from './falsy';
import { pathEqual } from './pathEqual';
import { rejects } from './rejects';
import { repeat } from './repeat';
import { resolves } from './resolves';
import { satisfies } from './satisfies';
import { throws } from './throws';
import { truthy } from './truthy';


export const assertron = {
false(value: any) {
if (value !== false)
Expand All @@ -19,6 +19,7 @@ export const assertron = {
falsy,
pathEqual,
rejects,
repeat,
resolves,
satisfies,
throws,
Expand Down
23 changes: 23 additions & 0 deletions src/assertron/repeat.spec.ts
@@ -0,0 +1,23 @@
import a from '..'

test('repeat function n times', () => {
let count = 0
a.repeat(() => ++count, 10)

expect(count).toBe(10)
})

test('repeat async function n times sequentially', async () => {
let count = 0
let actual = ''
let aa = await a.repeat(() => new Promise<string>(a => {
setTimeout(() => {
++count
actual += String(count)
a(actual)
}, Math.random() * 10)
}), 10)

expect(actual).toBe('12345678910')
expect(actual).toBe(aa)
})
20 changes: 20 additions & 0 deletions src/assertron/repeat.ts
@@ -0,0 +1,20 @@
import isPromise from 'is-promise';

/**
* Repeat the specified function n times and return the last result.
* If the result is a promise, it will run the function sequentially.
*/
export function repeat<R>(fn: () => R | (() => Promise<R>), times: number): ReturnType<typeof fn> extends Promise<R> ? Promise<R> : R {
const result = fn()
if (isPromise(result)) {
if (times <= 1) return result as any
return result.then(() => repeat(fn, times - 1)) as any
}
else {
let result
for (let i = 1; i < times; i++) {
result = fn()
}
return result
}
}

0 comments on commit 8419d51

Please sign in to comment.