Skip to content

Updating the areaCodePromityMap.json File

Charlie Weems edited this page Aug 29, 2022 · 2 revisions

In order to help select phone numbers by the closest available geography, we provide a JSON file that gives a list of nearby area codes for each area code in the U.S. and Canada.

This file shouldn't need to be modified unless a new area code is added. If that happens, you can use the following node script to re-generate the JSON file with the new area code:

Note that the script requires geolib.

/* eslint-disable space-before-function-paren */
import * as fsp from 'fs/promises'
import { getDistance } from 'geolib'
import path from 'path'
import areaCodeGeos from './areaCodeGeos'

/****************************************************
 Computes src/data/area-code-proxmity-map.json which is used to determine the
 closest area codes to another area code.

 It is not executed by the project at anytime. This script is included to show
 how the proximity was calculated and allow you to modify it, if necessary.
****************************************************/

interface AreaCodeItem {
  areaCode: number
  latitude: number
  longitude: number
}

async function prepareAreaCodeProximityMap() {
  await fsp.writeFile(
    path.resolve(__dirname, '../src/data/areaCodeProximityMap.json'),
    JSON.stringify({
      ca: computeAreaCodeProximities(areaCodeGeos.ca),
      us: computeAreaCodeProximities(areaCodeGeos.us)
    })
  )
}

function computeAreaCodeProximities(areaCodeList: AreaCodeItem[]) {
  return areaCodeList
    .map((curAreaCodeItem) => ({
      [curAreaCodeItem.areaCode]: [curAreaCodeItem.areaCode].concat(
        areaCodeList
          .filter(
            (areaCodeItem) => areaCodeItem.areaCode !== curAreaCodeItem.areaCode
          )
          .map((areaCodeItem) => [
            areaCodeItem.areaCode,
            getDistance(curAreaCodeItem, areaCodeItem)
          ])
          .sort(([, aDistance], [, bDistance]) => aDistance - bDistance)
          .map(([areaCode]) => areaCode)
      )
    }))
    .reduce((acc, cur) => Object.assign(acc, cur), {})
}

prepareAreaCodeProximityMap()
Clone this wiki locally