Skip to content

Commit

Permalink
Merge pull request #5 from eveningkid/fix-args-separation-regex
Browse files Browse the repository at this point in the history
fix: args separation regex
  • Loading branch information
eveningkid authored May 7, 2021
2 parents 4ac82e8 + 2fc0279 commit ca87022
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 43 deletions.
7 changes: 1 addition & 6 deletions dist/parse.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "args-parser",
"version": "1.0.1",
"version": "1.1.0",
"description": "Straight-forward node.js arguments parser",
"main": "parse.js",
"main": "dist/parse.min.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
Expand Down
70 changes: 35 additions & 35 deletions parse.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,45 @@
"use strict";
'use strict';

/*
Straight-forward node.js arguments parser
Author: eveningkid
License: Apache-2.0
*/

function Parse (argv) {
// Removing node/bin and called script name
argv = argv.slice(2);

// Returned object
var args = {};
var argName, argValue;

// For each argument
argv.forEach(function (arg, index) {
// Seperate argument, for a key/value return
arg = arg.split('=');

// Retrieve the argument name
argName = arg[0];
// Remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
}
// Associate defined value or initialize it to "true" state
argValue = (arg.length === 2)
? parseFloat(arg[1]).toString() === arg[1] // check if argument is valid number
? +arg[1]
: arg[1]
: true;

// Finally add the argument to the args set
args[argName] = argValue;
});

return args;
const ARGUMENT_SEPARATION_REGEX = /([^=\s]+)=?([^\s]*)/;

function Parse(argv) {
// Removing node/bin and called script name
argv = argv.slice(2);

const parsedArgs = {};
let argName, argValue;

argv.forEach(function (arg) {
// Separate argument for a key/value return
arg = arg.match(ARGUMENT_SEPARATION_REGEX);
arg.splice(0, 1);

// Retrieve the argument name
argName = arg[0];

// Remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
}

// Parse argument value or set it to `true` if empty
argValue =
arg[1] !== ''
? parseFloat(arg[1]).toString() === arg[1]
? +arg[1]
: arg[1]
: true;

parsedArgs[argName] = argValue;
});

return parsedArgs;
}

module.exports = Parse;

0 comments on commit ca87022

Please sign in to comment.