UNPKG

@onesy/date

Version:

Time and date utils library

52 lines (51 loc) 2.67 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const getStringVariables_1 = __importDefault(require("@onesy/utils/getStringVariables")); const setStringVariables_1 = __importDefault(require("@onesy/utils/setStringVariables")); const OnesyDate_1 = __importDefault(require("./OnesyDate")); const formats_1 = __importDefault(require("./formats")); function format(onesyDate = OnesyDate_1.default.onesyDate, value_ = `YYYY-MM-DDTHH:mm:ss`, options) { const l = (options === null || options === void 0 ? void 0 : options.l) || (value => value); if (onesyDate && onesyDate.valid) { let value = value_; const formatValues = (0, formats_1.default)(onesyDate); const abrs = formatValues.map(item => item.abr); // Extract and save all words quoted with: '', "", ``, {} or [], // in a string, so adding abr values doesn't override 'em const words = (0, getStringVariables_1.default)(value, { variablesRegExp: /('.*?'|".*?"|`.*?`|\{.*?\}|\[.*?\])/g, }); // Add placeholders before adding all abr values value = words.valueWithPlaceholders; // Replace all abr values // tslint:disable-next-line const reAbr = abrs.reduce((result, current, index) => result += `${current}${index !== abrs.length - 1 ? '|' : ''}`, ''); const abrVariables = (0, getStringVariables_1.default)(value, { variablesRegExp: new RegExp(reAbr, 'g'), cleanVariables: false, placeholderPrefix: '__', }); // Add placeholders for matches prior to adding all abr values value = abrVariables.valueWithPlaceholders; const abrVariablesToValue = []; abrVariables.variables.forEach(variable => { const format_ = formatValues.find(item => item.abr === variable); abrVariablesToValue.push({ key: variable, value: l(format_.value) }); }); // Replace abr variables with appropriate values value = (0, setStringVariables_1.default)(value, abrVariablesToValue, { getVariables: false, placeholderPrefix: '__', }); // Revert back all the saved words const wordsVariablesToValue = []; words.variables.forEach(variable => wordsVariablesToValue.push({ key: variable, value: variable })); value = (0, setStringVariables_1.default)(value, wordsVariablesToValue, { getVariables: false }); return value; } } exports.default = format;