2
\$\begingroup\$

I am writing a function that I would use to handle parameters with options for use later in another project.

A sample input would be similar to this:

foo bar --baz con str --w=1920 --h=1080

From the example above I would expect foo and bar to be not part of any flag and baz would contain con and str and w with the value of 1920 and h with 1080:

foo
bar
baz = [con, str]
w   = 1920
h   = 1080

This getFlags function would take a string and perform the "flag" logic that I had in mind.

const getFlags = (str) => {
  const prefix = '--';

  const strArray = str
    .trim()
    .replaceAll(/\s+/ig, ' ')
    .split(' ');

  let flagArray = {
    _noFlag: {
      values: [],
    },
  };

  let lastArg = '';
  strArray.forEach((arg) => {
    if (arg.startsWith(prefix) && arg.length > prefix.length) {
      noPrefixFlag = arg.slice(prefix.length);

      if (noPrefixFlag.includes('=')) {
        const pair = noPrefixFlag.split('=');
        flagArray[pair[0]] = {
          values: [pair[1]],
        };
        lastArg = '';
      } else {
        lastArg = noPrefixFlag;
        flagArray[lastArg] = {
          values: [],
        };
      }

    } else if (lastArg) {
      flagArray[lastArg].values.push(arg);
    } else {
      flagArray._noFlag.values.push(arg);
    }
  });

  return flagArray;
};

It works as I expect it, but I feel like this function can be improved.

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.