CollectionUtils.ts 1.93 KB
import LinkList from '@ohos.util.List';
import HashMap from '@ohos.util.HashMap';

/**
 * CollectionUtils class.
 */

export class CollectionUtils {
  /**
   *  The Array utils tag.
   */
  private static readonly TAG: string = 'CollectionUtils';

  /**
   * Check collection is empty or not.
   * @param collection any[]
   * @returns  {boolean} true(empty)
   */
  static isEmpty(collection?: any[]): boolean {
    return !collection || collection.length === 0;
  }

  // static isEmptyList<T>(list1?: LinkList<T>): boolean {
  //   return !list1 || list1.length === 0;
  // }
  //
  // static isEmptyHashMap(obj?: HashMap<any, any>): boolean {
  //   if (!obj) {
  //     return true;
  //   }
  //   return obj.isEmpty();
  // }
  //
  // static isEmptyMap(obj?: Map<any, any>): boolean {
  //   if (!obj) {
  //     return true;
  //   }
  //   return Object.keys(obj).length === 0 && obj.constructor === Object;
  // }
  //
  // static isEmptyRecord(obj?: Record<string, string>): boolean {
  //   if (!obj) {
  //     return true;
  //   }
  //   return Object.keys(obj).length === 0 && obj.constructor === Object;
  // }

  /**
   * Check collection is empty or not.
   * @param collection any[]
   * @returns  {boolean} true(not empty)
   */
  static isNotEmpty(collection?: any[]): boolean {
    if (!collection) {
      return false
    }
    return collection.length > 0;
  }

  static getLength(collection?: any[]): number {
    return CollectionUtils.isEmpty(collection) ? 0 : collection.length;
  }

  static getElement(collection?: any[], index?: number): any {
    if (CollectionUtils.isEmpty(collection) || index === undefined) {
      return null;
    }
    return index >= 0 && index < collection.length ? collection[index] : null;
  }

  static isArray(value: any): boolean {
    if (typeof Array.isArray === 'function') {
      return Array.isArray(value);
    } else {
      return Object.prototype.toString.call(value) === '[object Array]';
    }
  }
}