import { Ref } from 'vue';

export function setDefault<T = any>(
  val: Ref<T | undefined>,
  _default: T | undefined
) {
  if (val.value === undefined) val.value = _default;
  return val;
}

const toArray = (val: string | string[]) => {
  if (val === null || val === undefined) {
    return [];
  }
  return Array.isArray(val) ? val : [val];
};

export function getPathValue(record: any, path: string | string[]) {
  // Skip if path is empty
  if (!path && typeof path !== 'number') {
    return record;
  }
  const pathList = toArray(path);
  let current = record;
  for (let i = 0; i < pathList.length; i++) {
    if (!current) {
      return null;
    }
    const prop = pathList[i];
    current = current[prop];
  }
  return current;
}
