mukeshsoni / country-telephone-data

Data related to a country's telephone dial code and number formatting
41 stars 38 forks source link

Refactor internal data format #11

Open eemeli opened 5 years ago

eemeli commented 5 years ago

Based on #10, this goes on to refactor the internal data format and separates the data into data.json and the output functions into index.js. All external interfaces are kept unmodified.

The previous data format was:

[[name, iso2, dialCode, format, priority, areaCodes]]

And the updated data format is:

{ [dialCode]: [{ iso2, name, format, areaCodes }] }

In terms of file size, using an object with string keys rather than an array actually has almost no effect on gzipped output size, as the common strings get compacted. Legibility is significantly increased, and some of the previous possibilities for errors (namely, missing priority order) are eliminated.

As an additional feature, the data itself is now exposed separately, which allows its use even outside JS environments.

eemeli commented 5 years ago

In case it's of interest, here's the mapping I used to generate data.json from the previous allCountries data:

const data = allCountries.reduce(
  (data, [name, iso2, dial, format, prio, areas]) => {
    const row = { iso2, name };
    if (format) row.format = format;
    if (areas) row.areaCodes = areas;
    if (!data[dial]) data[dial] = [];
    if (typeof prio == 'number') data[dial][prio] = row;
    else data[dial].push(row);
    return data;
  },
  {}
);