jeremyheiler / wharf

A Clojure library for transforming map keys.
34 stars 9 forks source link

How to deal with sequential capitals? #5

Open theronic opened 10 years ago

theronic commented 10 years ago

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?

jeremyheiler commented 10 years ago

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

wharf.core> (camel->hyphen "IMEINumber")
"IMEI-Number"
sbitteker commented 9 years ago

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?

jeremyheiler commented 9 years ago

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.

sbitteker commented 9 years ago

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"