Skip to content

Commit 9c801dc

Browse files
committed
feat(overmind): add throttle operator
1 parent b29bebf commit 9c801dc

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

packages/node_modules/overmind/src/index.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,3 +1443,29 @@ export function debounce<Input, ThisConfig extends IConfiguration = Config>(
14431443
}
14441444
)
14451445
}
1446+
1447+
export function throttle<Input, ThisConfig extends IConfiguration = Config>(
1448+
ms: number
1449+
): IOperator<ThisConfig, Input, Input> {
1450+
let timeout
1451+
let previousFinal
1452+
1453+
return createOperator(
1454+
'throttle',
1455+
String(ms),
1456+
(err, context, value, next, final) => {
1457+
if (err) next(err, value)
1458+
else {
1459+
if (timeout) {
1460+
previousFinal(null, value)
1461+
} else {
1462+
timeout = setTimeout(() => {
1463+
timeout = null
1464+
next(null, value)
1465+
}, ms)
1466+
}
1467+
previousFinal = final
1468+
}
1469+
}
1470+
)
1471+
}

packages/node_modules/overmind/src/operators.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
IAction,
1616
catchError,
1717
tryCatch,
18+
throttle,
1819
} from './'
1920

2021
describe('OPERATORS', () => {
@@ -316,6 +317,35 @@ describe('OPERATORS', () => {
316317
}
317318
)
318319
})
320+
test('throttle', () => {
321+
expect.assertions(1)
322+
const test: Operator = pipe(
323+
throttle(100),
324+
mutate(({ state }) => state.runCount++)
325+
)
326+
const state = {
327+
runCount: 0,
328+
}
329+
const config = {
330+
state,
331+
actions: {
332+
test,
333+
},
334+
}
335+
const overmind = new Overmind(config)
336+
337+
type Config = IConfig<typeof config>
338+
339+
interface Operator<Input = void, Output = Input>
340+
extends IOperator<Config, Input, Output> {}
341+
342+
return Promise.all([overmind.actions.test(), overmind.actions.test()]).then(
343+
() => {
344+
expect(overmind.state.runCount).toBe(1)
345+
}
346+
)
347+
})
348+
319349
test('catchError', () => {
320350
expect.assertions(3)
321351
const test: Operator<string> = pipe(

0 commit comments

Comments
 (0)