Implementing kebab-case to camelCase in Nix

How would you implement a string transformation function that’ll mutate a kebab-case string to a camelCase string in Nix?

Here’s what I have:

default.nix:

let
  lib = builtins // (import <nixpkgs> { }).lib;

  mutFirstChar = f: s:
    let
      c = lib.stringToCharacters s;
    in
    lib.concatStrings ([ (f (lib.head c)) ] ++ (lib.sublist 1 (lib.length c) c));

  kebabToCamel = s: mutFirstChar lib.toLower (lib.concatStrings
    (lib.map
      (c: mutFirstChar lib.toUpper c)
      (lib.splitString "-" s)));
in
{ inherit kebabToCamel; }

REPL:

$ nix repl --file default.nix
Added 1 variables.
nix-repl> kebabToCamel "some-kebab-string"
"someKebabString"

Any cleaner solutions? Thanks in advance!

Typically, implementations are toCamelCase or toKebabCase, regardless of what case the input is.

I suggest making an RFC for adding case conversion functions to nixpkgs. Perhaps a rough draft to gain general yes/no.

1 Like

It was requested to cover this in this week’s Nix Hour, which we did in the beginning, ending up just changing the code slightly, ending up with this :smile:

Definitely no need to make an RFC for something like this! Just a PR is sufficient, new functions often get added to lib like that. The most important thing to follow the lib’s PR guidelines :wink:

7 Likes