coords.ts 4.15 KB
/**
 * 坐标规范化:把原始文本按十进制读到六位小数(四舍五入),并给出接口/缓存/合理盒要用的形态。
 *
 * 为什么不用 double 直接 toFixed:`Number('113.0000005')` 落在 113.0000005 略下方,
 * toFixed 会给成 …000000,同一坐标在两台机器上算出不同缓存键就会重复付费。
 * 这里在数字字符串上做舍入,不引入通用十进制类。
 */
import { UserError } from './errors.ts';

/** 与主程序 ingestCore 的合理盒同一组数:盒外的点主程序导入时必拒,先在这里挡掉就不必付费查 */
export const SANITY_BOX = { minLng: 113.6, maxLng: 114.7, minLat: 22.3, maxLat: 23.0 };

/** 六位小数的规范化坐标,接口与日志用的文本形态 */
export type Coords = readonly [string, string];

const DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;

/** 整数部分(去前导零);先粗筛量级,避免把 1e9999999 这种写成定点串 */
function integerDigits(digits: string, point: number): string {
  if (point <= 0) return '';
  return digits.slice(0, point).replace(/^0+/, '');
}

/**
 * 四舍五入到六位小数后的定点文本(不含符号)。
 * digits 是小数点前后的数字串,point 是小数点位置(可为 0 或负)。
 */
function roundSix(digits: string, point: number): string {
  const keep = point + 6;
  if (keep <= 0) return '0.000000';
  let head = digits.slice(0, keep).padEnd(keep, '0');
  const firstDropped = digits.length > keep ? digits[keep] : '0';
  if (firstDropped >= '5') {
    let carry = 1;
    const chars = head.split('');
    for (let i = chars.length - 1; i >= 0 && carry > 0; i -= 1) {
      const sum = Number(chars[i]) + carry;
      chars[i] = String(sum % 10);
      carry = Math.floor(sum / 10);
    }
    head = carry > 0 ? `${carry}${chars.join('')}` : chars.join('');
  }
  head = head.replace(/^0+/, '');
  if (head === '') return '0.000000';
  const padded = head.padStart(7, '0');
  return `${padded.slice(0, padded.length - 6)}.${padded.slice(padded.length - 6)}`;
}

/** 读到六位小数;越界、非数、空值都抛 UserError */
export function normalizeCoordinate(raw: unknown, bound: number, name: string): string {
  const text = typeof raw === 'number' ? (Number.isFinite(raw) ? String(raw) : '')
    : typeof raw === 'string' ? raw.trim() : '';
  const match = DECIMAL.exec(text);
  if (match === null || (match[2] === '' && (match[3] === undefined || match[3] === ''))) {
    throw new UserError(`${name}缺失、非数值或格式非法`);
  }
  const [, sign, integer, fraction, exponent] = match;
  const point = integer.length + (exponent === undefined ? 0 : Number(exponent));
  if (!Number.isSafeInteger(point) || point > 12) throw new UserError(`${name}超出可处理范围`);
  const intDigits = integerDigits(`${integer}${fraction ?? ''}`, point);
  if (intDigits.length > String(bound).length
    || (intDigits.length === String(bound).length && intDigits > String(bound))) {
    throw new UserError(`${name}越界(绝对值需 ≤ ${bound})`);
  }
  const rounded = roundSix(`${integer}${fraction ?? ''}`, point);
  // 舍入后再比一次:整位相等但带小数尾巴的(180.0000004)已不在合法范围内
  if (Math.abs(Number(rounded)) > bound) throw new UserError(`${name}越界(绝对值需 ≤ ${bound})`);
  return sign === '-' && rounded !== '0.000000' ? `-${rounded}` : rounded;
}

export function normalizeCoordinates(lng: unknown, lat: unknown): [string, string] {
  return [normalizeCoordinate(lng, 180, '经度'), normalizeCoordinate(lat, 90, '纬度')];
}

/** 六位文本 → 微度整数(缓存主键);同一文本在任何机器上都得同一个数 */
export function toMicroDegrees(six: string): number {
  const negative = six.startsWith('-');
  const [whole, frac = ''] = six.replace('-', '').split('.');
  const value = Number(`${whole}${frac.padEnd(6, '0').slice(0, 6)}`);
  return negative ? -value : value;
}

export function insideSanityBox(coords: Coords): boolean {
  const lng = Number(coords[0]);
  const lat = Number(coords[1]);
  return lng >= SANITY_BOX.minLng && lng <= SANITY_BOX.maxLng
    && lat >= SANITY_BOX.minLat && lat <= SANITY_BOX.maxLat;
}