helpers.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. function isObject(value) {
  2. return Object.prototype.toString.call(value) === '[object Object]';
  3. }
  4. function isNumber(value) {
  5. return typeof value === 'number' && isFinite(value);
  6. }
  7. function interpolate(string, object) {
  8. var pattern = /(#\{(.*?)\})/g;
  9. return string.replace(pattern, function () {
  10. var name = arguments[2];
  11. var value = object[name];
  12. if (isNumber(value)) {
  13. value = value.toString();
  14. } else if (isObject(value)) {
  15. try {
  16. value = JSON.stringify(value);
  17. } catch (e) {
  18. console.error("Stringifying object (likely a circular structure) failed.");
  19. }
  20. }
  21. return typeof value === 'string' ? value : '';
  22. });
  23. }
  24. var enumerables = ['valueOf', 'toLocaleString', 'toString', 'constructor'];
  25. function apply(object, config, defaults) {
  26. if (defaults) {
  27. apply(object, defaults);
  28. }
  29. if (object && config && typeof config === 'object') {
  30. var i, j, k;
  31. for (i in config) {
  32. object[i] = config[i];
  33. }
  34. if (enumerables) {
  35. for (j = enumerables.length; j--;) {
  36. k = enumerables[j];
  37. if (config.hasOwnProperty(k)) {
  38. object[k] = config[k];
  39. }
  40. }
  41. }
  42. }
  43. return object;
  44. }
  45. module.exports = {
  46. isObject: isObject,
  47. isNumber: isNumber,
  48. interpolate: interpolate,
  49. apply: apply
  50. };