import { Vec2, Vec3 } from 'cc'; export default class Utilities { /** * * @param time (s) * @returns */ public static delay(time: number): Promise { return new Promise((resolve) => setTimeout(resolve, time * 1000)); } /** *@param predicate * @param time (s) * @returns */ public static async waitUntil(predicate: () => boolean, timeCheck = 0.01) { while (!predicate()) { await this.delay(timeCheck); } } public static getJson(json: string): any { try { return JSON.parse(json); } catch (error) { return false; } } public static Vec2ToVec3(Vec2: Vec2): Vec3 { return new Vec3(Vec2.x, Vec2.y); } public static Vec3ToVec2(Vec3: Vec3): Vec2 { return new Vec2(Vec3.x, Vec3.y); } public static weightedRandom(items: T[], weights: number[]): T { const weightsClone = [...weights]; const totalWeight = weightsClone.reduce((a, b) => a + b, 0); let random = Math.random() * totalWeight; const item = items.find((_, i) => (random -= weightsClone[i]) <= 0); return item; // for (i = 1; i < weightsClone.length; i++) { // weightsClone[i] += weights[i - 1]; // } // let random = Math.random() * weightsClone[weightsClone.length - 1]; // for (i = 0; i < weightsClone.length; i++) { // if (weightsClone[i] > random) break; // } // return [items[i], i]; } }