Camel case and snake case: Difference between revisions

Content added Content deleted
(→‎{{header|Raku}}: really need to show expected output)
(Added Wren)
Line 91: Line 91:
c://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc
c://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc
spaces ==> spaces</pre>
spaces ==> spaces</pre>

=={{header|Wren}}==
{{libheader|Wren-str}}
{{libheader|Wren-fmt}}
Well, I'm not entirely sure what I'm doing here as a result of space and hyphen being treated as equivalent to underscore but, in the case of the 'to snake' conversion:

1. I've retained any hyphens in the result string but replaced spaces with underscores as it says that white space is not permitted as part of the variable name.

2. I've assumed that an underscore should not be added if the previous character was already a separator.
<lang ecmascript>import "./str" for Char
import "/fmt" for Fmt

var toCamel = Fn.new { |snake|
snake = snake.trim()
var camel = ""
var underscore = false
for (c in snake) {
if ("_- ".contains(c)) {
underscore = true
} else if (underscore) {
camel = camel + Char.upper(c)
underscore = false
} else {
camel = camel + c
}
}
return camel
}

var toSnake = Fn.new { |camel|
camel = camel.trim().replace(" ", "_") // we don't want any spaces in the result
var snake = ""
var first = true
for (c in camel) {
if (first) {
snake = snake + c
first = false
} else if (!first && Char.isUpper(c)) {
if (snake[-1] == "_" || snake[-1] == "-") {
snake = snake + Char.lower(c)
} else {
snake = snake + "_" + Char.lower(c)
}
} else {
snake = snake + c
}
}
return snake
}

var tests = [
"snakeCase", "snake_case", "variable_10_case", "variable10Case", "ɛrgo rE tHis",
"hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces "
]

System.print(" === to_snake_case ===")
for (camel in tests) {
Fmt.print("$33s -> $s", camel, toSnake.call(camel))
}

System.print("\n === toCamelCase ===")
for (snake in tests) {
Fmt.print("$33s -> $s", snake, toCamel.call(snake))
}</lang>

{{out}}
<pre>
=== to_snake_case ===
snakeCase -> snake_case
snake_case -> snake_case
variable_10_case -> variable_10_case
variable10Case -> variable10_case
ɛrgo rE tHis -> ɛrgo_r_e_t_his
hurry-up-joe! -> hurry-up-joe!
c://my-docs/happy_Flag-Day/12.doc -> c://my-docs/happy_flag-day/12.doc
spaces -> spaces

=== toCamelCase ===
snakeCase -> snakeCase
snake_case -> snakeCase
variable_10_case -> variable10Case
variable10Case -> variable10Case
ɛrgo rE tHis -> ɛrgoRETHis
hurry-up-joe! -> hurryUpJoe!
c://my-docs/happy_Flag-Day/12.doc -> c://myDocs/happyFlagDay/12.doc
spaces -> spaces
</pre>