diff --git a/spec/stdlib/underscore-extensions-spec.coffee b/spec/stdlib/underscore-extensions-spec.coffee index 1ad7130a8..5ae310cde 100644 --- a/spec/stdlib/underscore-extensions-spec.coffee +++ b/spec/stdlib/underscore-extensions-spec.coffee @@ -30,3 +30,27 @@ describe "underscore extensions", -> expect(_.endsWith("test.txt", ".txt2")).toBeFalsy() expect(_.endsWith("test.txt", ".tx")).toBeFalsy() expect(_.endsWith("test.txt", "test")).toBeFalsy() + + describe "camelize(string)", -> + it "converts `string` to camel case", -> + expect(_.camelize("corey_dale_johnson")).toBe "coreyDaleJohnson" + expect(_.camelize("corey-dale-johnson")).toBe "coreyDaleJohnson" + expect(_.camelize("corey_dale-johnson")).toBe "coreyDaleJohnson" + expect(_.camelize("coreyDaleJohnson")).toBe "coreyDaleJohnson" + expect(_.camelize("CoreyDaleJohnson")).toBe "CoreyDaleJohnson" + + describe "dasherize(string)", -> + it "converts `string` to use dashes", -> + expect(_.dasherize("corey_dale_johnson")).toBe "corey-dale-johnson" + expect(_.dasherize("coreyDaleJohnson")).toBe "corey-dale-johnson" + expect(_.dasherize("CoreyDaleJohnson")).toBe "corey-dale-johnson" + expect(_.dasherize("corey-dale-johnson")).toBe "corey-dale-johnson" + + describe "underscore(string)", -> + it "converts `string` to use underscores", -> + expect(_.underscore("corey-dale-johnson")).toBe "corey_dale_johnson" + expect(_.underscore("coreyDaleJohnson")).toBe "corey_dale_johnson" + expect(_.underscore("CoreyDaleJohnson")).toBe "corey_dale_johnson" + expect(_.underscore("corey_dale_johnson")).toBe "corey_dale_johnson" + + diff --git a/src/stdlib/underscore-extensions.coffee b/src/stdlib/underscore-extensions.coffee index be1245349..df5865b24 100644 --- a/src/stdlib/underscore-extensions.coffee +++ b/src/stdlib/underscore-extensions.coffee @@ -69,6 +69,25 @@ _.mixin else "#{count} #{plural}" + camelize: (string) -> + string.replace /[_-]+(\w)/g, (m) -> m[1].toUpperCase() + + dasherize: (string) -> + string = string[0].toLowerCase() + string[1..] + string.replace /([A-Z])|(_)/g, (m, letter, underscore) -> + if letter + "-" + letter.toLowerCase() + else + "-" + + underscore: (string) -> + string = string[0].toLowerCase() + string[1..] + string.replace /([A-Z])|(-)/g, (m, letter, dash) -> + if letter + "_" + letter.toLowerCase() + else + "_" + losslessInvert: (hash) -> inverted = {} for key, value of hash