UNPKG

2.07 kBPlain TextView Raw
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/**
18 * A cached reference to the hasOwnProperty function.
19 */
20const hasOwnProperty = Object.prototype.hasOwnProperty;
21
22/**
23 * A constructor function that will create blank objects.
24 */
25function Blank() {}
26
27Blank.prototype = Object.create(null);
28
29/**
30 * Used to prevent property collisions between our "map" and its prototype.
31 * @param map The map to check.
32 * @param property The property to check.
33 * @return Whether map has property.
34 */
35function has(map: object, property: string): boolean {
36 return hasOwnProperty.call(map, property);
37}
38
39/**
40 * Creates an map object without a prototype.
41 * @returns An Object that can be used as a map.
42 */
43function createMap(): any {
44 return new (Blank as any)();
45}
46
47/**
48 * Truncates an array, removing items up until length.
49 * @param arr The array to truncate.
50 * @param length The new length of the array.
51 */
52function truncateArray(arr: Array<{} | null | undefined>, length: number) {
53 while (arr.length > length) {
54 arr.pop();
55 }
56}
57
58/**
59 * Creates an array for a desired initial size. Note that the array will still
60 * be empty.
61 * @param initialAllocationSize The initial size to allocate.
62 * @returns An empty array, with an initial allocation for the desired size.
63 */
64function createArray<T>(initialAllocationSize: number): Array<T> {
65 const arr = new Array(initialAllocationSize);
66 truncateArray(arr, 0);
67 return arr;
68}
69
70export { createArray, createMap, has, truncateArray };