bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.66k stars 495 forks source link

Impossible to create fake state with valid state abbr #402

Closed ViktorKarpilov closed 2 years ago

ViktorKarpilov commented 2 years ago

Please describe why you are requesting a feature

There are situations where is needed to create valid state with it abbreviation

Please provide a code example of what you are trying to achieve

For example: faker.Address.StateWithAbbr() -> {"Alaska", "AL"}

Please answer any or all of the questions below

If the feature request is approved, would you be willing to submit a PR? Yes

bchavez commented 2 years ago

You can currently generate state names with abbreviations; however, the solution below relies on the en locale ordering of the underlying data:

void Main()
{
   var faker = new Faker();
   var stateWithAbbr = faker.Address.StateWithAbbr();
   stateWithAbbr.Dump();
}

public static class MyExtensionsForBogus
{
   public static (string name, string abbr) StateWithAbbr(this Address addr)
   {
       var names = (BArray)Bogus.Database.Get("address","state");
       var abbr = (BArray)Bogus.Database.Get("address","state_abbr");

       var i = addr.Random.Number(0, names.Count - 1);

       return (names[i], abbr[i]);
   }
}

image

Ultimately, you'll need to use this hack for now until upstream faker.js supports generating state tuples. The problem with implementing this now is that StateWithAbbr will only work with the en locale, and probably break for other locales like ru if ordering (and count) is not maintained in other respective locales.

If you want to contribute a patch; I'd suggest submitting a faker.js patch upstream first, then we can possibly implement it downstream here in Bogus.

bchavez commented 2 years ago

Thinking about this more, you could add a StateWithAbbr() extension method in the Bogus.Extensions.UnitedStates which would help isolate the usage to just the US/en locale:

https://github.com/bchavez/Bogus/blob/master/Source/Bogus/Extensions/UnitedStates/ExtensionsForUnitedStates.cs

I can accept a PR that adds StateWithAbbr() extension method to ExtensionsForUnitedStates.cs