index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const regex = require('./regex.js')
  2. module.exports = BananaSlug
  3. const own = Object.hasOwnProperty
  4. function BananaSlug () {
  5. const self = this
  6. if (!(self instanceof BananaSlug)) return new BananaSlug()
  7. self.reset()
  8. }
  9. /**
  10. * Generate a unique slug.
  11. * @param {string} value String of text to slugify
  12. * @param {boolean} [false] Keep the current case, otherwise make all lowercase
  13. * @return {string} A unique slug string
  14. */
  15. BananaSlug.prototype.slug = function (value, maintainCase) {
  16. const self = this
  17. let slug = slugger(value, maintainCase === true)
  18. const originalSlug = slug
  19. while (own.call(self.occurrences, slug)) {
  20. self.occurrences[originalSlug]++
  21. slug = originalSlug + '-' + self.occurrences[originalSlug]
  22. }
  23. self.occurrences[slug] = 0
  24. return slug
  25. }
  26. /**
  27. * Reset - Forget all previous slugs
  28. * @return void
  29. */
  30. BananaSlug.prototype.reset = function () {
  31. this.occurrences = Object.create(null)
  32. }
  33. function slugger (string, maintainCase) {
  34. if (typeof string !== 'string') return ''
  35. if (!maintainCase) string = string.toLowerCase()
  36. return string.replace(regex, '').replace(/ /g, '-')
  37. }
  38. BananaSlug.slug = slugger