File

projects/wms-framework/src/lib/baseframework/DictionaryFactory.ts

Description

Class to instantiate dictionaries at runtime.

Index

Methods

Constructor

Private constructor()

Creates an instance of DictionaryFactory.

Methods

Static create
create(keyType: ClassType, _valueType: ClassType)
Type parameters :
  • K
  • V

Instantiates the correct dictionary type, according to the key and value types.

Parameters :
Name Type Optional
keyType ClassType No
_valueType ClassType No
Returns : Dictionary<K, V>

{Dictionary<K,V>}

Private Static isPrimitive
isPrimitive(type: ClassType)

Checks if the given type is a primitive data type, except for undefined, which will return false.

Parameters :
Name Type Optional
type ClassType No
Returns : boolean

{boolean}

import { Dictionary } from './Dictionary';
import { GeneralDictionary } from './GeneralDictionary';
import { Hashable, HashUtils } from './Hashable';
import { ClassType } from './ReflectionSupport';
import { SimpleDictionary } from './SimpleDictionary';

/**
 * Class to instantiate dictionaries at runtime.
 *
 * @export
 * @class DictionaryFactory
 */
export class DictionaryFactory {
  /**
   * Creates an instance of DictionaryFactory.
   *
   * @private
   * @memberof DictionaryFactory
   */
  private constructor() {}

  /**
   * Instantiates the correct dictionary type,
   * according to the key and value types.
   *
   * @static
   * @template K
   * @template V
   * @param {ClassType} keyType
   * @param {ClassType} _valueType
   * @return {*}  {Dictionary<K,V>}
   * @memberof DictionaryFactory
   */
  static create<K, V>(
    keyType: ClassType,
    _valueType: ClassType
  ): Dictionary<K, V> {
    if (DictionaryFactory.isPrimitive(keyType)) {
      return new SimpleDictionary<K, V>();
    } else if (HashUtils.isHashable(keyType)) {
      return new GeneralDictionary<Hashable, V>() as any;
    } else if (keyType == null) {
      throw new Error(
        'Key type is `null` or `undefined`. This may indicate that dictionary initialization should be moved out of `constructor` into `withGenericTypes()` function.'
      );
    }

    console.warn('Key type for dictionary is not primitive nor hashable:');
    console.warn(keyType);
    console.warn(
      'Key type must implement `Hashable` interface or be a primitive type to avoid this warning.'
    );
    return new SimpleDictionary<K, V>();
  }

  /**
   * Checks if the given type is a primitive data type, except for `undefined`,
   * which will return false.
   *
   * @private
   * @static
   * @param {ClassType} type
   * @return {*}  {boolean}
   * @memberof DictionaryFactory
   */
  private static isPrimitive(type: ClassType): boolean {
    return (
      type === String ||
      type === Number ||
      type === Boolean ||
      type === BigInt ||
      type === Symbol
    );
  }
}

result-matching ""

    No results matching ""