Skip to content

Commit 34a2e62

Browse files
Merge pull request #272 from umsungjun/once-add-bechmark
feat: add benchmark and JSDoc for once function
2 parents 74bcb6d + f12a761 commit 34a2e62

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/once.bench.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import _once from 'lodash/once'
2+
import {bench, describe} from 'vitest'
3+
4+
import once from './once'
5+
6+
const testCase = () => 'result'
7+
8+
const ITERATIONS = 1000
9+
10+
describe('once performance', () => {
11+
bench('hidash', () => {
12+
const hidashOnce = once(testCase)
13+
for (let i = 0; i < ITERATIONS; i++) {
14+
hidashOnce()
15+
}
16+
})
17+
bench('lodash', () => {
18+
const lodashOnce = _once(testCase)
19+
for (let i = 0; i < ITERATIONS; i++) {
20+
lodashOnce()
21+
}
22+
})
23+
})

src/once.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,23 @@
11
import {before} from './before'
22

3+
/**
4+
* Creates a function that is invoked only once.
5+
* Subsequent calls to the new function return the result of the first invocation.
6+
* Internally uses `before(2, func)` to allow the original function to be called only once.
7+
*
8+
* @template T - The type of the function to restrict.
9+
* @param {T} func - The function to invoke once.
10+
* @returns {(...args: Parameters<T>) => ReturnType<T>} A new function that calls `func` at most once.
11+
*
12+
* @example
13+
* const initialize = once(() => {
14+
* console.log('Initialized!');
15+
* return 'result';
16+
* });
17+
*
18+
* initialize(); // Logs: 'Initialized!' and returns 'result'
19+
* initialize(); // Returns 'result' without logging
20+
*/
321
export function once<T extends (...args: Parameters<T>) => ReturnType<T>>(
422
func: T,
523
): (...args: Parameters<T>) => ReturnType<T> {

0 commit comments

Comments
 (0)