This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 975
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
3 changed files
with
85 additions
and
44 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* This Source Code Form is subject to the terms of the Mozilla Public | ||
* License, v. 2.0. If a copy of the MPL was not distributed with this file, | ||
* You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
||
/** | ||
* Perform a sequence of function calls, grouping together contiguous function | ||
* calls for the same function different args. | ||
* See syncUtil.applySyncRecords() for a usage example. | ||
*/ | ||
module.exports = class FunctionBuffer { | ||
/** | ||
* @param {function=} prepareArguments Before calling a function, run this function to prepare the buffered arguments. | ||
*/ | ||
constructor (prepareArguments) { | ||
this.argumentsBuffer = [] | ||
this.previousFunction = () => {} | ||
this.prepareArguments = prepareArguments || ((args) => args) | ||
} | ||
|
||
/** | ||
* @param {function} fn Function to call. NOTE: this supports only calling with the first argument. | ||
* @param {any} arg Arg to buffer | ||
*/ | ||
buffer (fn, arg) { | ||
if (fn !== this.previousFunction) { | ||
this.flush() | ||
this.previousFunction = fn | ||
} | ||
this.argumentsBuffer.push(arg) | ||
} | ||
|
||
/** | ||
* Call previousFunction with buffered arguments and empty buffer. | ||
*/ | ||
flush () { | ||
if (!this.argumentsBuffer.length) { return } | ||
const preparedArgs = this.prepareArguments(this.argumentsBuffer) | ||
const returnValue = this.previousFunction(preparedArgs) | ||
this.argumentsBuffer = [] | ||
return returnValue | ||
} | ||
} |
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