@paulirish/trace_engine 0.0.15 → 0.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +27 -0
- package/PAUL.readme.md +5 -0
- package/README.md +166 -0
- package/analyze-trace.mjs +184 -0
- package/core/platform/array-utilities.d.ts +66 -0
- package/core/platform/array-utilities.js +199 -0
- package/core/platform/array-utilities.js.map +1 -0
- package/core/platform/date-utilities.d.ts +2 -0
- package/core/platform/date-utilities.js +14 -0
- package/core/platform/date-utilities.js.map +1 -0
- package/core/platform/dcheck-tsconfig.json +8 -0
- package/core/platform/dcheck.d.ts +4 -0
- package/core/platform/dcheck.js +5 -0
- package/core/platform/dom-utilities.d.ts +8 -0
- package/core/platform/dom-utilities.js +109 -0
- package/core/platform/dom-utilities.js.map +1 -0
- package/core/platform/keyboard-utilities.d.ts +17 -0
- package/core/platform/keyboard-utilities.js +22 -0
- package/core/platform/keyboard-utilities.js.map +1 -0
- package/core/platform/map-utilities.d.ts +18 -0
- package/core/platform/map-utilities.js +76 -0
- package/core/platform/map-utilities.js.map +1 -0
- package/core/platform/number-utilities.d.ts +15 -0
- package/core/platform/number-utilities.js +82 -0
- package/core/platform/number-utilities.js.map +1 -0
- package/core/platform/promise-utilities.d.ts +10 -0
- package/core/platform/promise-utilities.js +18 -0
- package/core/platform/promise-utilities.js.map +1 -0
- package/core/platform/set-utilities.d.ts +2 -0
- package/core/platform/set-utilities.js +23 -0
- package/core/platform/set-utilities.js.map +1 -0
- package/core/platform/string-utilities.d.ts +71 -0
- package/core/platform/string-utilities.js +513 -0
- package/core/platform/string-utilities.js.map +1 -0
- package/core/platform/typescript-utilities.d.ts +56 -0
- package/core/platform/typescript-utilities.js +25 -0
- package/core/platform/typescript-utilities.js.map +1 -0
- package/models/trace/EntriesFilter.d.ts +6 -0
- package/models/trace/EntriesFilter.js +17 -0
- package/models/trace/EntriesFilter.js.map +1 -1
- package/package.json +7 -6
- package/test/invalid-animation-events.json.gz +0 -0
- package/test/test-trace-engine.mjs +52 -0
- /package/core/platform/{Brand.d.ts → brand.d.ts} +0 -0
- /package/core/platform/{Brand.js → brand.js} +0 -0
- /package/core/platform/{Brand.js.map → brand.js.map} +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Copyright 2014 The Chromium Authors. All rights reserved.
|
|
2
|
+
//
|
|
3
|
+
// Redistribution and use in source and binary forms, with or without
|
|
4
|
+
// modification, are permitted provided that the following conditions are
|
|
5
|
+
// met:
|
|
6
|
+
//
|
|
7
|
+
// * Redistributions of source code must retain the above copyright
|
|
8
|
+
// notice, this list of conditions and the following disclaimer.
|
|
9
|
+
// * Redistributions in binary form must reproduce the above
|
|
10
|
+
// copyright notice, this list of conditions and the following disclaimer
|
|
11
|
+
// in the documentation and/or other materials provided with the
|
|
12
|
+
// distribution.
|
|
13
|
+
// * Neither the name of Google Inc. nor the names of its
|
|
14
|
+
// contributors may be used to endorse or promote products derived from
|
|
15
|
+
// this software without specific prior written permission.
|
|
16
|
+
//
|
|
17
|
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
18
|
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
19
|
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
20
|
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
21
|
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
22
|
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
23
|
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
24
|
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
25
|
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
26
|
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/PAUL.readme.md
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Trace Model (NOT FOR PUBLIC CONSUMPTION)
|
|
2
|
+
|
|
3
|
+
This package contains the trace engine implementation used by the DevTools Performance Panel.
|
|
4
|
+
|
|
5
|
+
⚠️ The API is not stable and it's fairly likely that upgrades will break you (at some point).
|
|
6
|
+
But the breakages should be obvious exceptions or type failures.
|
|
7
|
+
|
|
8
|
+
## API quickstart
|
|
9
|
+
|
|
10
|
+
```js
|
|
11
|
+
import * as TraceModel from '@paulirish/trace_engine';
|
|
12
|
+
|
|
13
|
+
polyfillDOMRect();
|
|
14
|
+
const engine = TraceModel.Processor.TraceProcessor.createWithAllHandlers();
|
|
15
|
+
|
|
16
|
+
await engine.parse(traceEvents);
|
|
17
|
+
console.log(engine.data) // TraceParseData
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Note:** To run in Node, you'll need to polyfill `window.DOMRect`. 😜
|
|
21
|
+
|
|
22
|
+
See the included `analyze-trace.mjs` a runnable invocation.
|
|
23
|
+
|
|
24
|
+
### Types
|
|
25
|
+
|
|
26
|
+
You'll probably use something like…
|
|
27
|
+
|
|
28
|
+
@type {import('@paulirish/trace_engine').Types.TraceEvents.TraceEventData[]
|
|
29
|
+
@type {import('@paulirish/trace_engine').Handlers.Types.TraceParseData
|
|
30
|
+
|
|
31
|
+
## Maintainer cheatsheet
|
|
32
|
+
|
|
33
|
+
See also http://go/btlax
|
|
34
|
+
|
|
35
|
+
#### Build, run, extract
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
# Build devtools and prep a package
|
|
39
|
+
scripts/trace/build-trace-engine-lib.sh
|
|
40
|
+
|
|
41
|
+
# run
|
|
42
|
+
node scripts/trace/analyze-trace.mjs test/unittests/fixtures/traces/web-dev.json.gz
|
|
43
|
+
|
|
44
|
+
# test
|
|
45
|
+
node scripts/trace/test/test-trace-engine.mjs
|
|
46
|
+
|
|
47
|
+
# copy built files to $HOME/code/trace_engine
|
|
48
|
+
scripts/trace/copy-build-trace-engine-for-publish.sh
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
#### Test and publish
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
# switch to standalone
|
|
55
|
+
cd $HOME/code/trace_engine
|
|
56
|
+
|
|
57
|
+
# test
|
|
58
|
+
node test/test-trace-engine.mjs
|
|
59
|
+
|
|
60
|
+
# bump and publish
|
|
61
|
+
npm version v0.0.XXX # Manually determine next version
|
|
62
|
+
npm publish --access public --dry-run
|
|
63
|
+
npm publish --access public
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## High level architecture
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
┌──────────────┐
|
|
70
|
+
│ Model#parse ├───┐
|
|
71
|
+
└──────────────┘ │
|
|
72
|
+
│
|
|
73
|
+
┌──────────▼──────────┐
|
|
74
|
+
│async processor#parse│
|
|
75
|
+
└──────────┬──────────┘
|
|
76
|
+
│
|
|
77
|
+
┌──────────▼────────────┐
|
|
78
|
+
│for handler of handlers│
|
|
79
|
+
└───┬────────────────┬──┘
|
|
80
|
+
│ │
|
|
81
|
+
┌────────────────▼────┐ ┌─────▼────────────────┐
|
|
82
|
+
│NetworkRequestHandler│ │...many more handlers │
|
|
83
|
+
│ │ │ │
|
|
84
|
+
│ reset() │ │ │
|
|
85
|
+
│ initialize() │ │ │
|
|
86
|
+
│ │ │ │
|
|
87
|
+
│ handleEvent() │ │ │
|
|
88
|
+
│ │ │ │
|
|
89
|
+
│ finalize() │ │ │
|
|
90
|
+
│ │ │ │
|
|
91
|
+
│ data() │ │ │ │
|
|
92
|
+
└─────────────────────┘ │ └──────────────────────┘
|
|
93
|
+
│
|
|
94
|
+
│
|
|
95
|
+
┌──────────────────▼─────────────────┐
|
|
96
|
+
│const data = model.traceParsedData()│
|
|
97
|
+
└────────────────────────────────────┘
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`Model#parse` is the entrypoint into the engine and is the public interface that consumers use to initiate tracing and to fetch data back.
|
|
101
|
+
|
|
102
|
+
All the processing is done by the `Processor`. The processor contains a series of *Handlers*, each of which is responsible for parsing events of a particular category.
|
|
103
|
+
|
|
104
|
+
The trace processor loops over every event in the trace and calls each handler in turn (done this way so we only loop over the trace file once, rather than doing it once-per-handler). A Handler is a file that exposes a set of methods, most importantly `handleEvent()` and `data()`. The `handleEvent` function will be called for each event in the trace, and it is up to an individual handler to do something with that event if it needs to. The `data` method should return the final data that has been parsed and generated by the handler.
|
|
105
|
+
|
|
106
|
+
Once processing is done (read on for more details on how to track this), you can use the `traceParsedData()` method to fetch the result of parsing a given trace.
|
|
107
|
+
|
|
108
|
+
## Enabled handlers and creating a model
|
|
109
|
+
|
|
110
|
+
At the time of writing (06 June 2023) we are midway through a migration of the Performanc Panel's trace engine from the SDK.TracingModel to the new TraceEngine. Consequently, not all of the TraceEngine's handlers are currently active, because we don't want to run expensive handlers whose data we do not yet use in the UI.
|
|
111
|
+
|
|
112
|
+
Therefore, to create a model instance, we use `Model.createWithRequiredHandlersForMigration()`, which initializes a model configured correctly with the right handlers.
|
|
113
|
+
|
|
114
|
+
Once the migration is done, we can swap to `Model.createWithAllHandlers()` and remove the code that enables a subset of the handlers to run.
|
|
115
|
+
|
|
116
|
+
If you want to strictly control the set of handlers that are run (for example, if you only want to run one particular handler), you can initialize the model yourself and pass in the set of handlers:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const model = new Model({
|
|
120
|
+
NetworkRequestHandler: Handlers.ModelHandlers.NetworkRequestHandler,
|
|
121
|
+
})
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Parsing a trace and getting data back
|
|
125
|
+
|
|
126
|
+
Once you have an instance of the model, you can call the `parse` method to take a set of raw events and parse them. Once parsed, you then have to call the `traceParsedData` method, providing an index of the trace you want to have the data for. This is because any model can store a number of traces. Each trace is given an index, which starts at 0 and increments by one as a new trace is parsed.
|
|
127
|
+
|
|
128
|
+
If you are managing multiple traces, you should store them in some form of indexed data structure so you can easily know which index to use to fetch any data from the model. You may delete a trace with `deleteTraceByIndex`, which will then update the indexes of all other traces too.
|
|
129
|
+
|
|
130
|
+
If you need to check how many traces you have, you can call `model.size()`. The latest trace's index is therefore always `model.size() - 1`.
|
|
131
|
+
|
|
132
|
+
## Waiting for updates from the model
|
|
133
|
+
|
|
134
|
+
When you call `parse` you have two options. You can `await` it, which will wait until the trace is fully parsed:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
await this.model.parse();
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
But it's likely preferable to instead use events, to avoid blocking the UI whilst parsing is in progress. You can listen to the `ModelUpdateEvent` for updates:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
this.model.addEventListener(Model.ModelUpdateEvent.eventName, event => {
|
|
144
|
+
const {data} = event as Model.ModelUpdateEvent;
|
|
145
|
+
|
|
146
|
+
if (data.data === 'done') {
|
|
147
|
+
// trace is complete
|
|
148
|
+
const newestData = this.model.traceParsedData(this.model.size() - 1);
|
|
149
|
+
} else {
|
|
150
|
+
// data.data will be an object: { index: X, total: Y}, which represents how many events (X) have been processed out of a total (Y).
|
|
151
|
+
// This can be used to show a progress bar, for example.
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## The structure of the final data object
|
|
157
|
+
|
|
158
|
+
The object returned from `traceParsedData()` is an object of key-value pairs where each key is the name of a handler, and the value is the data that was parsed and returned from that handler.
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
{
|
|
162
|
+
NetworkRequestHandler: ReturnType<typeof NetworkRequestHandler['data']>,
|
|
163
|
+
LayoutShiftHandler: ReturnType<typeof LayoutShiftHandler['data']>,
|
|
164
|
+
// and so on for each enabled Handler
|
|
165
|
+
}
|
|
166
|
+
```
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Copyright 2023 The Chromium Authors. All rights reserved.
|
|
2
|
+
// Use of this source code is governed by a BSD-style license that can be
|
|
3
|
+
// found in the LICENSE file.
|
|
4
|
+
|
|
5
|
+
// Run this first:
|
|
6
|
+
// front_end/models/trace/build-trace-engine-lib.sh
|
|
7
|
+
|
|
8
|
+
/* eslint-disable rulesdir/es_modules_import */
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import zlib from 'node:zlib';
|
|
11
|
+
|
|
12
|
+
/** @typedef {import('../front_end/models/trace/trace.ts')} TraceEngine */
|
|
13
|
+
|
|
14
|
+
// For types... see Connor's manual hack here:
|
|
15
|
+
// https://github.com/GoogleChrome/lighthouse/pull/15703/files#diff-ec7e073cf0e6135d4f2af9bc04fe6100ec0df80ad1686bee2da53871be5f1a7b
|
|
16
|
+
// and https://github.com/GoogleChrome/lighthouse/pull/15703/files#diff-6dab4507247217209f5ab0f6c343ca2b00af1300878abba81fb74d51cdfbedf9
|
|
17
|
+
|
|
18
|
+
/** @type {TraceEngine} */
|
|
19
|
+
import * as TraceEngine from './models/trace/trace.js';
|
|
20
|
+
|
|
21
|
+
polyfillDOMRect();
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {string} filename
|
|
25
|
+
* @returns {Promise<TraceEngine.TraceModel>}
|
|
26
|
+
*/
|
|
27
|
+
export async function analyzeTrace(filename) {
|
|
28
|
+
const traceEvents = loadTraceEventsFromFile(filename);
|
|
29
|
+
const model = TraceEngine.TraceModel.Model.createWithAllHandlers(TraceEngine.Types.Configuration.DEFAULT); // aka `fullTraceEngine`
|
|
30
|
+
await model.parse(traceEvents);
|
|
31
|
+
return model.traceParsedData();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// If run as CLI, parse the argv trace (or a fallback)
|
|
35
|
+
if (import.meta.url.endsWith(process?.argv[1])) {
|
|
36
|
+
cli();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function cli() {
|
|
40
|
+
const filename = process.argv.at(2);
|
|
41
|
+
const TraceEngine = await analyzeTrace(filename);
|
|
42
|
+
console.log(TraceEngine);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string=} filename
|
|
48
|
+
* @returns TraceEvent[]
|
|
49
|
+
*/
|
|
50
|
+
function loadTraceEventsFromFile(filename) {
|
|
51
|
+
const fileBuf = fs.readFileSync(filename);
|
|
52
|
+
let data;
|
|
53
|
+
if (isGzip(fileBuf)) {
|
|
54
|
+
data = zlib.gunzipSync(fileBuf);
|
|
55
|
+
} else {
|
|
56
|
+
data = fileBuf.toString('utf8');
|
|
57
|
+
}
|
|
58
|
+
const json = JSON.parse(data);
|
|
59
|
+
const traceEvents = json.traceEvents ?? json;
|
|
60
|
+
console.assert(Array.isArray(traceEvents));
|
|
61
|
+
return traceEvents;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Read the first 3 bytes looking for the gzip signature in the file header
|
|
66
|
+
* https://www.rfc-editor.org/rfc/rfc1952#page-6
|
|
67
|
+
* @param {ArrayBuffer} ab
|
|
68
|
+
* @returns boolean
|
|
69
|
+
*/
|
|
70
|
+
function isGzip(ab) {
|
|
71
|
+
const buf = new Uint8Array(ab);
|
|
72
|
+
if (!buf || buf.length < 3) {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return buf[0] === 0x1F && buf[1] === 0x8B && buf[2] === 0x08;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function polyfillDOMRect() {
|
|
79
|
+
|
|
80
|
+
// devtools assumes clientside :(
|
|
81
|
+
|
|
82
|
+
// Everything else in here is the DOMRect polyfill
|
|
83
|
+
// https://raw.githubusercontent.com/JakeChampion/polyfill-library/master/polyfills/DOMRect/polyfill.js
|
|
84
|
+
|
|
85
|
+
(function (global) {
|
|
86
|
+
function number(v) {
|
|
87
|
+
return v === undefined ? 0 : Number(v);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function different(u, v) {
|
|
91
|
+
return u !== v && !(isNaN(u) && isNaN(v));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function DOMRect(xArg, yArg, wArg, hArg) {
|
|
95
|
+
let x, y, width, height, left, right, top, bottom;
|
|
96
|
+
|
|
97
|
+
x = number(xArg);
|
|
98
|
+
y = number(yArg);
|
|
99
|
+
width = number(wArg);
|
|
100
|
+
height = number(hArg);
|
|
101
|
+
|
|
102
|
+
Object.defineProperties(this, {
|
|
103
|
+
x: {
|
|
104
|
+
get: function () { return x; },
|
|
105
|
+
set: function (newX) {
|
|
106
|
+
if (different(x, newX)) {
|
|
107
|
+
x = newX;
|
|
108
|
+
left = right = undefined;
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
enumerable: true
|
|
112
|
+
},
|
|
113
|
+
y: {
|
|
114
|
+
get: function () { return y; },
|
|
115
|
+
set: function (newY) {
|
|
116
|
+
if (different(y, newY)) {
|
|
117
|
+
y = newY;
|
|
118
|
+
top = bottom = undefined;
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
enumerable: true
|
|
122
|
+
},
|
|
123
|
+
width: {
|
|
124
|
+
get: function () { return width; },
|
|
125
|
+
set: function (newWidth) {
|
|
126
|
+
if (different(width, newWidth)) {
|
|
127
|
+
width = newWidth;
|
|
128
|
+
left = right = undefined;
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
enumerable: true
|
|
132
|
+
},
|
|
133
|
+
height: {
|
|
134
|
+
get: function () { return height; },
|
|
135
|
+
set: function (newHeight) {
|
|
136
|
+
if (different(height, newHeight)) {
|
|
137
|
+
height = newHeight;
|
|
138
|
+
top = bottom = undefined;
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
enumerable: true
|
|
142
|
+
},
|
|
143
|
+
left: {
|
|
144
|
+
get: function () {
|
|
145
|
+
if (left === undefined) {
|
|
146
|
+
left = x + Math.min(0, width);
|
|
147
|
+
}
|
|
148
|
+
return left;
|
|
149
|
+
},
|
|
150
|
+
enumerable: true
|
|
151
|
+
},
|
|
152
|
+
right: {
|
|
153
|
+
get: function () {
|
|
154
|
+
if (right === undefined) {
|
|
155
|
+
right = x + Math.max(0, width);
|
|
156
|
+
}
|
|
157
|
+
return right;
|
|
158
|
+
},
|
|
159
|
+
enumerable: true
|
|
160
|
+
},
|
|
161
|
+
top: {
|
|
162
|
+
get: function () {
|
|
163
|
+
if (top === undefined) {
|
|
164
|
+
top = y + Math.min(0, height);
|
|
165
|
+
}
|
|
166
|
+
return top;
|
|
167
|
+
},
|
|
168
|
+
enumerable: true
|
|
169
|
+
},
|
|
170
|
+
bottom: {
|
|
171
|
+
get: function () {
|
|
172
|
+
if (bottom === undefined) {
|
|
173
|
+
bottom = y + Math.max(0, height);
|
|
174
|
+
}
|
|
175
|
+
return bottom;
|
|
176
|
+
},
|
|
177
|
+
enumerable: true
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
globalThis.DOMRect = DOMRect;
|
|
183
|
+
})(globalThis);
|
|
184
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export declare const removeElement: <T>(array: T[], element: T, firstOnly?: boolean) => boolean;
|
|
2
|
+
type NumberComparator = (a: number, b: number) => number;
|
|
3
|
+
export declare function sortRange(array: number[], comparator: NumberComparator, leftBound: number, rightBound: number, sortWindowLeft: number, sortWindowRight: number): number[];
|
|
4
|
+
export declare const binaryIndexOf: <T, S>(array: T[], value: S, comparator: (a: S, b: T) => number) => number;
|
|
5
|
+
export declare const intersectOrdered: <T>(array1: T[], array2: T[], comparator: (a: T, b: T) => number) => T[];
|
|
6
|
+
export declare const mergeOrdered: <T>(array1: T[], array2: T[], comparator: (a: T, b: T) => number) => T[];
|
|
7
|
+
export declare const DEFAULT_COMPARATOR: (a: string | number, b: string | number) => -1 | 0 | 1;
|
|
8
|
+
/**
|
|
9
|
+
* Returns the index of the element closest to the needle that is equal to or
|
|
10
|
+
* greater than it. Assumes that the provided array is sorted.
|
|
11
|
+
*
|
|
12
|
+
* If no element is found, the right bound is returned.
|
|
13
|
+
*
|
|
14
|
+
* Uses the provided comparator function to determine if two items are equal or
|
|
15
|
+
* if one is greater than the other. If you are working with strings or
|
|
16
|
+
* numbers, you can use ArrayUtilities.DEFAULT_COMPARATOR. Otherwise, you
|
|
17
|
+
* should define one that takes the needle element and an element from the
|
|
18
|
+
* array and returns a positive or negative number to indicate which is greater
|
|
19
|
+
* than the other.
|
|
20
|
+
*
|
|
21
|
+
* When specified, |left| (inclusive) and |right| (exclusive) indices
|
|
22
|
+
* define the search window.
|
|
23
|
+
*/
|
|
24
|
+
export declare function lowerBound<T>(array: Uint32Array | Int32Array, needle: T, comparator: (needle: T, b: number) => number, left?: number, right?: number): number;
|
|
25
|
+
export declare function lowerBound<S, T>(array: S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;
|
|
26
|
+
export declare function lowerBound<S, T>(array: readonly S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;
|
|
27
|
+
/**
|
|
28
|
+
* Returns the index of the element closest to the needle that is greater than
|
|
29
|
+
* it. Assumes that the provided array is sorted.
|
|
30
|
+
*
|
|
31
|
+
* If no element is found, the right bound is returned.
|
|
32
|
+
*
|
|
33
|
+
* Uses the provided comparator function to determine if two items are equal or
|
|
34
|
+
* if one is greater than the other. If you are working with strings or
|
|
35
|
+
* numbers, you can use ArrayUtilities.DEFAULT_COMPARATOR. Otherwise, you
|
|
36
|
+
* should define one that takes the needle element and an element from the
|
|
37
|
+
* array and returns a positive or negative number to indicate which is greater
|
|
38
|
+
* than the other.
|
|
39
|
+
*
|
|
40
|
+
* When specified, |left| (inclusive) and |right| (exclusive) indices
|
|
41
|
+
* define the search window.
|
|
42
|
+
*/
|
|
43
|
+
export declare function upperBound<T>(array: Uint32Array, needle: T, comparator: (needle: T, b: number) => number, left?: number, right?: number): number;
|
|
44
|
+
export declare function upperBound<S, T>(array: S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;
|
|
45
|
+
/**
|
|
46
|
+
* Obtains the first item in the array that satisfies the predicate function.
|
|
47
|
+
* So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
|
|
48
|
+
* the first item arr[i] such that arr[i] > 5 you would be returned 2, because
|
|
49
|
+
* array[2] is 6, the first item in the array that satisfies the
|
|
50
|
+
* predicate function.
|
|
51
|
+
*
|
|
52
|
+
* Please note: this presupposes that the array is already ordered.
|
|
53
|
+
*/
|
|
54
|
+
export declare function nearestIndexFromBeginning<T>(arr: T[], predicate: (arrayItem: T) => boolean): number | null;
|
|
55
|
+
/**
|
|
56
|
+
* Obtains the last item in the array that satisfies the predicate function.
|
|
57
|
+
* So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
|
|
58
|
+
* the last item arr[i] such that arr[i] < 5 you would be returned 1, because
|
|
59
|
+
* arr[1] is 4, the last item in the array that satisfies the
|
|
60
|
+
* predicate function.
|
|
61
|
+
*
|
|
62
|
+
* Please note: this presupposes that the array is already ordered.
|
|
63
|
+
*/
|
|
64
|
+
export declare function nearestIndexFromEnd<T>(arr: readonly T[], predicate: (arrayItem: T) => boolean): number | null;
|
|
65
|
+
export declare function arrayDoesNotContainNullOrUndefined<T>(arr: (T | null | undefined)[]): arr is T[];
|
|
66
|
+
export {};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// Copyright (c) 2020 The Chromium Authors. All rights reserved.
|
|
2
|
+
// Use of this source code is governed by a BSD-style license that can be
|
|
3
|
+
// found in the LICENSE file.
|
|
4
|
+
export const removeElement = (array, element, firstOnly) => {
|
|
5
|
+
let index = array.indexOf(element);
|
|
6
|
+
if (index === -1) {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
if (firstOnly) {
|
|
10
|
+
array.splice(index, 1);
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
for (let i = index + 1, n = array.length; i < n; ++i) {
|
|
14
|
+
if (array[i] !== element) {
|
|
15
|
+
array[index++] = array[i];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
array.length = index;
|
|
19
|
+
return true;
|
|
20
|
+
};
|
|
21
|
+
function swap(array, i1, i2) {
|
|
22
|
+
const temp = array[i1];
|
|
23
|
+
array[i1] = array[i2];
|
|
24
|
+
array[i2] = temp;
|
|
25
|
+
}
|
|
26
|
+
function partition(array, comparator, left, right, pivotIndex) {
|
|
27
|
+
const pivotValue = array[pivotIndex];
|
|
28
|
+
swap(array, right, pivotIndex);
|
|
29
|
+
let storeIndex = left;
|
|
30
|
+
for (let i = left; i < right; ++i) {
|
|
31
|
+
if (comparator(array[i], pivotValue) < 0) {
|
|
32
|
+
swap(array, storeIndex, i);
|
|
33
|
+
++storeIndex;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
swap(array, right, storeIndex);
|
|
37
|
+
return storeIndex;
|
|
38
|
+
}
|
|
39
|
+
function quickSortRange(array, comparator, left, right, sortWindowLeft, sortWindowRight) {
|
|
40
|
+
if (right <= left) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const pivotIndex = Math.floor(Math.random() * (right - left)) + left;
|
|
44
|
+
const pivotNewIndex = partition(array, comparator, left, right, pivotIndex);
|
|
45
|
+
if (sortWindowLeft < pivotNewIndex) {
|
|
46
|
+
quickSortRange(array, comparator, left, pivotNewIndex - 1, sortWindowLeft, sortWindowRight);
|
|
47
|
+
}
|
|
48
|
+
if (pivotNewIndex < sortWindowRight) {
|
|
49
|
+
quickSortRange(array, comparator, pivotNewIndex + 1, right, sortWindowLeft, sortWindowRight);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function sortRange(array, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight) {
|
|
53
|
+
if (leftBound === 0 && rightBound === (array.length - 1) && sortWindowLeft === 0 && sortWindowRight >= rightBound) {
|
|
54
|
+
array.sort(comparator);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
quickSortRange(array, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight);
|
|
58
|
+
}
|
|
59
|
+
return array;
|
|
60
|
+
}
|
|
61
|
+
export const binaryIndexOf = (array, value, comparator) => {
|
|
62
|
+
const index = lowerBound(array, value, comparator);
|
|
63
|
+
return index < array.length && comparator(value, array[index]) === 0 ? index : -1;
|
|
64
|
+
};
|
|
65
|
+
function mergeOrIntersect(array1, array2, comparator, mergeNotIntersect) {
|
|
66
|
+
const result = [];
|
|
67
|
+
let i = 0;
|
|
68
|
+
let j = 0;
|
|
69
|
+
while (i < array1.length && j < array2.length) {
|
|
70
|
+
const compareValue = comparator(array1[i], array2[j]);
|
|
71
|
+
if (mergeNotIntersect || !compareValue) {
|
|
72
|
+
result.push(compareValue <= 0 ? array1[i] : array2[j]);
|
|
73
|
+
}
|
|
74
|
+
if (compareValue <= 0) {
|
|
75
|
+
i++;
|
|
76
|
+
}
|
|
77
|
+
if (compareValue >= 0) {
|
|
78
|
+
j++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (mergeNotIntersect) {
|
|
82
|
+
while (i < array1.length) {
|
|
83
|
+
result.push(array1[i++]);
|
|
84
|
+
}
|
|
85
|
+
while (j < array2.length) {
|
|
86
|
+
result.push(array2[j++]);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
export const intersectOrdered = (array1, array2, comparator) => {
|
|
92
|
+
return mergeOrIntersect(array1, array2, comparator, false);
|
|
93
|
+
};
|
|
94
|
+
export const mergeOrdered = (array1, array2, comparator) => {
|
|
95
|
+
return mergeOrIntersect(array1, array2, comparator, true);
|
|
96
|
+
};
|
|
97
|
+
export const DEFAULT_COMPARATOR = (a, b) => {
|
|
98
|
+
return a < b ? -1 : (a > b ? 1 : 0);
|
|
99
|
+
};
|
|
100
|
+
export function lowerBound(array, needle, comparator, left, right) {
|
|
101
|
+
let l = left || 0;
|
|
102
|
+
let r = right !== undefined ? right : array.length;
|
|
103
|
+
while (l < r) {
|
|
104
|
+
const m = (l + r) >> 1;
|
|
105
|
+
if (comparator(needle, array[m]) > 0) {
|
|
106
|
+
l = m + 1;
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
r = m;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return r;
|
|
113
|
+
}
|
|
114
|
+
export function upperBound(array, needle, comparator, left, right) {
|
|
115
|
+
let l = left || 0;
|
|
116
|
+
let r = right !== undefined ? right : array.length;
|
|
117
|
+
while (l < r) {
|
|
118
|
+
const m = (l + r) >> 1;
|
|
119
|
+
if (comparator(needle, array[m]) >= 0) {
|
|
120
|
+
l = m + 1;
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
r = m;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return r;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Obtains the first or last item in the array that satisfies the predicate function.
|
|
130
|
+
* So, for example, if the array were arr = [2, 4, 6, 8, 10], and you are looking for
|
|
131
|
+
* the last item arr[i] such that arr[i] < 5 you would be returned 1, because
|
|
132
|
+
* array[1] is 4, the last item in the array that satisfies the
|
|
133
|
+
* predicate function.
|
|
134
|
+
*
|
|
135
|
+
* If instead you were looking for the first item in the same array that satisfies
|
|
136
|
+
* arr[i] > 5 you would be returned 2 because array[2] = 6.
|
|
137
|
+
*
|
|
138
|
+
* Please note: this presupposes that the array is already ordered.
|
|
139
|
+
*/
|
|
140
|
+
function nearestIndex(arr, predicate, searchStart) {
|
|
141
|
+
const searchFromEnd = searchStart === "END" /* NearestSearchStart.END */;
|
|
142
|
+
if (arr.length === 0) {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
let left = 0;
|
|
146
|
+
let right = arr.length - 1;
|
|
147
|
+
let pivot = 0;
|
|
148
|
+
let matchesPredicate = false;
|
|
149
|
+
let moveToTheRight = false;
|
|
150
|
+
let middle = 0;
|
|
151
|
+
do {
|
|
152
|
+
middle = left + (right - left) / 2;
|
|
153
|
+
pivot = searchFromEnd ? Math.ceil(middle) : Math.floor(middle);
|
|
154
|
+
matchesPredicate = predicate(arr[pivot]);
|
|
155
|
+
moveToTheRight = matchesPredicate === searchFromEnd;
|
|
156
|
+
if (moveToTheRight) {
|
|
157
|
+
left = Math.min(right, pivot + (left === pivot ? 1 : 0));
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
right = Math.max(left, pivot + (right === pivot ? -1 : 0));
|
|
161
|
+
}
|
|
162
|
+
} while (right !== left);
|
|
163
|
+
// Special-case: the indexed item doesn't pass the predicate. This
|
|
164
|
+
// occurs when none of the items in the array are a match for the
|
|
165
|
+
// predicate.
|
|
166
|
+
if (!predicate(arr[left])) {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
return left;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Obtains the first item in the array that satisfies the predicate function.
|
|
173
|
+
* So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
|
|
174
|
+
* the first item arr[i] such that arr[i] > 5 you would be returned 2, because
|
|
175
|
+
* array[2] is 6, the first item in the array that satisfies the
|
|
176
|
+
* predicate function.
|
|
177
|
+
*
|
|
178
|
+
* Please note: this presupposes that the array is already ordered.
|
|
179
|
+
*/
|
|
180
|
+
export function nearestIndexFromBeginning(arr, predicate) {
|
|
181
|
+
return nearestIndex(arr, predicate, "BEGINNING" /* NearestSearchStart.BEGINNING */);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Obtains the last item in the array that satisfies the predicate function.
|
|
185
|
+
* So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
|
|
186
|
+
* the last item arr[i] such that arr[i] < 5 you would be returned 1, because
|
|
187
|
+
* arr[1] is 4, the last item in the array that satisfies the
|
|
188
|
+
* predicate function.
|
|
189
|
+
*
|
|
190
|
+
* Please note: this presupposes that the array is already ordered.
|
|
191
|
+
*/
|
|
192
|
+
export function nearestIndexFromEnd(arr, predicate) {
|
|
193
|
+
return nearestIndex(arr, predicate, "END" /* NearestSearchStart.END */);
|
|
194
|
+
}
|
|
195
|
+
// Type guard for ensuring that `arr` does not contain null or undefined
|
|
196
|
+
export function arrayDoesNotContainNullOrUndefined(arr) {
|
|
197
|
+
return !arr.includes(null) && !arr.includes(undefined);
|
|
198
|
+
}
|
|
199
|
+
//# sourceMappingURL=array-utilities.js.map
|