@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
54 lines (52 loc) • 2.51 kB
JavaScript
import { isObject } from "./isObject.js";
// src/internal/position.ts
/**
* Read a `Position` from a caller's value, or `null`. This is the one check every function that
* takes a `Position` makes; that function then returns its own sentinel for `null`.
*
* - `latitude` must be a number from -90 to 90 inclusive (RFC 5870 §3.4.2). `longitude` must be a
* number from -180 to 180 inclusive (RFC 5870 §3.4.2; §3.4.4 treats 180 and -180 as equal).
* Neither is wrapped or clamped.
* - `height` is optional and has no range, but when it is present it must be a finite number.
* `undefined` means the height is not known, and the result then has no `height` key. `null` is
* not the same as absent and gives `null`.
* - The members are read with an ordinary property get, once each, in the order `height`,
* `latitude`, `longitude`. All three are read before any is checked, and the caller's value is
* never read again.
* - Nothing is coerced: `"35.68"`, `35n` and `new Number(35)` are all invalid.
* - Values are copied unchanged. `-0` stays `-0`, and `180` and `-180` are never rewritten.
* - The result is a new plain object with the keys `latitude`, `longitude` and, when given,
* `height`. Extra members on the input are not copied. It is not frozen.
* - It never throws. A throwing getter, a throwing Proxy or a revoked Proxy gives `null`.
*
* @param value the caller's candidate position
* @example readPosition({ latitude: 35.68, longitude: 139.77 }) // { latitude: 35.68, longitude: 139.77 }
* @example readPosition({ latitude: 35.68, longitude: 139.77, height: -30 }) // { latitude: 35.68, longitude: 139.77, height: -30 }
* @example readPosition({ latitude: 0, longitude: -180 }) // { latitude: 0, longitude: -180 }
* @example readPosition([139.77, 35.68]) // null
* @example readPosition({ latitude: 90.000001, longitude: 0 }) // null
* @returns a new `Position`, or `null` when `value` is not a valid position
*/
function readPosition(value) {
if (!isObject(value)) return null;
let height;
let latitude;
let longitude;
try {
({height, latitude, longitude} = value);
} catch {
return null;
}
if (typeof latitude !== "number" || !(latitude >= -90 && latitude <= 90) || typeof longitude !== "number" || !(longitude >= -180 && longitude <= 180)) return null;
if (height === void 0) return {
latitude,
longitude
};
if (typeof height !== "number" || !Number.isFinite(height)) return null;
return {
latitude,
longitude,
height
};
}
export { readPosition };