Created
June 18, 2021 17:40
-
-
Save safareli/f4e2eaf1c9917492dd1fb7e2545b3606 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pascalCaseToKebabCase = (x: string) => | |
x.replace( | |
/[A-Z]/g, | |
(match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase() | |
); | |
const kebabCaseToPascalCase = (x: string) => | |
x | |
.replace(/(^[a-z])|(-[a-z])/g, (match) => match.toUpperCase()) | |
.replace(/-/g, ""); | |
function characterArbitrary( | |
min: number, | |
max: number, | |
mapToCode: (v: number) => number | |
) { | |
return fc.integer(min, max).map((n) => String.fromCodePoint(mapToCode(n))); | |
} | |
const genAlphaUpperCaseChar = characterArbitrary(0, 25, (v: number) => { | |
return v + 65; // A-Z | |
}); | |
const genAlphaLowerCaseChar = characterArbitrary(0, 25, (v) => { | |
return v + 97; // a-z | |
}); | |
const genPascalCase = fc | |
.tuple( | |
genAlphaUpperCaseChar, | |
fc.stringOf( | |
fc.frequency( | |
{ | |
arbitrary: genAlphaLowerCaseChar, | |
weight: 10, | |
}, | |
{ | |
arbitrary: genAlphaUpperCaseChar, | |
weight: 1, | |
} | |
), | |
{ | |
minLength: 0, | |
maxLength: 30, | |
} | |
) | |
) | |
.map((s) => s.join("")); | |
const genKebabCase = fc | |
.tuple( | |
genAlphaLowerCaseChar, | |
fc.stringOf( | |
fc.frequency( | |
{ | |
arbitrary: genAlphaLowerCaseChar, | |
weight: 10, | |
}, | |
{ | |
arbitrary: fc.constant("-"), | |
weight: 1, | |
} | |
), | |
{ | |
minLength: 0, | |
maxLength: 30, | |
} | |
), | |
genAlphaLowerCaseChar | |
) | |
.map((s) => s.join("").replace(/--+/g, "-")); | |
describe("PascalCase << >> kebab-case", () => { | |
it("PascalCase to kebab-case to PascalCase = identity", () => { | |
fc.assert( | |
fc.property(genPascalCase, (strPascalCase) => { | |
expect( | |
kebabCaseToPascalCase(pascalCaseToKebabCase(strPascalCase)) | |
).toBe(strPascalCase); | |
}), | |
{ examples: [["ZendeskChat"], ["Recharge"]] } | |
); | |
}); | |
it("kebab-case to PascalCase to kebab-case = identity", () => { | |
fc.assert( | |
fc.property(genKebabCase, (strKebabCase) => { | |
expect(pascalCaseToKebabCase(kebabCaseToPascalCase(strKebabCase))).toBe( | |
strKebabCase | |
); | |
}), | |
{ examples: [["zendesk-chat"], ["recharge"]] } | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment