utils.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. function p5Utils__format(str, args) {
  2. return args.reduce(
  3. function (ret, arg, idx) {
  4. return ret.replace(new RegExp('\\{' + idx + '\\}', 'gm'), arg)
  5. },
  6. str
  7. )
  8. }
  9. function p5Utils__parseFloatOrZero(strToParse) {
  10. if (!strToParse) return 0
  11. if ("string" === typeof strToParse) {
  12. strToParse = strToParse.replace(/,/g, '.')
  13. strToParse = strToParse.replace(/ /g, '')
  14. }
  15. var floatVal = parseFloat(strToParse)
  16. return (!isNaN(floatVal))? floatVal : 0
  17. }
  18. function p5Utils__pricePrint(value, defaultValue) {
  19. return p5Utils__pricePrintFormat(value, defaultValue, '.', ',');
  20. }
  21. function p5Utils__pricePrintPL(value, defaultValue) {
  22. return p5Utils__pricePrintFormat(value, defaultValue, ',', ' ');
  23. }
  24. function p5Utils__pricePrintFormat(value, defaultValue, decPoint, thousands_sep) {
  25. if (undefined === defaultValue) defaultValue = '';
  26. if (!value && value !== 0 && value !== '0') return defaultValue;
  27. if ("number" === typeof value) {
  28. } else if ("string" === typeof value) {
  29. value = p5Utils__parseFloatOrZero(value);
  30. if (isNaN(value)) {
  31. return defaultValue;
  32. }
  33. } else {
  34. return defaultValue;
  35. }
  36. var valueParts = value.toFixed(2).split('.'),
  37. firstPart = valueParts[0],
  38. secondPart = valueParts[1],
  39. parts = [],
  40. minus = ''
  41. ;
  42. if ('-' === firstPart.substr(0, 1)) {
  43. minus = '-';
  44. firstPart = firstPart.substr(1);
  45. }
  46. var len = firstPart.length,
  47. str = firstPart,
  48. i = 0
  49. ;
  50. while (len > 3) {
  51. parts.unshift(str.substr(-3));
  52. len -= 3;
  53. str = str.substr(0, len);
  54. i++;
  55. }
  56. if (len > 0) {
  57. parts.unshift(str);
  58. }
  59. return '' + minus + parts.join(thousands_sep) + decPoint + secondPart;
  60. }
  61. function p5Utils__clearNode(node) {
  62. if (!node || !node.lastChild) return;
  63. var lastNode;
  64. while (lastNode = node.lastChild) node.removeChild(lastNode);
  65. }
  66. function p5Utils__nodeStyle(node, style) {
  67. if (!node || !style) return;
  68. for (i in style) node.style[i] = style[i];
  69. }
  70. global.p5Utils__format = p5Utils__format
  71. global.p5Utils__parseFloatOrZero = p5Utils__parseFloatOrZero
  72. global.p5Utils__pricePrint = p5Utils__pricePrint
  73. global.p5Utils__pricePrintPL = p5Utils__pricePrintPL
  74. global.p5Utils__pricePrintFormat = p5Utils__pricePrintFormat
  75. global.p5Utils__clearNode = p5Utils__clearNode
  76. global.p5Utils__nodeStyle = p5Utils__nodeStyle