Skip to content

Instantly share code, notes, and snippets.

@roelofr
Last active January 31, 2021 14:21
Show Gist options
  • Select an option

  • Save roelofr/19117e3cf4de727110e8c3e476183fdd to your computer and use it in GitHub Desktop.

Select an option

Save roelofr/19117e3cf4de727110e8c3e476183fdd to your computer and use it in GitHub Desktop.
Find valid Bahrain postal ranges

Find Bahrain (BH) postal ranges

This snippet, to be run in your devtools, finds all numbers in the table on this page and finds the largest overlaps in an $O(N)$ fashion.

Bahrain postal codes have a XYY or XXYY format, where X is the municipality and Y is the locality.

Results are printed as info messages. Debug info is grouped.

The first result are all available postal code ranges. The second result is just the municipality ranges.

(() => {
let numbers = []
const numericSort = (a, b) => a - b
const resolveAscending = (values) => {
let ranges = []
let currentRange = null
let previousNumber = null
// Separate, to make code DRY
const assignResult = () => {
if (currentRange !== null && currentRange === previousNumber) {
ranges.push(`${currentRange}`)
} else if (currentRange !== null) {
ranges.push(`${currentRange}-${previousNumber}`)
}
}
values.sort(numericSort)
values.forEach(value => {
if (value - 1 !== previousNumber) {
assignResult()
currentRange = value
}
previousNumber = value
})
assignResult()
return ranges
}
// Find tables matching '123', '123, 456' and repetatives of that
console.groupCollapsed('Bodies')
document.querySelectorAll('td').forEach(node => {
const nodeText = node.innerText.trim()
if (nodeText.match(/^(\d+, )*\d+$/)) {
console.info('Found match %o in %o', nodeText, node)
const nodeNumbers = nodeText.split(',').map(node => parseInt(node, 10))
numbers = [...numbers, ...nodeNumbers]
}
})
console.groupEnd()
// Get full ranges
numbers.sort(numericSort)
console.info('Available number ranges: %o', resolveAscending(numbers))
// Get code, which is >=100. De-duplicate using a Set
const municipalitiesSet = [...new Set(numbers.map(val => Math.floor(val / 100)))]
console.info('Resolved municipality ranges: %o', resolveAscending(municipalitiesSet))
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment