(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular-ru/cdk/coercion')) :
    typeof define === 'function' && define.amd ? define('@angular-ru/cdk/utils', ['exports', '@angular-ru/cdk/coercion'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global["angular-ru"] = global["angular-ru"] || {}, global["angular-ru"].cdk = global["angular-ru"].cdk || {}, global["angular-ru"].cdk.utils = {}), global["angular-ru"].cdk.coercion));
})(this, (function (exports, coercion) { 'use strict';

    function $any(value) {
        return value;
    }

    function $cast(value) {
        return value;
    }

    function checkValueIsEmpty(value) {
        // note: don't use isString for preserve circular dependencies
        var val = typeof value === 'string' ? value.trim() : value;
        return [undefined, null, NaN, '', Infinity].includes(val);
    }

    function checkEveryValueIsEmpty() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.every(checkValueIsEmpty);
    }

    function isFalse(value) {
        return value === false;
    }

    function checkEveryValueIsFalse() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.length === 0 ? false : values.every(isFalse);
    }

    function checkValueIsFilled(value) {
        return !checkValueIsEmpty(value);
    }

    function checkEveryValueIsFilled() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.every(checkValueIsFilled);
    }

    function isTrue(value) {
        return value === true;
    }

    function checkEveryValueIsTrue() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.length === 0 ? false : values.every(isTrue);
    }

    function checkSomeValueIsEmpty() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.some(checkValueIsEmpty);
    }

    function checkSomeValueIsFalse() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.some(isFalse);
    }

    function checkSomeValueIsTrue() {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.some(isTrue);
    }

    function isNil(value) {
        return value === null || typeof value === 'undefined';
    }

    function isNotNil(value) {
        return !isNil(value);
    }

    // eslint-disable-next-line max-lines-per-function
    function copyHtml(plainHtml) {
        var element = document.createElement('div');
        element.innerHTML = plainHtml;
        element.style.position = 'absolute';
        element.style.opacity = '0';
        element.style.pointerEvents = 'none';
        document.body.appendChild(element);
        var range = document.createRange();
        range.selectNode(element);
        var selection = window.getSelection();
        if (isNil(selection)) {
            throw new Error('Selection is not supported by this browser');
        }
        var previousRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
        selection.removeAllRanges();
        selection.addRange(range);
        // eslint-disable-next-line deprecation/deprecation
        document.execCommand('copy');
        document.body.removeChild(element);
        if (isNotNil(previousRange)) {
            selection.removeAllRanges();
            selection.addRange(previousRange);
        }
    }

    /**
     * @deprecated Use `copyString`
     */
    var copyBuffer = copyString;
    function copyString(str) {
        var _a, _b, _c;
        var firstIndex = 0;
        var el = document.createElement('textarea');
        el.value = str;
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        var selected = ((_a = document === null || document === void 0 ? void 0 : document.getSelection()) === null || _a === void 0 ? void 0 : _a.rangeCount) > firstIndex ? document === null || document === void 0 ? void 0 : document.getSelection().getRangeAt(firstIndex) : false;
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        if (coercion.coerceBoolean(selected)) {
            (_b = document === null || document === void 0 ? void 0 : document.getSelection()) === null || _b === void 0 ? void 0 : _b.removeAllRanges();
            (_c = document === null || document === void 0 ? void 0 : document.getSelection()) === null || _c === void 0 ? void 0 : _c.addRange(selected);
        }
    }

    var associative = {
        unitIndex: 0,
        pairIndex: 1,
        multipleIndex: 2
    };
    /**
     * @description: We pass this function a number, and an array of headers,
     * among which the correct form will be chosen to match the number.
     * The first element of the directory is for units, the second is for pairs,
     * and the third is for other numbers.
     *
     *
     * The declination depends on the last digit of the number.
     * Second: 1.
     * Seconds: 0, 5, 6, 7, 8, 9.
     * Seconds: 2, 3, 4.
     *
     * Given the ranges used, the last digit can be obtained as a remainder of division by 10.
     *
     * @param numberValue example as 1
     * @param dictionary example as ["арбуз", "арбуза", "арбузов"]
     * @return Nullable<string> as "арбуз"
     */
    function declinationOfNumber(numberValue, dictionary) {
        var remainder = Math.abs(numberValue) % 100;
        var result;
        if (isMultipleDeclination(remainder)) {
            result = dictionary[associative.multipleIndex];
        }
        else if (isPairDeclination(remainder)) {
            result = dictionary[associative.pairIndex];
        }
        else if (isUnitDeclination(remainder)) {
            result = dictionary[associative.unitIndex];
        }
        else {
            result = dictionary[associative.multipleIndex];
        }
        return result;
    }
    function isMultipleDeclination(remainder) {
        return remainder > 10 && remainder < 20;
    }
    function isPairDeclination(remainder) {
        return remainder % 10 > 1 && remainder % 10 < 5;
    }
    function isUnitDeclination(remainder) {
        return remainder % 10 === 1;
    }

    function detectChanges(detectorOrDetectors) {
        if (isNil(detectorOrDetectors)) {
            return;
        }
        if (Array.isArray(detectorOrDetectors)) {
            detectorOrDetectors.forEach(function (detector) { return internalDetectChanges(detector); });
        }
        else if (isNotNil(detectorOrDetectors)) {
            internalDetectChanges(detectorOrDetectors);
        }
    }
    function internalDetectChanges(cd) {
        if (isNotNil(cd) && !cd.destroyed) {
            cd.detectChanges();
        }
    }

    function downloadFile(file) {
        if (checkEveryValueIsEmpty(file.name, file.extension)) {
            throw new Error('File name or file extension must be provided');
        }
        var anchor = document.createElement('a');
        var url = window.URL.createObjectURL(file.blob);
        var filePath = [file.name, file.extension].filter(Boolean).join('.');
        anchor.href = url;
        anchor.download = filePath;
        anchor.click();
        window.URL.revokeObjectURL(url);
    }

    function fallbackIfEmpty(value, fallback) {
        return (checkValueIsEmpty(value) ? fallback : value);
    }

    /* eslint-disable @typescript-eslint/no-magic-numbers */
    function generateUid() {
        // eslint-disable-next-line spellcheck/spell-checker
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0;
            var v = c === 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    }

    function getBodyRect() {
        var _a;
        return (_a = document.querySelector('body')) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    }

    function isBoolean(value) {
        return typeof value === 'boolean';
    }

    function isTruthy(val) {
        return Boolean(val);
    }

    function isFalsy(val) {
        return !isTruthy(val);
    }

    function isIE(userAgent) {
        if (userAgent === void 0) { userAgent = navigator.userAgent; }
        return /edge|msie\s|trident\//i.test(userAgent);
    }

    function parseXmlFromString(xml, type) {
        if (type === void 0) { type = 'application/xml'; }
        var parser = new DOMParser();
        var dom = parser.parseFromString(xml, type);
        if (dom.documentElement.nodeName === 'parsererror') {
            console.error(dom);
            throw new Error('error while parsing');
        }
        return dom;
    }

    var DEFAULT_UNITS_MAP = {
        s: 1,
        m: 60,
        h: 3600,
        d: 86400,
        w: 604800
    };

    var NUMBER_PATTERN = "([0-9]+([.][0-9]+)?)";
    function replaceUnits(text, unitsMap) {
        return parseMultiLineText(text, unitsMap);
    }
    function parseMultiLineText(text, unitsMap) {
        var textList = [];
        text.split('\n').forEach(function (item) {
            var prepared = item;
            prepared = replaceMultiple(prepared, unitsMap);
            prepared = replaceSingle(prepared, unitsMap);
            textList.push(prepared);
        });
        return textList.join('\n');
    }
    function replaceMultiple(value, unitsMap) {
        var pattern = getMultipleUnitsPattern(unitsMap);
        var text = value;
        while (pattern.test(text)) {
            text = replaceByMatch(text, pattern, unitsMap);
        }
        return text;
    }
    function replaceSingle(value, unitsMap) {
        var pattern = getSingleUnitPattern(unitsMap);
        var text = value;
        while (pattern.test(text)) {
            text = replaceByMatch(text, pattern, unitsMap);
        }
        return text;
    }
    function replaceByMatch(text, pattern, unitsMap) {
        var _a, _b;
        var match = (_b = (_a = pattern.exec(text)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : '';
        var num = convertToNumber(match, unitsMap);
        var prepared = match.replace(RegExp(/\S.*\S/), num.toString());
        return text.replace(pattern, prepared);
    }
    function convertToNumber(text, unitsMap) {
        var units = text.trim();
        var sum = units
            .split(' ')
            .filter(function (item) { return item !== ''; })
            .map(function (item) {
            var coefficient = getCoefficient(item);
            var unitValue = getUnitValue(item, unitsMap);
            return coefficient * unitValue;
        })
            .reduce(function (accumulator, item) { return accumulator + item; }, 0);
        return sum;
    }
    function getMultipleUnitsPattern(unitsMap) {
        var unitKeys = getUnitKeys(unitsMap);
        return new RegExp("(^|\\s)((" + NUMBER_PATTERN + ")(" + unitKeys + "))(\\s+((" + NUMBER_PATTERN + ")(" + unitKeys + ")))+(\\s|$)");
    }
    function getSingleUnitPattern(unitsMap) {
        var unitKeys = getUnitKeys(unitsMap);
        return new RegExp("(^|\\s)(" + NUMBER_PATTERN + ")(" + unitKeys + ")(\\s|$)");
    }
    function getCoefficient(unit) {
        var _a, _b;
        var prefix = (_b = (_a = unit.match("^" + NUMBER_PATTERN)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : '';
        var result = prefix.includes('.') ? parseFloat(prefix) : parseInt(prefix);
        return result;
    }
    function getUnitValue(unit, unitsMap) {
        var _a, _b, _c;
        var postfix = (_b = (_a = unit.match(/[^0-9]+$/s)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : '';
        return (_c = unitsMap[postfix]) !== null && _c !== void 0 ? _c : 0;
    }
    function getUnitKeys(unitsMap) {
        return Object.keys(unitsMap)
            .map(function (item) { return (item.length > 1 ? "(" + item + ")" : item); })
            .join('|');
    }

    function serializeXmlToString(xml) {
        return new XMLSerializer().serializeToString(xml);
    }

    function tryParseJson(text) {
        try {
            return JSON.parse(text);
        }
        catch (_a) {
            return undefined;
        }
    }

    /**
     * Generated bundle index. Do not edit.
     */

    exports.$any = $any;
    exports.$cast = $cast;
    exports.DEFAULT_UNITS_MAP = DEFAULT_UNITS_MAP;
    exports.checkEveryValueIsEmpty = checkEveryValueIsEmpty;
    exports.checkEveryValueIsFalse = checkEveryValueIsFalse;
    exports.checkEveryValueIsFilled = checkEveryValueIsFilled;
    exports.checkEveryValueIsTrue = checkEveryValueIsTrue;
    exports.checkSomeValueIsEmpty = checkSomeValueIsEmpty;
    exports.checkSomeValueIsFalse = checkSomeValueIsFalse;
    exports.checkSomeValueIsTrue = checkSomeValueIsTrue;
    exports.checkValueIsEmpty = checkValueIsEmpty;
    exports.checkValueIsFilled = checkValueIsFilled;
    exports.copyBuffer = copyBuffer;
    exports.copyHtml = copyHtml;
    exports.copyString = copyString;
    exports.declinationOfNumber = declinationOfNumber;
    exports.detectChanges = detectChanges;
    exports.downloadFile = downloadFile;
    exports.fallbackIfEmpty = fallbackIfEmpty;
    exports.generateUid = generateUid;
    exports.getBodyRect = getBodyRect;
    exports.isBoolean = isBoolean;
    exports.isFalse = isFalse;
    exports.isFalsy = isFalsy;
    exports.isIE = isIE;
    exports.isNil = isNil;
    exports.isNotNil = isNotNil;
    exports.isTrue = isTrue;
    exports.isTruthy = isTruthy;
    exports.parseXmlFromString = parseXmlFromString;
    exports.replaceUnits = replaceUnits;
    exports.serializeXmlToString = serializeXmlToString;
    exports.tryParseJson = tryParseJson;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=angular-ru-cdk-utils.umd.js.map
