Skip to content

Commit 761587c

Browse files
committed
Refactor Mgrs.parse() for improved clarity
1 parent 9dbc666 commit 761587c

File tree

1 file changed

+14
-27
lines changed

1 file changed

+14
-27
lines changed

mgrs.js

+14-27
Original file line numberDiff line numberDiff line change
@@ -155,41 +155,28 @@ class Mgrs {
155155
if (!mgrsGridRef) throw new Error(`invalid MGRS grid reference ‘${mgrsGridRef}’`);
156156

157157
// check for military-style grid reference with no separators
158-
if (!mgrsGridRef.trim().match(/\s/)) { // replace with standard space-separated format
159-
const milref = mgrsGridRef.match(/(\d\d?[A-Z])([A-Z]{2})([0-9]{2,10})/);
160-
if (!milref) throw new Error(`invalid MGRS grid reference ‘${mgrsGridRef}’`);
161-
const mil = {
162-
gzd: milref[1],
163-
en100k: milref[2],
164-
en: milref[3],
165-
};
166-
mil.e = mil.en.slice(0, mil.en.length/2);
167-
mil.n = mil.en.slice(-mil.en.length/2);
168-
mgrsGridRef = `${mil.gzd} ${mil.en100k} ${mil.e} ${mil.n}`;
158+
if (!mgrsGridRef.trim().match(/\s/)) { // convert mgrsGridRef to standard space-separated format
159+
const ref = mgrsGridRef.match(/(\d\d?[A-Z])([A-Z]{2})([0-9]{2,10})/i);
160+
if (!ref) throw new Error(`invalid MGRS grid reference ‘${mgrsGridRef}’`);
161+
162+
const [ , gzd, en100k, en ] = ref; // split grid ref into gzd, en100k, en
163+
const [ easting, northing ] = [ en.slice(0, en.length/2), en.slice(-en.length/2) ];
164+
mgrsGridRef = `${gzd} ${en100k} ${easting} ${northing}`;
169165
}
170166

171167
// match separate elements (separated by whitespace)
172-
const ref = mgrsGridRef.match(/\S+/g);
173-
168+
const ref = mgrsGridRef.match(/\S+/g); // returns [ gzd, e100k, easting, northing ]
174169
if (ref==null || ref.length!=4) throw new Error(`invalid MGRS grid reference ‘${mgrsGridRef}’`);
175170

176-
// split gzd into zone/band
177-
const gzd = ref[0].match(/(\d\d?)([A-Z])/i);
178-
const zone = gzd[1];
179-
const band = gzd[2];
180-
181-
// split 100km letter-pair into e/n
182-
const en100k = ref[1];
183-
const e100k = en100k.slice(0, 1);
184-
const n100k = en100k.slice(1, 2);
185-
186-
let e = ref[2], n = ref[3];
171+
const [ gzd, en100k, e, n ] = ref; // split grid ref into gzd, en100k, e, n
172+
const [ , zone, band ] = gzd.match(/(\d\d?)([A-Z])/i); // split gzd into zone, band
173+
const [ e100k, n100k ] = en100k.split(''); // split 100km letter-pair into e, n
187174

188175
// standardise to 10-digit refs - ie metres) (but only if < 10-digit refs, to allow decimals)
189-
e = e.length>=5 ? e : (e+'00000').slice(0, 5);
190-
n = n.length>=5 ? n : (n+'00000').slice(0, 5);
176+
const easting = e.length>=5 ? e : e.padEnd(5, '0');
177+
const northing = n.length>=5 ? n : n.padEnd(5, '0');
191178

192-
return new Mgrs(zone, band, e100k, n100k, e, n);
179+
return new Mgrs(zone, band, e100k, n100k, easting, northing);
193180
}
194181

195182

0 commit comments

Comments
 (0)