webroo / dummy-json

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

How to generate a letter from the range #9

Closed kuncevic closed 8 years ago

kuncevic commented 8 years ago

Lets say I want to generate a single letter from the range ABCDE/[A-E] is there any way of doing that?

webroo commented 8 years ago

Yes there is! Unfortunately it's not a built-in helper but you can easily make one yourself. The method you need is dummyjson.utils.randomChar(). Here's an example:

var myHelpers = {
  char: function() {
    return dummyjson.utils.randomChar('ABCDE');
  }
};
var template = 'My random character is {{char}}';
var result = dummyjson.parse(template, {helpers: myHelpers});
// result is "My random character is C"

randomChar() takes a string and returns a single random character from it. The postcode helper uses it internally. I might expose it as a built-in helper in future updates.

If you need greater control over the characters generated then this library might be useful: https://github.com/fent/randexp.js