import type { DoubleArray } from 'cheminfo-types';

import type { DataXReIm } from '../types/index.ts';

/**
 * Sort object of arrays, x has to be monotone.
 * @param data - object of kind {x:[], re:[], im:[]}
 * @returns sorted DataXReIm object.
 */
export function xreimSortX<ArrayType extends DoubleArray = DoubleArray>(
  data: DataXReIm<ArrayType>,
): DataXReIm<ArrayType> {
  const { x, re, im } = data;

  if (x.length !== re.length || x.length !== im.length) {
    throw new TypeError('length of x, re and im must be identical');
  }

  if (x.length < 2 || x[0] < x[1]) return data;

  return {
    x: x.toReversed() as ArrayType,
    re: re.toReversed() as ArrayType,
    im: im.toReversed() as ArrayType,
  };
}
