Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
50 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
} | ||
} |