diff --git a/src/createRedirect.ts b/src/createRedirect.ts index 59a7aec..b48c610 100644 --- a/src/createRedirect.ts +++ b/src/createRedirect.ts @@ -1,15 +1,15 @@ import type { Redirects } from './index.js' +import { prependForwardSlash } from './utils.js' export function createRedirect( redirects: Redirects, redirectFrom: string[], postSlug: string ) { - // Prepend all slugs with a slash if not present - if (!postSlug.startsWith('/')) postSlug = `/${postSlug}` + postSlug = prependForwardSlash(postSlug) for (let slug of redirectFrom) { - if (!slug.startsWith('/')) slug = `/${slug}` + slug = prependForwardSlash(slug) redirects[slug] = postSlug } diff --git a/src/utils.ts b/src/utils.ts index 7f86571..bad93e4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -38,3 +38,7 @@ export async function writeJson(path: PathLike, data: T) { encoding: 'utf-8' }) } + +export function prependForwardSlash(str: string) { + return str.startsWith('/') ? str : '/' + str +} diff --git a/test/utils.test.ts b/test/utils.test.ts index dd35acf..f22f07f 100644 --- a/test/utils.test.ts +++ b/test/utils.test.ts @@ -4,6 +4,7 @@ import { getMarkdownFiles, getMarkdownFrontmatter, getSlugFromFilePath, + prependForwardSlash, writeJson } from '../src/utils' @@ -63,3 +64,29 @@ describe('writeJson', () => { expect(parsedContent).toEqual(testData) }) }) + +describe('prependForwardSlash', () => { + it('should prepend a forward slash if it does not start with one', () => { + const stringWithSlash = '/alreadyHasSlash' + const result1 = prependForwardSlash(stringWithSlash) + expect(result1).toBe('/alreadyHasSlash') + }) + + it('should prepend a forward slash', () => { + const stringWithoutSlash = 'noSlashAtStart' + const result2 = prependForwardSlash(stringWithoutSlash) + expect(result2).toBe('/noSlashAtStart') + }) + + it('should return a single forward slash if the input string is empty', () => { + const emptyString = '' + const result3 = prependForwardSlash(emptyString) + expect(result3).toBe('/') + }) + + it('should return a single forward slash if a slash is passed', () => { + const string = '/' + const result4 = prependForwardSlash(string) + expect(result4).toBe('/') + }) +})