Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Generating Slugs with Random Numbers #82

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions slug.go
Expand Up @@ -7,6 +7,7 @@ package slug

import (
"bytes"
"math/rand"
"regexp"
"sort"
"strconv"
Expand Down Expand Up @@ -211,3 +212,22 @@ func IsSlug(text string) bool {
}
return true
}

// MakeWithRandomNumber returns a slug generated from the provided string
// with a random 3-digit number appended at the end. Will use "en" as language
// substitution.
func MakeWithRandomNumber(s string) (slug string) {

// Create the slug from the provided string
slug = Make(s)

// Generate a random 3-digit number
rand.Seed(time.Now().UnixNano())
randomNumber := rand.Intn(900) + 100

// Append the random number to the slug
randomNumberStr := strconv.Itoa(randomNumber)
slug += "-" + randomNumberStr

return slug
}
22 changes: 22 additions & 0 deletions slug_test.go
Expand Up @@ -6,6 +6,8 @@
package slug

import (
"strconv"
"strings"
"regexp"
"testing"
)
Expand Down Expand Up @@ -644,3 +646,23 @@ func BenchmarkIsSlugLong(b *testing.B) {
IsSlug(longStr)
}
}

func TestSlugMakeWidthRandomNumber(t *testing.T) {

in := "Hello World"

result := MakeWithRandomNumber(in)

expectedPrefix := Make(in) + "-"
if !strings.HasPrefix(result, expectedPrefix) {
t.Errorf("Expected prefix %s, but got prefix %s", expectedPrefix, result)

}

randomNumberStr := strings.TrimPrefix(result, expectedPrefix)
randomNumber, err := strconv.Atoi(randomNumberStr)
if err != nil || randomNumber < 100 || randomNumber > 999 {
t.Errorf("Random number is not within the expected range: %s", randomNumberStr)
}

}