Skip to content

Commit 240d9db

Browse files
committed
Improve once and limit: consistent-return
1 parent e8109d1 commit 240d9db

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

JavaScript/7-once.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,17 @@
22

33
// Wrapper will prevent calls > n
44

5-
const once = (f) => (...args) => {
6-
if (!f) return;
7-
const res = f(...args);
8-
f = null;
9-
return res;
5+
const emptiness = () => {};
6+
7+
const once = (fn) => {
8+
if (!fn) return emptiness;
9+
let finished = false;
10+
const wrapped = (...args) => {
11+
if (finished) return;
12+
finished = true;
13+
fn(...args);
14+
};
15+
return wrapped;
1016
};
1117

1218
// Usage

JavaScript/8-limit.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@
22

33
// Wrapper will prevent calls > n
44

5-
const limit = (count, f) => {
5+
const emptiness = () => {};
6+
7+
const limit = (count, fn) => {
68
let counter = 0;
7-
return (...args) => {
8-
if (counter === count) return;
9+
if (!fn) return emptiness;
10+
const wrapped = (...args) => {
11+
if (counter === count) return null;
912
counter++;
10-
return f(...args);
13+
return fn(...args);
1114
};
15+
return wrapped;
1216
};
1317

1418
// Usage

0 commit comments

Comments
 (0)