wharf icon indicating copy to clipboard operation
wharf copied to clipboard

How to deal with sequential capitals?

Open theronic opened this issue 10 years ago • 4 comments

Given a string "IMEINumber", I want to get out "imei-number", but camel->dash expects title case:

(camel->dash "IMEINumber")
=> "I-M-E-I-Number"

Which is expected behaviour, as per the tests. Is there a trick to transform the sequential "IMEINumber" to "ImeiNumber" to get the desired output?

theronic avatar Nov 12 '14 07:11 theronic

I've made some changes, and now it doesn't split the all-capital tokens.

wharf.core> (camel->hyphen "IMEINumber")
"IMEI-Number"

jeremyheiler avatar Nov 15 '14 03:11 jeremyheiler

When converting

(camel->underscore "XMLsettingsAndOtherThings") "XM_Lsettings_And_Other_Things"

Is there a way to convert it to "xml_settings_and_other_things" or "XML_Settings_And_Other_Things" (looking to get the prior)

Perhaps insert underscores on case change from multiple consecutive CAPS?

sbitteker avatar Feb 07 '15 01:02 sbitteker

How often do you have this case? I'm not sure I want to support it out of the box. However, you could handle it manually.

(defn camel->underscore*
  [s]
  (let [x (camel->underscore s)]
    (if (.startsWith x "xml")
      (str (subs x 0 3) "_" (subs x 3))
      x)))

Something more generic would involve some and a sequence of prefixes.

Or you could use split-camel-case to get the tokens if the special prefix isn't at the beginning.

Hope this helps.

jeremyheiler avatar Feb 07 '15 01:02 jeremyheiler

Granted this is probably a special case for most and it's through away code for me. I'll just do something like this...

(defn camel->underscore*
  "convert CamelCase to underscore, if prefix found separate on prefix."
  [s prefix]
  (let [pre-found (.startsWith s prefix)]
    (if pre-found
      (let [pre-len (count prefix)
            modified (str
                       (subs s 0 pre-len)
                       (.toUpperCase (subs s pre-len (inc pre-len)))
                       (subs s (+ pre-len 1)))]
        (camel->underscore modified))
      (camel->underscore s))))
 (camel->underscore* "XMLsettingsAndOtherThings" "XML")
"XML_Settings_And_Other_Things"
(camel->underscore "XMLsettingsAndOtherThings")
"XM_Lsettings_And_Other_Things"

sbitteker avatar Feb 07 '15 02:02 sbitteker