import isStr from './isStr';
import isArr from './isArr';
import isUdf from './isUdf';

/**
 * 数组或字符串去重
 * @param {Array|string} value
 * @param {boolean|Array} condition Array，表示按数组元素属性去重；boolean，表示是否不匹配数组元素的类型
 *
 * @returns {*}
 *
 * @example
 * unique('abbcddefaa');             // => 'abcdef'
 * unique(['a', 'b', 'a', 'd']);     // => ['a', 'b', 'd']
 * unique([1, 3, 1, 5, '1']);        // => [1, 3, 5, '1']
 * unique([1, 3, 1, 5, '1'], true);  // => [1, 3, 5]
 *
 * const arr = [
 *   {name: 'Tom', age: 28},
 *   {name: 'Bob', age: 28},
 *   {name: 'Tom', age: 32},
 * ]
 * unique(arr, ['age']);  // => [{name: 'Tom', age: 28}, {name: 'Tom', age: 32}]
 */
function unique(value, condition) {
  var isValStr = isStr(value);
  if (isValStr) value = value.split('');
  if (!isArr(value)) value = [];
  var arr = value.slice();
  var i = -1;

  while (++i < arr.length) {
    var j = i;

    var _loop = function _loop() {
      var ai = arr[i],
          aj = arr[j],
          isCdArr = isArr(condition);

      // eslint-disable-next-line
      var isDup = !isCdArr && (condition ? ai == aj : ai === aj) || isCdArr && condition.some(function (p) {
        return ai && aj && !isUdf(ai[p]) && ai[p] === aj[p];
      });
      if (isDup) arr.splice(j--, 1);
    };

    while (++j < arr.length) {
      _loop();
    }
  }

  return isValStr ? arr.join('') : arr;
}

export default unique;
