All files / geonet-geohash/src geohashToBBox.js

100% Statements 25/25
100% Branches 10/10
100% Functions 1/1
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                            1x                     1485x 1x       1484x 1484x 1484x 1484x 1484x   1484x   7455x 7455x   7455x 1x     7454x 37270x   37270x   19368x 19368x       17902x 17902x     37270x       1483x     1x  
/** ****************************************************************************************************
 * File: geohashToBBox.js
 * Project: geohash
 * @author Nick Soggin <iSkore@users.noreply.github.com> on 19-Feb-2019
 *******************************************************************************************************/
'use strict';
 
const
	{
		BASE32,
		MIN_LNG,
		MIN_LAT,
		MAX_LNG,
		MAX_LAT
	} = require( './variables' );
 
/**
 * geohashToBBox
 * @description
 * Returns BBox bounds of specified geohash.
 * @param   {string} hash - geohash to convert to bbox
 * @returns {number[]} bbox array
 * @throws  Invalid geohash.
 */
function geohashToBBox( hash ) {
	if ( hash.length === 0 ) {
		throw new Error( 'Invalid geohash' );
	}
 
	let
		evenBit = true,
		lngMin  = MIN_LNG,
		latMin  = MIN_LAT,
		lngMax  = MAX_LNG,
		latMax  = MAX_LAT;
 
	for ( let i = 0; i < hash.length; i++ ) {
		const
			chr      = hash.charAt( i ),
			hashChar = BASE32.indexOf( chr );
 
		if ( hashChar === -1 ) {
			throw new Error( 'Invalid geohash' );
		}
 
		for ( let n = 4; n >= 0; n-- ) {
			const bitN = hashChar >> n & 1;
 
			if ( evenBit ) {
				// longitude
				const lngMid = ( lngMin + lngMax ) / 2;
				bitN === 1 ? lngMin = lngMid : lngMax = lngMid;
			}
			else {
				// latitude
				const latMid = ( latMin + latMax ) / 2;
				bitN === 1 ? latMin = latMid : latMax = latMid;
			}
 
			evenBit = !evenBit;
		}
	}
 
	return [ lngMin, latMin, lngMax, latMax ];
}
 
module.exports = geohashToBBox;