The lodash method once exported as a module to restrict function invocation to a single execution.
npx @tessl/cli install tessl/npm-lodash--once@4.1.00
# lodash.once
1
2
The lodash method `_.once` exported as a standalone Node.js module. Creates a function that is restricted to invoking a given function once, with subsequent calls returning the cached result from the first invocation.
3
4
## Package Information
5
6
- **Package Name**: lodash.once
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.once`
10
11
## Core Imports
12
13
```javascript
14
const once = require('lodash.once');
15
```
16
17
For ES modules:
18
19
```javascript
20
import once from 'lodash.once';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const once = require('lodash.once');
27
28
// Create a function that only runs once
29
const initialize = once(function() {
30
console.log('Application initialized');
31
return { status: 'ready' };
32
});
33
34
// First call executes the function
35
const result1 = initialize(); // Logs: "Application initialized"
36
console.log(result1); // { status: 'ready' }
37
38
// Subsequent calls return cached result
39
const result2 = initialize(); // No log output
40
console.log(result2); // { status: 'ready' } (same reference)
41
42
console.log(result1 === result2); // true
43
```
44
45
## Capabilities
46
47
### Function Restriction
48
49
Creates a function wrapper that restricts the provided function to execute only once.
50
51
```javascript { .api }
52
/**
53
* Creates a function that is restricted to invoking `func` once. Repeat calls
54
* to the function return the value of the first invocation. The `func` is
55
* invoked with the `this` binding and arguments of the created function.
56
*
57
* @param {Function} func The function to restrict.
58
* @returns {Function} Returns the new restricted function.
59
* @throws {TypeError} Throws a TypeError if `func` is not a function.
60
*/
61
function once(func);
62
```
63
64
**Usage Examples:**
65
66
```javascript
67
const once = require('lodash.once');
68
69
// Event handler that should only run once
70
const handleClick = once(function(event) {
71
console.log('Button clicked for the first time');
72
// Expensive operation here
73
return performExpensiveOperation();
74
});
75
76
button.addEventListener('click', handleClick);
77
78
// Initialization function
79
const createConnection = once(function() {
80
console.log('Creating database connection...');
81
return new DatabaseConnection();
82
});
83
84
// Multiple calls return the same connection instance
85
const conn1 = createConnection();
86
const conn2 = createConnection();
87
console.log(conn1 === conn2); // true
88
89
// Function with parameters - first call's arguments are used
90
const greet = once(function(name) {
91
return `Hello, ${name}!`;
92
});
93
94
console.log(greet('Alice')); // "Hello, Alice!"
95
console.log(greet('Bob')); // "Hello, Alice!" (cached result)
96
97
// Preserves `this` context
98
const obj = {
99
value: 42,
100
getValue: once(function() {
101
return this.value;
102
})
103
};
104
105
console.log(obj.getValue()); // 42
106
console.log(obj.getValue()); // 42 (cached)
107
```
108
109
**Error Handling:**
110
111
```javascript
112
const once = require('lodash.once');
113
114
try {
115
const invalid = once('not a function');
116
} catch (error) {
117
console.log(error instanceof TypeError); // true
118
console.log(error.message); // "Expected a function"
119
}
120
```
121
122
**Return Value Behavior:**
123
124
- If the original function returns `undefined`, subsequent calls will also return `undefined`
125
- If the original function throws an error, that error is thrown on the first call, and subsequent calls return `undefined` (since no result was stored)
126
- The returned function maintains the same `this` binding as the first invocation
127
- After the first invocation, the original function reference is cleared for memory efficiency
128
129
```javascript
130
const once = require('lodash.once');
131
132
// Function that throws an error
133
const errorFunction = once(function() {
134
throw new Error('Something went wrong');
135
});
136
137
try {
138
errorFunction(); // Throws error
139
} catch (e) {
140
console.log(e.message); // "Something went wrong"
141
}
142
143
const result = errorFunction(); // Returns undefined (no error thrown)
144
console.log(result); // undefined
145
146
// Function that returns a value before throwing would still cache the value
147
const mixedFunction = once(function(shouldThrow) {
148
if (shouldThrow) {
149
throw new Error('Error on first call');
150
}
151
return 'success';
152
});
153
154
console.log(mixedFunction(false)); // 'success'
155
console.log(mixedFunction(true)); // 'success' (cached, ignores new argument)
156
```