minus one

JSvalueprimitiveStringmethod.replace() ⟩ example ⟩ minus one

// amount-unit pattern
const amountUnitPattern = /\b(\d+) (\w+)\b/g;
// groups:                   ╰─1─╯ ╰─2─╯

const stock = "1 lemon, 2 cabbages, and 101 eggs";
// matches:    ╰─────╯  ╰────────╯      ╰──────╯
// minus 1: → no lemon, 1 cabbage, and 100 eggs

// replacer function:                                   ╭─G1─╮  ╭G2╮
const minus1 = stock.replace(amountUnitPattern, (match, amount, unit) => {
    
    amount = +amount - 1;
    
    // only one left, remove the 's'
    if (amount === 1) unit = unit.slice(0, unit.length - 1);
    if (amount === 0) amount = "no";
    
    return amount + " " + unit;
});

Last updated