Camel case and snake case: Difference between revisions

Add Factor
(Added Algol 68)
(Add Factor)
Line 170:
c://my-docs/happy_Flag-Day/12.doc -> c://my-docs/happy-flag-day/12.doc
spaces -> spaces
</pre>
 
=={{header|Factor}}==
In my interpretation of the task, leading/trailing whitespace should be ignored, not trimmed. And non-trailing whitespace should be dealt with the same way as underscores and hyphens. Although the task says nothing about numbers, I chose to treat letter->number and number->letter transitions the same way as lower->upper for the sake of converting to snake case.
{{works with|Factor|0.99 2021-06-02}}
<lang factor>USING: formatting kernel math regexp sequences splitting
splitting.extras unicode ;
 
! ignore leading/trailing whitespace
: preserve ( str quot -- newstr )
[ [ blank? ] split-head [ blank? ] split-tail swap ] dip
call glue ; inline
 
: >snake ( str -- newstr )
[
R/ (\p{lower}\p{upper}|\d\p{alpha}|\p{alpha}\d)/
[ 1 cut >lower "_" glue ] re-replace-with
R/ [\s-]/ "_" re-replace
] preserve ;
 
: capitalize ( str -- newstr ) 1 short cut swap >upper prepend ;
 
: >camel ( str -- newstr )
[
"\s_-" split harvest
dup length 1 > [ 1 cut [ capitalize ] map append ] when
"" join
] preserve ;
 
: test ( str -- )
dup >snake over dup >camel
"%u >snake %u\n%u >camel %u\n" printf ;
 
{
"snakeCase" "snake_case" "variable_10_case" "variable10Case"
"ɛrgo rE tHis" "hurry-up-joe!"
"c://my-docs/happy_Flag-Day/12.doc" " spaces "
" internal space "
} [ test ] each</lang>
{{out}}
<pre>
"snakeCase" >snake "snake_case"
"snakeCase" >camel "snakeCase"
"snake_case" >snake "snake_case"
"snake_case" >camel "snakeCase"
"variable_10_case" >snake "variable_10_case"
"variable_10_case" >camel "variable10Case"
"variable10Case" >snake "variable_10_case"
"variable10Case" >camel "variable10Case"
"ɛrgo rE tHis" >snake "ɛrgo_r_e_t_his"
"ɛrgo rE tHis" >camel "ɛrgoRETHis"
"hurry-up-joe!" >snake "hurry_up_joe!"
"hurry-up-joe!" >camel "hurryUpJoe!"
"c://my-docs/happy_Flag-Day/12.doc" >snake "c://my_docs/happy_Flag_Day/12.doc"
"c://my-docs/happy_Flag-Day/12.doc" >camel "c://myDocs/happyFlagDay/12.doc"
" spaces " >snake " spaces "
" spaces " >camel " spaces "
" internal space " >snake " internal_space "
" internal space " >camel " internalSpace "
</pre>
 
1,808

edits