utils.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*!
  2. * lunr.utils
  3. * Copyright (C) @YEAR Oliver Nightingale
  4. */
  5. /**
  6. * A namespace containing utils for the rest of the lunr library
  7. * @namespace lunr.utils
  8. */
  9. lunr.utils = {}
  10. /**
  11. * Print a warning message to the console.
  12. *
  13. * @param {String} message The message to be printed.
  14. * @memberOf lunr.utils
  15. * @function
  16. */
  17. lunr.utils.warn = (function (global) {
  18. /* eslint-disable no-console */
  19. return function (message) {
  20. if (global.console && console.warn) {
  21. console.warn(message)
  22. }
  23. }
  24. /* eslint-enable no-console */
  25. })(this)
  26. /**
  27. * Convert an object to a string.
  28. *
  29. * In the case of `null` and `undefined` the function returns
  30. * the empty string, in all other cases the result of calling
  31. * `toString` on the passed object is returned.
  32. *
  33. * @param {Any} obj The object to convert to a string.
  34. * @return {String} string representation of the passed object.
  35. * @memberOf lunr.utils
  36. */
  37. lunr.utils.asString = function (obj) {
  38. if (obj === void 0 || obj === null) {
  39. return ""
  40. } else {
  41. return obj.toString()
  42. }
  43. }
  44. /**
  45. * Clones an object.
  46. *
  47. * Will create a copy of an existing object such that any mutations
  48. * on the copy cannot affect the original.
  49. *
  50. * Only shallow objects are supported, passing a nested object to this
  51. * function will cause a TypeError.
  52. *
  53. * Objects with primitives, and arrays of primitives are supported.
  54. *
  55. * @param {Object} obj The object to clone.
  56. * @return {Object} a clone of the passed object.
  57. * @throws {TypeError} when a nested object is passed.
  58. * @memberOf Utils
  59. */
  60. lunr.utils.clone = function (obj) {
  61. if (obj === null || obj === undefined) {
  62. return obj
  63. }
  64. var clone = Object.create(null),
  65. keys = Object.keys(obj)
  66. for (var i = 0; i < keys.length; i++) {
  67. var key = keys[i],
  68. val = obj[key]
  69. if (Array.isArray(val)) {
  70. clone[key] = val.slice()
  71. continue
  72. }
  73. if (typeof val === 'string' ||
  74. typeof val === 'number' ||
  75. typeof val === 'boolean') {
  76. clone[key] = val
  77. continue
  78. }
  79. throw new TypeError("clone is not deep and does not support nested objects")
  80. }
  81. return clone
  82. }