Skip to content

Commit

Permalink
Merge pull request #1 from wooorm/bug/fix-empty-slug
Browse files Browse the repository at this point in the history
Fix bug for multiple empty slugs
  • Loading branch information
Flet committed Jan 23, 2016
2 parents 0f2437a + 7d98799 commit 9610954
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
25 changes: 12 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function BananaSlug () {
var self = this
if (!(self instanceof BananaSlug)) return new BananaSlug()

self.slugs = []
self.reset()
}

/**
Expand All @@ -15,30 +15,29 @@ function BananaSlug () {
BananaSlug.prototype.slug = function (value) {
var self = this
var slug = slugger(value)
if (self.slugs.some(slugExists)) {
var suffix = '-' + self.slugs.filter(slugMatches).length
slug = slug + suffix
var occurrences = self.occurrences[slug]

if (self.occurrences.hasOwnProperty(slug)) {
occurrences++
} else {
occurrences = 0
}

self.slugs.push(slug)
return slug
self.occurrences[slug] = occurrences

function slugMatches (s) {
var slugMatch = new RegExp(slug + '(-[0-9])*$')
return slugMatch.test(s)
if (occurrences) {
slug = slug + '-' + occurrences
}

function slugExists (s) {
return s === slug
}
return slug
}

/**
* Reset - Forget all previous slugs
* @return void
*/
BananaSlug.prototype.reset = function () {
this.slugs = []
this.occurrences = {}
}

var whitespace = /\s/g
Expand Down
25 changes: 25 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,31 @@ var testCases = [
text: 'exchange.bind_headers(exchange, routing [, bindCallback])',
slug: 'exchangebind_headersexchange-routing--bindcallback'
},
{
mesg: 'empty',
text: '',
slug: ''
},
{
mesg: 'a space',
text: ' ',
slug: '-1'
},
{
mesg: 'initial space',
text: ' initial space',
slug: 'initial-space'
},
{
mesg: 'final space',
text: 'final space ',
slug: 'final-space'
},
{
mesg: 'deals with prototype properties',
text: 'length',
slug: 'length'
},
{
mesg: 'deals with duplicates correctly',
text: 'duplicate',
Expand Down

0 comments on commit 9610954

Please sign in to comment.