lib.strings: init toCamelCase (#402372)

authored by Johannes Kirschbauer and committed by GitHub b7d438b8 d78486f4

Changed files
+80
lib
+1
lib/default.nix
··· 345 345 upperChars 346 346 toLower 347 347 toUpper 348 + toCamelCase 348 349 toSentenceCase 349 350 addContextFrom 350 351 splitString
+57
lib/strings.nix
··· 1501 1501 ); 1502 1502 1503 1503 /** 1504 + Converts a string to camelCase. Handles snake_case, PascalCase, 1505 + kebab-case strings as well as strings delimited by spaces. 1506 + 1507 + # Inputs 1508 + 1509 + `string` 1510 + : The string to convert to camelCase 1511 + 1512 + # Type 1513 + 1514 + ``` 1515 + toCamelCase :: string -> string 1516 + ``` 1517 + 1518 + # Examples 1519 + :::{.example} 1520 + ## `lib.strings.toCamelCase` usage example 1521 + 1522 + ```nix 1523 + toCamelCase "hello-world" 1524 + => "helloWorld" 1525 + toCamelCase "hello_world" 1526 + => "helloWorld" 1527 + toCamelCase "hello world" 1528 + => "helloWorld" 1529 + toCamelCase "HelloWorld" 1530 + => "helloWorld" 1531 + ``` 1532 + 1533 + ::: 1534 + */ 1535 + toCamelCase = 1536 + str: 1537 + lib.throwIfNot (isString str) "toCamelCase does only accepts string values, but got ${typeOf str}" ( 1538 + let 1539 + separators = splitStringBy ( 1540 + prev: curr: 1541 + elem curr [ 1542 + "-" 1543 + "_" 1544 + " " 1545 + ] 1546 + ) false str; 1547 + 1548 + parts = lib.flatten ( 1549 + map (splitStringBy ( 1550 + prev: curr: match "[a-z]" prev != null && match "[A-Z]" curr != null 1551 + ) true) separators 1552 + ); 1553 + 1554 + first = if length parts > 0 then toLower (head parts) else ""; 1555 + rest = if length parts > 1 then map toSentenceCase (tail parts) else [ ]; 1556 + in 1557 + concatStrings (map (addContextFrom str) ([ first ] ++ rest)) 1558 + ); 1559 + 1560 + /** 1504 1561 Appends string context from string like object `src` to `target`. 1505 1562 1506 1563 :::{.warning}
+22
lib/tests/misc.nix
··· 969 969 970 970 testToSentenceCasePath = testingThrow (strings.toSentenceCase ./.); 971 971 972 + testToCamelCase = { 973 + expr = strings.toCamelCase "hello world"; 974 + expected = "helloWorld"; 975 + }; 976 + 977 + testToCamelCaseFromKebab = { 978 + expr = strings.toCamelCase "hello-world"; 979 + expected = "helloWorld"; 980 + }; 981 + 982 + testToCamelCaseFromSnake = { 983 + expr = strings.toCamelCase "hello_world"; 984 + expected = "helloWorld"; 985 + }; 986 + 987 + testToCamelCaseFromPascal = { 988 + expr = strings.toCamelCase "HelloWorld"; 989 + expected = "helloWorld"; 990 + }; 991 + 992 + testToCamelCasePath = testingThrow (strings.toCamelCase ./.); 993 + 972 994 testToInt = testAllTrue [ 973 995 # Naive 974 996 (123 == toInt "123")