webroo / dummy-json

Generates random dummy JSON data in Node.js
MIT License
380 stars 61 forks source link

new feature for small inline arrays #34

Closed peterprib closed 4 years ago

peterprib commented 4 years ago

To avoid have to do overhead of having to do own helpers could I suggest new keyword of array e.g. {{array ["M","F"]}}

Better still add driving probability of selection

{{array ["cat","dog","mouse"] [0.4, 0.4, 0.2]}}

where second array is driving probability of selection. Makes it a lot easier to handle different types of classifications normally associated with data.

webroo commented 4 years ago

This is really nice idea but after some quick experimentation it seems you can't pass arrays to handlebars helpers. You could pass a string and then json.parse it, but depending on how you write your template you might need to escape some quotes, which looks a bit ugly:

'{{array \'["cat","dog","mouse"]\'}}'

Alternatively you could pass each array element as an argument, but that would make implementing the probability array harder:

{{array "cat" "dog" "mouse"}}

Neither seem ideal to me but I'll leave this issue open for now in case I come up with a better idea.

peterprib commented 4 years ago

Had not realised the fact it was based on https://github.com/webroo/dummy-json how about this as a suggestion

{{list 'aaaa,"bbb, bb",cccc'}}

with helper of form

Handlebars.registerHelper('list', function (aString) { const s=aString.split(/(?:,|\n|^)("(?:(?:"")[^"])"|[^",\n]|(?:\n|$))/) const c=s[3] return c.startsWith('"')?c.substring(1,c.length-1):c

})

At least does a list.

webroo commented 4 years ago

In the end I decided to go with a simple approach that just used helper arguments:

{{random 'cat' 'dog' 'mouse'}}

This helper is available as of v3.0.0 and more examples can be found in the readme: https://github.com/webroo/dummy-json#random-item