Created
December 4, 2023 14:09
-
-
Save nyteshade/dd5d17a11e2eecd7ac677b835f33a8e3 to your computer and use it in GitHub Desktop.
Quick smaller version jq for JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const { readFile } = require('fs/promises') | |
const { format, parse } = require('path') | |
const expected = { attending: v => /true|1|yes/i.exec(v) ? true : false } | |
const { interpreter, executable, args, flags } = processArgsForFlags(process.argv, expected) | |
console.log(interpreter) | |
console.log(executable) | |
console.log(args) | |
console.log(flags) | |
function processArgsForFlags(fromArgs, expected = {}) { | |
let args = Array.from(fromArgs) | |
let flags = {} | |
let errors = [] | |
let interpreter = Object.assign(parse(args.shift()), { toString() { return format(this) }}) | |
let executable = Object.assign(parse(args.shift()), { toString() { return format(this) }}) | |
for (let i = 0; i < args.length; i++) { | |
let search = /--(\w+)(?:=(.*))?/g.exec(args[i]) | |
if (search) { | |
let param = search[1] | |
let value = search[2] | |
if (!value) { | |
if (i + 1 < args.length) { | |
value = args[i + 1] | |
args.splice(i, 2) | |
} | |
} | |
else { | |
args.splice(i, 1) | |
i-- // Decrement i to account for removed element | |
} | |
if (param in expected && typeof(expected[param]) == 'function') { | |
value = expected[param](value) | |
} | |
else { | |
if (typeof(expected[param]) !== 'function') { | |
errors.push({message: 'Expected type parameter is not a function that converts string to value', param}) | |
} | |
} | |
flags[param] = value | |
} | |
} | |
return { | |
interpreter, | |
executable, | |
args, | |
flags, | |
errors, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment