From b95006e5557fb507ca24921ce6bf82776eff82e7 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Fr=C3=A9d=C3=A9ric=20Vachon?= Date: Fri, 11 Jul 2014 00:17:47 -0400 Subject: [PATCH] lib/standard: Added to_snake_case and to_camel_case to string.nit MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Frédéric Vachon --- lib/standard/string.nit | 73 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/lib/standard/string.nit b/lib/standard/string.nit index eea52be..74ec7a2 100644 --- a/lib/standard/string.nit +++ b/lib/standard/string.nit @@ -640,6 +640,79 @@ abstract class String # # assert "Hello World!".to_lower == "hello world!" fun to_lower : SELFTYPE is abstract + + # Takes a camel case `self` and converts it to snake case + # + # assert "randomMethodId".to_snake_case == "random_method_id" + # + # If `self` is upper, it is returned unchanged + # + # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID" + # + # If the identifier is prefixed by an underscore, the underscore is ignored + # + # assert "_privateField".to_snake_case == "_private_field" + fun to_snake_case: SELFTYPE + do + if self.is_upper then return self + + var new_str = new FlatBuffer.with_capacity(self.length) + var is_first_char = true + + for char in self.chars do + if is_first_char then + new_str.add(char.to_lower) + is_first_char = false + else if char.is_upper then + new_str.add('_') + new_str.add(char.to_lower) + else + new_str.add(char) + end + end + + return new_str.to_s + end + + # Takes a snake case `self` and converts it to camel case + # + # assert "random_method_id".to_camel_case == "randomMethodId" + # + # If the identifier is prefixed by an underscore, the underscore is ignored + # + # assert "_private_field".to_camel_case == "_privateField" + # + # If `self` is upper, it is returned unchanged + # + # assert "RANDOM_ID".to_camel_case == "RANDOM_ID" + # + # If there are several consecutive underscores, they are considered as a single one + # + # assert "random__method_id".to_camel_case == "randomMethodId" + fun to_camel_case: SELFTYPE + do + if self.is_upper then return self + + var new_str = new FlatBuffer + var is_first_char = true + var follows_us = false + + for char in self.chars do + if is_first_char then + new_str.add(char) + is_first_char = false + else if char == '_' then + follows_us = true + else if follows_us then + new_str.add(char.to_upper) + follows_us = false + else + new_str.add(char) + end + end + + return new_str.to_s + end end private class FlatSubstringsIter -- 1.7.9.5