Skip to content

Add .asStringRecord #174

Open
Open
@hongkongkiwi

Description

It would be great to have a feature which produces a Record<string, string> from a set of strings.

For example if I have an environment variable like this:
"a=1,b=2,c=3" or string quoted ""a"="1","b"="2""

Right now, I can do it with this code:

  const envMetadata = Array.from(env.get("METADATA").default([]).asSet()).reduce((acc: Record<string, string>, metadata: string) => {
    const [key, value = ""] = metadata.split("=");
    acc[key] = value;
    return acc;
  }, {});

Or to handle the string quoted case:

  const envMetadata = Array.from(env.get("METADATA").default([]).asSet()).reduce((acc: Record<string, string>, metadata: string) => {
    const [key, value = ""] = metadata.split("=");
    acc[key.replace(/^["']|["']$/g, "")] = value.replace(/^["']|["']$/g, "");
    return acc;
  }, {});

It would be super awesome if I could just have a asStringRecord(",", "="), then the code would be much cleaner.

So the proposal is to add:

asStringRecord(recordDelimiter: string = ",", itemSeperator: string = "=")

This is quite neat as you could also do something like asIntRecord etc. And it's quite flexible as you can set the delimiter to say newline for records.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions