Path: blob/main/extensions/copilot/src/util/vs/base/common/numbers.ts
13405 views
//!!! DO NOT modify, this file was COPIED from 'microsoft/vscode'12/*---------------------------------------------------------------------------------------------3* Copyright (c) Microsoft Corporation. All rights reserved.4* Licensed under the MIT License. See License.txt in the project root for license information.5*--------------------------------------------------------------------------------------------*/67import { assert } from './assert';89export function clamp(value: number, min: number, max: number): number {10return Math.min(Math.max(value, min), max);11}1213export function rot(index: number, modulo: number): number {14return (modulo + (index % modulo)) % modulo;15}1617export class Counter {18private _next = 0;1920getNext(): number {21return this._next++;22}23}2425export class MovingAverage {2627private _n = 1;28private _val = 0;2930update(value: number): number {31this._val = this._val + (value - this._val) / this._n;32this._n += 1;33return this._val;34}3536get value(): number {37return this._val;38}39}4041export class SlidingWindowAverage {4243private _n: number = 0;44private _val = 0;4546private readonly _values: number[] = [];47private _index: number = 0;48private _sum = 0;4950constructor(size: number) {51this._values = new Array(size);52this._values.fill(0, 0, size);53}5455update(value: number): number {56const oldValue = this._values[this._index];57this._values[this._index] = value;58this._index = (this._index + 1) % this._values.length;5960this._sum -= oldValue;61this._sum += value;6263if (this._n < this._values.length) {64this._n += 1;65}6667this._val = this._sum / this._n;68return this._val;69}7071get value(): number {72return this._val;73}74}7576/** Returns whether the point is within the triangle formed by the following 6 x/y point pairs */77export function isPointWithinTriangle(78x: number, y: number,79ax: number, ay: number,80bx: number, by: number,81cx: number, cy: number82) {83const v0x = cx - ax;84const v0y = cy - ay;85const v1x = bx - ax;86const v1y = by - ay;87const v2x = x - ax;88const v2y = y - ay;8990const dot00 = v0x * v0x + v0y * v0y;91const dot01 = v0x * v1x + v0y * v1y;92const dot02 = v0x * v2x + v0y * v2y;93const dot11 = v1x * v1x + v1y * v1y;94const dot12 = v1x * v2x + v1y * v2y;9596const invDenom = 1 / (dot00 * dot11 - dot01 * dot01);97const u = (dot11 * dot02 - dot01 * dot12) * invDenom;98const v = (dot00 * dot12 - dot01 * dot02) * invDenom;99100return u >= 0 && v >= 0 && u + v < 1;101}102103export function randomChance(p: number): boolean {104assert(p >= 0 && p <= 1, 'p must be between 0 and 1');105return Math.random() < p;106}107108109