Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use SafeMap rather than plain object hash for internal results #65

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const {
ArrayPrototypeSlice,
ArrayPrototypeSplice,
ArrayPrototypePush,
ObjectFromEntries,
ObjectHasOwn,
SafeMap,
StringPrototypeCharAt,
StringPrototypeIncludes,
StringPrototypeIndexOf,
Expand Down Expand Up @@ -58,22 +60,20 @@ function storeOptionValue(parseOptions, option, value, result) {
ArrayPrototypeIncludes(parseOptions.multiples, option);

// Flags
result.flags[option] = true;
result.safeFlags.set(option, true);

// Values
if (multiple) {
// Always store value in array, including for flags.
// result.values[option] starts out not present,
// first value is added as new array [newValue],
// subsequent values are pushed to existing array.
// Create array when adding first value, undefined until then.
const usedAsFlag = value === undefined;
const newValue = usedAsFlag ? true : value;
if (result.values[option] !== undefined)
ArrayPrototypePush(result.values[option], newValue);
else
result.values[option] = [newValue];
if (!result.safeValues.get(option)) {
result.safeValues.set(option, []);
}
ArrayPrototypePush(result.safeValues.get(option), newValue);
} else {
result.values[option] = value;
result.safeValues.set(option, value);
}
}

Expand All @@ -90,8 +90,8 @@ const parseArgs = (
}

const result = {
flags: {},
values: {},
safeFlags: new SafeMap(),
safeValues: new SafeMap(),
positionals: []
};

Expand All @@ -112,7 +112,7 @@ const parseArgs = (
result.positionals,
ArrayPrototypeSlice(argv, ++pos)
);
return result;
break; // Finished processing argv, leave while loop
} else if (StringPrototypeCharAt(arg, 1) !== '-') {
// Look for shortcodes: -fXzy and expand them to -f -X -z -y:
if (arg.length > 2) {
Expand Down Expand Up @@ -172,7 +172,13 @@ const parseArgs = (
pos++;
}

return result;
// Copy back from "safe" objects to vanilla objects
const clientResult = {
flags: ObjectFromEntries(result.safeFlags),
values: ObjectFromEntries(result.safeValues),
positionals: result.positionals
};
return clientResult;
};

module.exports = {
Expand Down