utils.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. export function hasProperty(obj, prop) {
  2. return Object.prototype.hasOwnProperty.call(obj, prop);
  3. }
  4. export function lastItemOf(arr) {
  5. return arr[arr.length - 1];
  6. }
  7. // push only the items not included in the array
  8. export function pushUnique(arr, ...items) {
  9. items.forEach((item) => {
  10. if (arr.includes(item)) {
  11. return;
  12. }
  13. arr.push(item);
  14. });
  15. return arr;
  16. }
  17. export function stringToArray(str, separator) {
  18. // convert empty string to an empty array
  19. return str ? str.split(separator) : [];
  20. }
  21. export function isInRange(testVal, min, max) {
  22. const minOK = min === undefined || testVal >= min;
  23. const maxOK = max === undefined || testVal <= max;
  24. return minOK && maxOK;
  25. }
  26. export function limitToRange(val, min, max) {
  27. if (val < min) {
  28. return min;
  29. }
  30. if (val > max) {
  31. return max;
  32. }
  33. return val;
  34. }
  35. export function createTagRepeat(tagName, repeat, attributes = {}, index = 0, html = '') {
  36. const openTagSrc = Object.keys(attributes).reduce((src, attr) => {
  37. let val = attributes[attr];
  38. if (typeof val === 'function') {
  39. val = val(index);
  40. }
  41. return `${src} ${attr}="${val}"`;
  42. }, tagName);
  43. html += `<${openTagSrc}></${tagName}>`;
  44. const next = index + 1;
  45. return next < repeat
  46. ? createTagRepeat(tagName, repeat, attributes, next, html)
  47. : html;
  48. }
  49. // Remove the spacing surrounding tags for HTML parser not to create text nodes
  50. // before/after elements
  51. export function optimizeTemplateHTML(html) {
  52. return html.replace(/>\s+/g, '>').replace(/\s+</, '<');
  53. }