/**
 * 判断值是否是数组并执行 map
 * @param value
 * @param defaultValueOrMap
 * @param [map]
 */
export function getArray(value, defaultValueOrMap = [], map) {
  if (typeof defaultValueOrMap === 'function') [map, defaultValueOrMap] = [defaultValueOrMap, []];
  return Array.isArray(value)
      ? typeof map === 'function'
          ? value.map(map)
          : value
      : defaultValueOrMap;
}

export function toArray(value, defaultValueOrMap = [], map) {
  value = Array.isArray(value) ? value : value ? [value] : void 0;
  return getArray(value, defaultValueOrMap, map);
}

export function findArray(value, predicate, defaultValueIndex = -1) {
  if (!Array.isArray(value)) return void 0;
  if (Array.isArray(predicate)) predicate = {[predicate[0]]: predicate[1]};
  if (predicate && typeof predicate === 'object') {
    const entry = Object.entries(predicate);
    predicate = (item) => entry.every(([key, value]) => item[key] === value);
  }
  if (typeof predicate !== 'function') return void 0;

  const index = Math.max(value.findIndex(predicate), defaultValueIndex);
  return index === -1 ? void 0 : value[index];
}

export function stringToArray(value, separatorOrMap = ',', map) {
  if (!value || typeof value !== 'string') return [];

  if (typeof separatorOrMap === 'function') [map, separatorOrMap] = [separatorOrMap, ','];
  return getArray(value.split(separatorOrMap).filter(Boolean), map);
}