1 | /**
|
2 | * Copyright 2018 The Incremental DOM Authors. All Rights Reserved.
|
3 | *
|
4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | * you may not use this file except in compliance with the License.
|
6 | * You may obtain a copy of the License at
|
7 | *
|
8 | * http://www.apache.org/licenses/LICENSE-2.0
|
9 | *
|
10 | * Unless required by applicable law or agreed to in writing, software
|
11 | * distributed under the License is distributed on an "AS-IS" BASIS,
|
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 | * See the License for the specific language governing permissions and
|
14 | * limitations under the License.
|
15 | */
|
16 |
|
17 | import { truncateArray } from "./util";
|
18 |
|
19 | const buffer: Array<any> = [];
|
20 |
|
21 | let bufferStart = 0;
|
22 |
|
23 | /**
|
24 | * TODO(tomnguyen): This is a bit silly and really needs to be better typed.
|
25 | * @param fn A function to call.
|
26 | * @param a The first argument to the function.
|
27 | * @param b The second argument to the function.
|
28 | * @param c The third argument to the function.
|
29 | */
|
30 | function queueChange<A, B, C>(
|
31 | fn: (a: A, b: B, c: C) => void,
|
32 | a: A,
|
33 | b: B,
|
34 | c: C
|
35 | ) {
|
36 | buffer.push(fn);
|
37 | buffer.push(a);
|
38 | buffer.push(b);
|
39 | buffer.push(c);
|
40 | }
|
41 |
|
42 | /**
|
43 | * Flushes the changes buffer, calling the functions for each change.
|
44 | */
|
45 | function flush() {
|
46 | // A change may cause this function to be called re-entrantly. Keep track of
|
47 | // the portion of the buffer we are consuming. Updates the start pointer so
|
48 | // that the next call knows where to start from.
|
49 | const start = bufferStart;
|
50 | const end = buffer.length;
|
51 |
|
52 | bufferStart = end;
|
53 |
|
54 | for (let i = start; i < end; i += 4) {
|
55 | const fn = buffer[i] as (a: any, b: any, c: any) => undefined;
|
56 | fn(buffer[i + 1], buffer[i + 2], buffer[i + 3]);
|
57 | }
|
58 |
|
59 | bufferStart = start;
|
60 | truncateArray(buffer, start);
|
61 | }
|
62 |
|
63 | export { queueChange, flush };
|