Skip to content

Instantly share code, notes, and snippets.

@swingley
Created October 15, 2019 05:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swingley/304d35d40a2c14f579c9625de3c2131c to your computer and use it in GitHub Desktop.
Save swingley/304d35d40a2c14f579c9625de3c2131c to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
// read the API response files
const DATA_DIR = 'data'
const API_RESPONSE_FILE_PREFIX = 'census_api_response'
const STATES_FILE = path.join(DATA_DIR, `${API_RESPONSE_FILE_PREFIX}_fips_states.json`)
const COUNTIES_FILE = path.join(DATA_DIR, `${API_RESPONSE_FILE_PREFIX}_fips_counties.json`)
const states = JSON.parse(fs.readFileSync(STATES_FILE))
const counties = JSON.parse(fs.readFileSync(COUNTIES_FILE))
const state_abbreviations = JSON.parse(fs.readFileSync('us_state_abbreviations.txt'))
Object.entries(state_abbreviations).forEach(([key, value]) => {
state_abbreviations[value] = key
})
// First element in the array isn't data but field headers, throw it out
states.shift()
let lookup = states.reduce((accum, [name, fips]) => {
const abbreviation = state_abbreviations[name]
if (abbreviation) {
accum[abbreviation] = {
'_name': name,
'_fips': fips
}
accum.fipsToState[fips] = abbreviation
}
return accum
}, { fipsToState: {} })
// First element in the array isn't data but field headers, throw it out
counties.shift()
counties.reduce((accum, [name, stateFips, fips]) => {
if (stateFips && fips && lookup.fipsToState[stateFips]) {
const countyFips = `${stateFips}${fips}`
const currentState = lookup.fipsToState[stateFips]
lookup[currentState][name.split(',')[0]] = countyFips
}
return lookup
}, lookup)
const FIPS_LOOKUP = path.join(DATA_DIR, 'fips_lookup_by_state.json')
fs.writeFileSync(FIPS_LOOKUP, JSON.stringify(lookup, null, 2))
// console.log(JSON.stringify(lookup, null, 2))
console.log(`wrote lookup file: ${FIPS_LOOKUP}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment