Postal Parser
solution to reddit dailyprogrammer puzzle
HTML
<a>Enter your adress Below</a>
<br />
<textarea id="address" cols="40" rows="10"></textarea>
<input type="button" id="go" value="go!" onclick="parse()">
<div id="results"></div>
JavaScript
var AddressBook = [];
function Address(addressee, address, street, locale, city, state, postal_code, country, phone) {
this.addressee = addressee;
this.address = address;
this.street = street;
this.city = city;
this.localization = locale;
this.state = state;
this.postal_code = postal_code;
this.country = country;
this.phone = phone;
}
function parse() {
var business, address, street, city, locArr, state, postal_code, country, phone, locStr;
var zipArr, addArr;
var phoneIndex, countryIndex, zipIndex, addressIndex, csIndex;
phoneIndex = countryIndex = zipIndex = addressIndex = csIndex = -1;
var text = document.getElementById("address").value.trim()
var lines = text.split("\n")
//only consider addresses with 3 lines (name, zip, country at minimum)
if (lines.length < 3) {
window.alert("Please enter a valid Address")
return;
}
/*we will work backwards with this basic logic
/last line will either have numbers or not. If it has numbers, it is a phone numbers
/line before phone number will be country
/next line with numbers will contain area code, and possibly city
/next line with numbers will contain street and address
/lines with a comma will be assumed to be city and state
/smush all remaining info into a locale catch-all
/position 0 in array will always be addressee
*/
else {
addressee = lines[0];
if (lines[lines.length - 1].search(/\d/) > -1) {
phoneIndex = lines.length - 1;
countryIndex = lines.length - 2;
} else {
countryIndex = lines.length - 1
}
//first loop to get zip, address, and some cities
for (var i = countryIndex - 1; i > 0; i--) {
if (lines[i].search(/\d/) > -1 && zipIndex == -1) {
zipIndex = i;
} else if (lines[i].search(/\d/) > -1 && zipIndex > -1) {
addressIndex = i;
}
if (lines[i].search(",") > 0) {
csIndex = i;
locArr = lines[i].split(",");
city = locArr[0];
state =...