Last active
December 9, 2018 11:13
-
-
Save MathieuLoutre/27376d65292906f7a38a401e07a9ad0e to your computer and use it in GitHub Desktop.
Using OpenCageData address formatting with Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const yaml = require('js-yaml') | |
const Mustache = require('mustache') | |
const addressFormats = yaml.safeLoad(fs.readFileSync('./worldwide.yaml', 'utf8')) | |
const first = function () { | |
return (text, render) => render(text, this).split(/\s*\|\|\s*/).find((el) => el) | |
} | |
const formatAddress = (components, countryCode) => { | |
let format = addressFormats[countryCode] || addressFormats.default | |
if (format.use_country) { | |
if (format.change_country) { | |
// TODO: make replace $state generic | |
components.country = format.change_country.replace('$state', components.state) | |
} | |
if (format.add_component) { | |
const [key, value] = format.add_component.split('=') | |
components[key] = value | |
} | |
format = addressFormats[format.use_country] | |
} | |
const template = format.address_template | |
if (format.replace) { | |
format.replace.forEach((replaceRule) => { | |
if (replaceRule[0].includes('=')) { | |
const [field, rule] = replaceRule[0].split('=') | |
if (components[field]) { | |
components[field] = components[field].replace(new RegExp(rule), replaceRule[1]) | |
} | |
} | |
else { | |
Object.keys(components).map((field) => { | |
if (components[field]) { | |
components[field] = components[field].replace(new RegExp(replaceRule[0]), replaceRule[1]) | |
} | |
}) | |
} | |
}) | |
} | |
let output = Mustache.render(template, { ...components, first }) | |
if (format.postformat_replace) { | |
format.postformat_replace.forEach((replaceRule) => { | |
output = output.replace(new RegExp(replaceRule[0]), replaceRule[1]) | |
}) | |
} | |
// Cleanup extra space | |
output = output.replace(/^\s+/gm, '').replace(/ +/g, ' ') | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment