[Construcción ecológica] -js consejos de juicio

0, referencia

Descripción : a partir de varios puntos fáciles de obtener, expanda y amplíe gradualmente la aplicación para garantizar la confiabilidad del código

1. Determine si es de un tipo determinado

// 判断是否为 null
const isNull = o => {
    
    
  return o === null;
};

// 判断是否为 undefined
const isUndefined = o => {
    
    
  return o === undefined;
};

// 判断是否为 null or undefined
const isNil = o => {
    
    
  return isNull(o) || isUndefined(o);
};

// 判断是否为 string
const isString = o => {
    
    
  return !isNil(o) && (typeof o === 'string' || o instanceof String);
};

// 判断是否为 number
const isNumber = o => {
    
    
  return !isNil(o) // 不为 null or undefined
    && (
      (!isNaN(o) && isFinite(o)
        && typeof o === 'number'
      ) || o instanceof Number);
};

// 判断是否为 boolean
const isBoolean = o => {
    
    
  return !isNil(o) && (typeof o === 'boolean' || o instanceof Boolean);
};

// 判断是否为 array
const isArray = o => {
    
    
  return !isNil(o) && Array.isArray(o);
}

// 判断是否为 object
const isObject = o => {
    
    
  return ({
    
    }).toString.call(o) === '[object Object]';
}

// 判断 o 为 O 的实例
const isType = (o, O) => {
    
    
  return !isNil(o) && o instanceof O;
}

// 判断是否为 set
const isSet = o => {
    
    
  return isType(o, Set);
}

// 判断是否为 map
const isMap = o => {
    
    
  return isType(o, Map);
}

// 判断是否为 date
const isDate = o => {
    
    
  return isType(o, Date);
}

2. Determine si está vacío

Se pueden usar números y cadenas o.length === 0para determinar, se usan tipos de Conjunto y Mapa o.size === 0, y se usan tipos de Objeto Object.keys(o).length === 0para determinar, de la siguiente manera:

// 判断是否为空
const isEmpty = o => {
    
    
  if (isArray(o) || isString(o)) {
    
    
    return o.length === 0;
  }

  if (isSet(o) || isMap(o)) {
    
    
    return o.size === 0;
  }

  if (isObject(o)) {
    
    
    return Object.keys(o).length === 0;
  }

  return false;
}

3. Obtén el elemento i-th

Principalmente lista, mapa, tipos de conjuntos

// 获取列表的第i项
const getXItem = (i, list) => {
    
    
  if (!isArray(list) || !isSet(list) || !isMap(list)) {
    
    
    return undefined;
  }

  if (isArray(list)) {
    
    
    return list.slice(i)[0] || undefined;
  }
  if (isSet(list)) {
    
    
    return Array.from(list).slice(i)[0] || undefined;
  }
  if (isMap(list)) {
    
    
    return Array.from(list.value()).slice(i)[0] || undefined;
  }
}

// 获取列表的最后一项
const getLastItem = list => {
    
    
	return getXItem(-1, list);
}

Supongo que te gusta

Origin blog.csdn.net/piano9425/article/details/112388356
Recomendado
Clasificación