All files / geonet-geohash/src neighbor.js

100% Statements 12/12
100% Branches 8/8
100% Functions 1/1
100% Lines 12/12

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                        1x                     2621x 1x   2620x 1x       2619x 2619x   2619x   2619x 545x       2619x     1x  
/** ****************************************************************************************************
 * File: neighbor.js
 * Project: geohash
 * @author Nick Soggin <iSkore@users.noreply.github.com> on 19-Feb-2019
 *******************************************************************************************************/
'use strict';
 
const
	{
		BASE32,
		NEIGHBOR_CODEX,
		BORDER_CODEX
	} = require( './variables' );
 
/**
 * Determines neighbor cell in given direction.
 *
 * @param {string} geohash - Cell to which neighbor cell is required.
 * @param {string} direction - Direction from geohash (N/S/E/W).
 * @returns {string} Geocode of neighbor cell.
 * @throws  Invalid geohash.
 */
function neighbor( geohash, direction ) {
	if ( geohash.length === 0 ) {
		throw new Error( 'Invalid geohash' );
	}
	else if ( 'nsew'.indexOf( direction ) === -1 ) {
		throw new Error( 'Invalid direction' );
	}
 
	const
		lastCh = geohash.slice( -1 ),
		type   = geohash.length % 2;
 
	let parent = geohash.slice( 0, -1 );
 
	if ( BORDER_CODEX[ direction ][ type ].indexOf( lastCh ) !== -1 && parent !== '' ) {
		parent = neighbor( parent, direction );
	}
 
	// append letter for direction to parent
	return parent + BASE32.charAt( NEIGHBOR_CODEX[ direction ][ type ].indexOf( lastCh ) );
}
 
module.exports = neighbor;