UNPKG

step-sequence-generator

Version:

A step sequence generator for figure skating programs

51 lines (50 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NumberGenerator = void 0; class NumberGenerator { constructor() { this._fallbackWeight = 0.1; } get fallbackWeight() { return this._fallbackWeight; } set fallbackWeight(value) { this._fallbackWeight = value; } /** * generateNumber * @arg args * @arg args.selection элементы * @arg args.weightMap список весов элементов * @arg args.weightKeyCreator callback для опредления ключа в weightMap */ generateNumber(args) { const weightList = this.createWeightList(args); const virtualChanceListLength = this.getVirtualChanceListLength(weightList); const randomIndex = this.getRandomIndex(virtualChanceListLength); return this.getItemIndex(weightList, randomIndex); } createWeightList(args) { const { selection, weightMap, weightKeyCreator } = args; return selection.map((item) => { const weightKey = weightKeyCreator(item); return weightMap.get(weightKey) ?? this.fallbackWeight; }); } getVirtualChanceListLength(chanceList) { return chanceList.reduce((acc, chance) => acc + chance, 0); } getRandomIndex(max) { return Math.random() * max; } getItemIndex(chanceList, randomIndex) { let cumulative = 0; for (let i = 0; i < chanceList.length; i++) { cumulative += chanceList[i]; if (cumulative >= randomIndex) return i; } return chanceList.length - 1; } } exports.NumberGenerator = NumberGenerator;