UNPKG

args-any

Version:

Utility lib for parsing command options

100 lines 3.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OptionMap = void 0; const string_converter_1 = require("string-converter"); const args_parser_1 = require("../parser/args.parser"); const prefixless_key_parser_1 = require("../parser/prefixless-key.parser"); const partial_1 = require("../partial"); const types_1 = require("../../types"); /** * Map of `Option` */ class OptionMap extends types_1.ReadonlyMap { mapArgs() { const options = this.arg.reduce((acc, curr) => { if (this.has(curr)) { acc.push(curr); const option = this.get(curr); if (option === null || option === void 0 ? void 0 : option.value) { acc.push(option.value); } } return acc; }, []); return { all: () => this.arg, options: () => options, other: () => this.arg.filter((x) => !options.includes(x)) }; } constructor(arg, settings) { super((0, args_parser_1.parseArgs)(arg, settings)); this.arg = arg; this.settings = settings; // this.args = args; this.args = this.mapArgs(); // this.args = argContainer(arg, this); this.settings = settings; } /** * Filter a list of items based on options defined in the map * @param items The items to filter * @returns The items matching options in the map */ filter(...items) { // allow this alias for now // eslint-disable-next-line @typescript-eslint/no-this-alias const map = this; return items.filter((x) => this.matches.call(map, x)); } /** * Check if an option exists in the map * @param key key of the option to check * @returns `true` if the option exists, otherwise `false` */ has(key) { return super.has(prefixless_key_parser_1.prefixlessKey.parse(key, this.settings)); } /** * Creates a `Partial<T>` from the `OptionMap` with the keys and values defined in the map */ asPartial() { return (0, partial_1.toObject)(this); } /** * Get option by key * @param key The option to fetch * @returns `Option` for the specified `key` */ get(key) { return super.get(prefixless_key_parser_1.prefixlessKey.parse(key, this.settings)); } /** @ignore */ matches(item) { return [...this.keys()].reduce((acc, curr) => { if (acc === false) return false; const itemValue = item[curr]; const option = this.get(curr); if (option === undefined) return false; const optionValue = (0, string_converter_1.convert)(option.value); switch (option.operator) { case types_1.Operator.Ne: return itemValue !== optionValue; case types_1.Operator.Ge: return (optionValue && itemValue >= optionValue) || false; case types_1.Operator.Gt: return (optionValue && itemValue > optionValue) || false; case types_1.Operator.Le: return (optionValue && itemValue <= optionValue) || false; case types_1.Operator.Lt: return (optionValue && itemValue < optionValue) || false; default: return itemValue === optionValue; } }, true); } } exports.OptionMap = OptionMap; //# sourceMappingURL=OptionMap.js.map