OpoTests/Public/ecma/Modules/Format/SelectFormat.ecma.js
2025-10-25 17:34:51 +02:00

118 lines
3.7 KiB
JavaScript

"use strict";
import {Utils} from "../../Utils/Utils.ecma.js";
import {Check} from "../../Utils/Check.ecma.js";
import {FormatModule} from "../FormatModule.ecma.js";
/**
* @typedef {import("../FormatModule.ecma.js").FormatModule} FormatModule
*/
/**
* @class SelectFormat
* @constructor
* @param {!FormatModule} format
* @returns {void}
* @access public
* @static
*/
export const SelectFormat = (function(){
/**
* @constructs SelectFormat
* @param {!FormatModule} format
* @returns {void}
* @access private
* @static
*/
const SelectFormat = function(format){
/** @type {SelectFormat} */
const self = this;
/**
* @returns {void}
* @access private
*/
const constructor = () => {
format.modes.select = self.get;
format.checks.select = self.check;
format.modes.Select = (inputs, shared, fragments) => self.get(inputs, {
...shared, capitalized : true
}, fragments);
format.checks.Select = (string, inputs, shared, fragments) => self.check(string, inputs, {
...shared, capitalized : true
}, fragments);
};
/**
* @param {!(string|Array.<any|null>)} inputs
* @param {!Object.<string, any|null>} [shared = {}]
* @param {!Array.<string>} [fragments = []]
* @returns {string}
* @access public
*/
this.get = (inputs, shared = {}, fragments = []) => {
/** @type {[[number, number], string, Array.<string>]} */
const [range, separator, original_items] = (
Check.is_string(inputs) ? ((_, range, separator, items) => [
range.split("-").map(Number), separator, items.split("|")
])(...inputs.match(/^([^,]+),([^,]+),(.*)$/)) :
Check.is_array(inputs) ? inputs :
[]),
/** @type {number} */
i = Utils.get_random(...range);
if(!i)
return "";
/** @type {Array.<string>} */
const items = [...original_items];
/** @type {number} */
let l = items.length,
/** @type {string} */
results;
if(l < 2)
results = items.join("");
else{
Utils.randomize_array(items);
items.splice(0, l - i);
l = items.length;
results = (
l < 2 ? items[0] :
items.slice(0, l - 1).join(", ") + (
!separator ? " " :
/^[a-z 0-9]+$/i.test(separator.trim()) ? " " + separator.trim() + " " :
separator) + items[l - 1]);
};
results = format.execute(results, shared, fragments);
return shared.capitalized ? results.replace(/^./, character => character.toUpperCase()) : results;
};
/**
* @param {!string} string
* @param {!(string|Array.<string>)} inputs
* @param {!Object.<string, any|null>} [shared = {}]
* @param {!Array.<string>} [fragments = []]
* @returns {number}
* @access public
*/
this.check = (string, inputs, shared = {}, fragments = []) => format.check_select(string, (
Check.is_string(inputs) ? ((_, range, separator, options) => [
range.split("-").map(Number), separator, options.split("|")
])(...inputs.match(/^([^,]+),([^,]+),(.*)$/)) :
Check.is_array(inputs) ? inputs :
[]), shared, fragments);
constructor();
};
return SelectFormat;
})();