Debian Codegraph @

node/@xterm/xterm/src/vs/base/common/numbers.ts

raw
1 /*---------------------------------------------------------------------------------------------
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt in the project root for license information.
4 *--------------------------------------------------------------------------------------------*/
5
6 export function clamp(value: number, min: number, max: number): number {
7 return Math.min(Math.max(value, min), max);
8 }
9
10 export function rot(index: number, modulo: number): number {
11 return (modulo + (index % modulo)) % modulo;
12 }
13
14 export class Counter {
15 private _next = 0;
16
17 getNext(): number {
18 return this._next++;
19 }
20 }
21
22 export class MovingAverage {
23
24 private _n = 1;
25 private _val = 0;
26
27 update(value: number): number {
28 this._val = this._val + (value - this._val) / this._n;
29 this._n += 1;
30 return this._val;
31 }
32
33 get value(): number {
34 return this._val;
35 }
36 }
37
38 export class SlidingWindowAverage {
39
40 private _n: number = 0;
41 private _val = 0;
42
43 private readonly _values: number[] = [];
44 private _index: number = 0;
45 private _sum = 0;
46
47 constructor(size: number) {
48 this._values = new Array(size);
49 this._values.fill(0, 0, size);
50 }
51
52 update(value: number): number {
53 const oldValue = this._values[this._index];
54 this._values[this._index] = value;
55 this._index = (this._index + 1) % this._values.length;
56
57 this._sum -= oldValue;
58 this._sum += value;
59
60 if (this._n < this._values.length) {
61 this._n += 1;
62 }
63
64 this._val = this._sum / this._n;
65 return this._val;
66 }
67
68 get value(): number {
69 return this._val;
70 }
71 }
72
73 /** Returns whether the point is within the triangle formed by the following 6 x/y point pairs */
74 export function isPointWithinTriangle(
75 x: number, y: number,
76 ax: number, ay: number,
77 bx: number, by: number,
78 cx: number, cy: number
79 ) {
80 const v0x = cx - ax;
81 const v0y = cy - ay;
82 const v1x = bx - ax;
83 const v1y = by - ay;
84 const v2x = x - ax;
85 const v2y = y - ay;
86
87 const dot00 = v0x * v0x + v0y * v0y;
88 const dot01 = v0x * v1x + v0y * v1y;
89 const dot02 = v0x * v2x + v0y * v2y;
90 const dot11 = v1x * v1x + v1y * v1y;
91 const dot12 = v1x * v2x + v1y * v2y;
92
93 const invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
94 const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
95 const v = (dot00 * dot12 - dot01 * dot02) * invDenom;
96
97 return u >= 0 && v >= 0 && u + v < 1;
98 }