Как автоматически вставить запятую или амперсанд между словами в JS на основе логического? - PullRequest
0 голосов
/ 07 ноября 2018
const confirmations = {
    quantity: false,
    total_price: true,
    unit_price: true
}

// Should print -> Total Price & Unit Price
// If three variables are true then should print -> Quantity, Total Price & Unit Price

Я знаю, что это может быть достигнуто с помощью пары if...else операторов, но это действительно глупо. Есть ли другой способ добиться этого?

Ответы [ 4 ]

0 голосов
/ 07 ноября 2018

Вот моя попытка. Гораздо стройнее после изучения версии Йосвела Кинтеро

const fmtText = obj => Object
    .keys(obj)                     // array of keys
    .filter(k => obj[k])           // take only the true ones 
    .join(", ")                    // join found keys with ,
    .replace(/_/g, " ")            // replace the underscore
    .replace(/\b([a-z])/g, x => x.toUpperCase()) // InitialCap
    .replace(/,(?=[^,]*$)/, ' &'); // replace last comma

const conf1 = { quantity: false, total_price: true, unit_price: true }
const conf2 = { quantity: true,  total_price: true, unit_price: true }
const conf3 = { quantity: false, total_price: true, unit_price: false }

console.log(fmtText(conf1))
console.log(fmtText(conf2))
console.log(fmtText(conf3))
0 голосов
/ 07 ноября 2018

Вы можете взять другой объект для формулировки, а затем создать красивую строку, заменив два последних слова амперсандом и все слова перед объединением с запятой.

function getString(confirmations) {
    const
        nice = a => a.concat(a.splice(-2, 2).join(' & ')).join(', '),
        words = { quantity: 'Quantity', total_price: 'Total Price', unit_price: 'Unit Price' };

    return nice(Object
        .entries(confirmations)
        .filter(([, v]) => v)
        .map(([w]) => words[w])
    );
}

console.log(getString({ quantity: false, total_price: true, unit_price: true }));
console.log(getString({ quantity: true, total_price: true, unit_price: true }));
console.log(getString({ quantity: false, total_price: true, unit_price: false }));
0 голосов
/ 07 ноября 2018

Это должно сделать работу:

const confirmations = {
    quantity: false,
    total_price: true,
    unit_price: true
};

// filter out false values and return object keys as an array of strings
const validatedConfirmations = Object.keys(confirmations).filter((name) => confirmations[name]);

// make them human readable
const humanReadableConfirmations = validatedConfirmations.map(makeItHumanReadable);

// crunch it all to a single string
const lastConfirmationMessage = humanReadableConfirmations.pop();
const confirmationMessage = humanReadableConfirmation.join(', ') + ` & ${lastConfirmationMessage}`;

Осторожно, если верен только один элемент, он будет отображать "& Unit Price", вы можете адаптировать его в любом случае.

0 голосов
/ 07 ноября 2018

Вы можете сделать:

const confirmations1 = {quantity: false, total_price: true, unit_price: true};
const confirmations2 = {quantity: true, total_price: true, unit_price: true};

const getFormattedSentence = obj => Object
  .keys(obj)
  .filter(k => obj[k])
  .map(k => k
    .split('_')
    .map(w => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ')
  )
  .join(', ')
  .replace(/,(?!.*,)/gmi, ' &');
  
console.log(getFormattedSentence(confirmations1));
console.log(getFormattedSentence(confirmations2));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...