Skip to content

Instantly share code, notes, and snippets.

@uqmessias
Last active February 13, 2023 03:21
Show Gist options
  • Save uqmessias/6e23a0a65c4366731fc88a610bf549ad to your computer and use it in GitHub Desktop.
Save uqmessias/6e23a0a65c4366731fc88a610bf549ad to your computer and use it in GitHub Desktop.

It sums a list of amounts within a markdown snippet

_**2079,30** (2022/01)_<br>  
_**2014,40** (2022/02)_<br>  
_**2161,51** (2022/03)_<br>  
_**226,29** (2022/04)_<br>  
_**2.283,29** (2022/05)_<br>  
_**223,92** (2022/06)_<br>  
_**222,48** (2022/07)_<br>  
_**223,72** (2022/08)_<br>  
_**325,01** (2022/09)_<br>  
_**294,15** (2022/10)_<br>  
_**198,01** (2022/11)_<br>  
_**252,54** (2022/12)_<br>
/**
 *
 * @param {string} text Markdown text with the values to be added
 * @returns {Array<number>} A list with all the found amounts in the markdown `text`
 */
function getAmountList(text) {
  if (!text) {
    return [];
  }
  const matches = text.match(/-?([0-9]*)\.?([0-9]*)\.?([0-9]*),([0-9]{2})/gi);

  return matches == null
    ? []
    : matches.map(
        (amount) => parseInt(amount.replace(/([^\-0-9]*)/gi, ''), 10) / 100
      );
}


/**
 *
 * @param {Array<number>} amountList List with all amounts to be added
 * @returns {number} The sum of all items in the {amountList}
 */
function sumAmountList(amountList) {
  return amountList.reduce((sum, amount) => sum + amount, 0);
}

/**
 *
 * @param {string} text Markdown text with the values to be added
 * @returns {number} The sum of all items in the {amountList}
 */
function getTotal(text) {
  return sumAmountList(getAmountList(text));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment