lucapette / fakedata

CLI utility for fake data generation
MIT License
200 stars 7 forks source link

Support concatenating items when using range loop #57

Closed gmile closed 1 year ago

gmile commented 7 years ago

I'm facing a difficulty when generating JSON arrays by means of templates.

In the following example it's not possible to generate a valid JSON array, because of the trailing coma:

echo '[{{ range Loop 5 }}"{{ Int }}",{{ end }}]' | fakedata -l 1
["52","419","365","561","753",]

If only there'd be a way to concat items before outputting them. Something like this would work great:

echo '[{{ range Loop 5 "," }}"{{ Int }}",{{ end }}]' | fakedata -l 1
["52","419","365","561","753"]

Above, by specifying another argument in range, it'd be possible to define a string that would be used when concatenating items before final output.

KevinGimbel commented 7 years ago

Hi @gmile. This is a very good issue report, thank you very much!

I originally intended to have a {{ Last }} and {{ First }} function for templates for this exact use case but couldn't implement them (yet). The problem I faced was that I needed to pass the current iteration, e.g. {{ Last $i }}, which was not a nice API.

I'll give this some testing and think about a way to implement either a {{ Last }} / {{ First }} function or a concat function.

lucapette commented 7 years ago

@gmile thank you! Awesome explanation!

@kevingimbel I'm very grateful you self-assigned this one and will look into it. It's so cool to see there's a real world need for the Last First function we've been discussing in the past!

lucapette commented 1 year ago

I just merged #78 which makes this a little easier (and makes me consider it done). You can now do this:

echo '[{{ range $index := Loop 5 }}"{{ Int }}"{{if lt $index 4}},{{end}}{{ end }}]' | fakedata
["347","340","291","43","911"]
["791","231","843","921","945"]
["183","857","285","322","44"]
["75","130","843","609","718"]
["497","795","912","692","774"]
["564","413","414","510","726"]
["934","251","454","551","423"]
["948","131","9","429","959"]
["154","834","417","775","874"]
["761","687","681","175","207"]

Which seems good enough for the use case. In case it doesn't work, please do reopen