Skip to content

Instantly share code, notes, and snippets.

@safareli
Created June 18, 2021 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safareli/f4e2eaf1c9917492dd1fb7e2545b3606 to your computer and use it in GitHub Desktop.
Save safareli/f4e2eaf1c9917492dd1fb7e2545b3606 to your computer and use it in GitHub Desktop.
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