I've written a algorithm to find parameters in a command line tool and are looking to clean up my code but is stuck.
The task
My program receives parameters as: flag output input ...
| input flag output
Examples are: -d one/path second/path/to/file.txt
and second/path/to/file.txt --dir one/path
etc. Each space is used as a delimiter to create an array of parameters. A parameter can be either a flag such as -d
or a path.
I got each flag mapped out in two arrays, which I zip into a an array of tuples. I call them the search set.
In math notation
I'm new to both FP and math notations so please forgive my mistakes (I've learned from wikipedia and other sites).
S for search and P for parameters
S = { S₁, S₂, S₃ }
where Sn = { flagShort, flagLong }
where flagShort = '-d' | '-r' | '-o'
flagLong = '--dir' | '--replace' | '--output'
P = { P₁, P₂, ... }
where Pn = flag | path
where path = dir | file
So I need to find the output by searching P for occurrences of Sn + the next parameter after the flag.
Ps = Sn ∩ P + Pₙ+₁
Input is just Ps ∉ P
, so that is easy if I can get Ps.
Which leads me to the following transformation:
P -> Pn -> S -> Sn -> Sn = Pn -> Pn + Pₙ+₁
In javascript it can be written as:
const flagsShort = ["-r","-d","-o"]
const flagsLong = ["--replace","--dir","--output"]
const search = _.zip(flagsShort, flagsLong)
let Ps = tuplesIntersectionParametersPlusNextP(
['one/path', '--dir', 'two/path', '-d', 'one/path', '-d'],
search
)
// Ps -> [ '--dir', 'two/path', '-d', 'one/path' ]
function tuplesIntersectionParametersPlusNextP(P, S) {
const Ps = [];
P.forEach( (Pn, n) => {
S.forEach(Sn => {
Sn.forEach(flag => {
if(flag===Pn) Ps.push(Pn, P[n+1])
})
})
})
return Ps
}
While the code above works, it doesn't look clean. I've been looking around for different FP libraries such as underscore and different python articles but have yet to figure out how to use all these clever FP functions to clean up my code.
I will accept an answer in any language, Python, Haskell, Scala, etc but please don't use list comprehensions. While I'm very confident that I can port your code to js, I find list comprehensions a tad difficult to port. Better use map
each
reduce
etc.
If you also can point me in the right direction with the set notations, I will be truly grateful!