UNPKG

@hamlog/maidenhead

Version:

For various amateur radio needs, we at [Hamlog.Online](https://hamlog.online) required a library to process [Maidenhead grid locators](https://en.wikipedia.org/wiki/Maidenhead_Locator_System) in Javascript.

2 lines (1 loc) 1.55 kB
(function(i,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(i=typeof globalThis<"u"?globalThis:i||self,a(i.lib={}))})(this,function(i){"use strict";function a(t){if(t.length%2!==0)return!1;const e=t.toLowerCase();if(!/^[a-x0-9]+$/.test(e))return!1;for(let n=0;n<e.length;n+=2){const o=`${e[n]}${e[n+1]}`;if(n==0){if(!/[a-r]{2}/.test(o))return!1}else if(n%4!=0){if(!/\d{2}/.test(o))return!1}else if(!/[a-x]{2}/.test(o))return!1}return!0}const u=65,d=48;function c(t){let e=t.charCodeAt(0);return e>=u?e-u:e-d}function h(t,e){return String.fromCharCode(t+(e?u:d))}function p(t){if(!a(t))throw new SyntaxError(`"${t}" is not a valid Maidenhead locator`);const e=t.toUpperCase(),n=e.length/2;let o=-90,f=-90,l=10;for(let r=0;r<n;r++)o+=l*c(e[2*r]),f+=l*c(e[2*r+1]),r<n-1&&(r%2>0?l/=24:l/=10);return o*=2,[{lat:f,lon:o},{lat:f+l,lon:o+l*2}]}function g(t){const e=p(t);return{lat:(e[0].lat+e[1].lat)/2,lon:(e[0].lon+e[1].lon)/2}}function v(t){let e="";for(let n=0;n<t.length;n++)e+=[4,5,12,13].includes(n)?t[n].toLowerCase():t[n].toUpperCase();return e}function C(t,e=6,n=!1){if(e%2!=0)throw SyntaxError("Maidenhead grids are supposed to have an even number of characters.");let o="",f=t.lon/2+90,l=t.lat+90,r=10;for(let s=0;s<=6;s++){const T=s%2==0;o+=h(Math.floor(f/r),T),o+=h(Math.floor(l/r),T),f%=r,l%=r,s%2>0?r/=24:r/=10}return n&&(o=v(o)),o.slice(0,e)}i.gridToBox=p,i.gridToPoint=g,i.pointToGrid=C,i.validateGrid=a,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});