Toy parser of command line arguments. Part of the "toys" collection.
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat: Implement flag argument parsing

This covers the simplest kind of arguments that could be parsed: switch flags
that could be either `true` or `false`.

Switch flags can only be switched to `true` from the command line, their
default value is falsy (`undefined`).

Flags are also identified by a single lowercase or uppercase letter, and
uppercase flags are different from lowercase flags using the same letter.

To turn a flag on, simply pass its name preceded by a dash, like this (for the
"f" flag):

```bash
$ call program -f
```

To turn on multiple switch flags at once, one can either pass them as
individual arguments or group them up rightafter the dash, so the following
two calls are functionally identical:

```bash
$ call program -a -b -C

$ call program -abC
```

+48 -1
+1 -1
package.json
··· 8 8 "type": "module", 9 9 "main": "index.js", 10 10 "scripts": { 11 - "test": "echo \"Error: no test specified\" && exit 1" 11 + "test": "vitest" 12 12 }, 13 13 "devDependencies": { 14 14 "prettier": "3.8.3",
+16
src/pargser.ts
··· 1 + export function pargser(argv: string[]) { 2 + const parsedArguments: Record<string, unknown> = {}; 3 + const flags: string[] = []; 4 + 5 + argv.forEach((argument) => { 6 + if (argument.startsWith('-')) { 7 + flags.push(...argument.slice(1).split('')); 8 + } 9 + }); 10 + 11 + flags.forEach((flag) => { 12 + parsedArguments[flag] = true; 13 + }); 14 + 15 + return parsedArguments; 16 + }
+31
test/pargser.test.ts
··· 1 + import { describe, expect, it, test } from 'vitest'; 2 + import { pargser } from '../src/pargser.js'; 3 + 4 + describe('pargser()', () => { 5 + it('should return an object with the parsed arguments', () => { 6 + expect( 7 + pargser(['node', 'test.js', 'argument1', 'argument2', 'argument3']), 8 + ).toEqual(expect.any(Object)); 9 + }); 10 + 11 + it('should handle individual flag-type switches', () => { 12 + expect(pargser(['node', 'test.js', '-a', '-B', '-C', '-c'])).toEqual({ 13 + a: true, 14 + B: true, 15 + c: true, 16 + C: true, 17 + }); 18 + }); 19 + 20 + it('should handle grouped flag-like switches', () => { 21 + expect(pargser(['node', 'index.js', '-Lsd', '-abCD'])).toEqual({ 22 + a: true, 23 + b: true, 24 + C: true, 25 + d: true, 26 + D: true, 27 + L: true, 28 + s: true, 29 + }); 30 + }); 31 + });