Skip to content

Commit

Permalink
fix: firstCapital=true not working in camelCase() function
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexMesser committed Apr 6, 2023
1 parent a11809e commit f1330ad
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 9 deletions.
13 changes: 5 additions & 8 deletions src/util/StringUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@ import shajs from "sha.js"
* @see http://stackoverflow.com/questions/2970525/converting-any-string-into-camel-case
*/
export function camelCase(str: string, firstCapital: boolean = false): string {
return str.replace(
/^([A-Z])|[\s-_](\w)/g,
function (match, p1, p2, offset) {
if (firstCapital === true && offset === 0) return p1
if (p2) return p2.toUpperCase()
return p1.toLowerCase()
},
)
if (firstCapital) str = " " + str
return str.replace(/^([A-Z])|[\s-_](\w)/g, function (match, p1, p2) {
if (p2) return p2.toUpperCase()
return p1.toLowerCase()
})
}

/**
Expand Down
44 changes: 43 additions & 1 deletion test/functional/util/StringUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from "chai"
import { snakeCase } from "../../../src/util/StringUtils"
import { camelCase, snakeCase } from "../../../src/util/StringUtils"

describe("StringUtils", () => {
describe("snakeCase", () => {
Expand Down Expand Up @@ -77,4 +77,46 @@ describe("StringUtils", () => {
}
})
})

describe("camelCase", () => {
it("should convert snakecase to camelcase", () => {
const input = "camel_case_string_here"
const expected = "camelCaseStringHere"
const actual = camelCase(input)

expect(actual).to.be.equal(expected, `Failed for Input: ${input}`)
})

it("should convert with first capital letter", () => {
const input = "camel_case_string_here"
const expected = "CamelCaseStringHere"
const actual = camelCase(input, true)

expect(actual).to.be.equal(expected, `Failed for Input: ${input}`)
})

it("should correctly convert repeating snakecase groups", () => {
const input = "option_a_or_b_or_c"
const expected = "optionAOrBOrC"
const actual = camelCase(input)

expect(actual).to.be.equal(expected, `Failed for Input: ${input}`)
})

it("should do nothing with strings that are already camelcase", () => {
const expected1 = "camelCaseStringHere"
expect(camelCase(expected1)).to.be.equal(expected1, expected1)

const expected2 = "CamelCaseStringHere"
expect(camelCase(expected2, true)).to.be.equal(expected2, expected2)
})

it("should correctly convert strings with numbers", () => {
const input = "device1_status"
const expected = "device1Status"
const actual = camelCase(input)

expect(actual).to.be.equal(expected, `Failed for Input: ${input}`)
})
})
})

0 comments on commit f1330ad

Please sign in to comment.