File

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

Description

Interface for objects which can be used in hash structures (like Dictionary).

Index

Methods

Methods

Equals
Equals(obj: any)
Parameters :
Name Type Optional
obj any No
Returns : boolean
GetHashCode
GetHashCode()
Returns : number
import { ClassType } from './ReflectionSupport';

/**
 * Interface for objects which can be used in hash structures (like `Dictionary`).
 *
 * @export
 * @interface Hashable
 */
export interface Hashable {
  GetHashCode(): number;
  Equals(obj: any): boolean;
}

/**
 * Contains utilitary functions related to hashing.
 *
 * @export
 * @class HashUtils
 */
export class HashUtils {
  /**
   * Creates an instance of HashUtils.
   *
   * @private
   * @memberof HashUtils
   */
  private constructor() {}

  /**
   * Check if the given class type implements the `Hashable` interface.
   *
   * @static
   * @param {ClassType} type
   * @return {*}  {boolean}
   * @memberof HashUtils
   */
  static isHashable(type: ClassType): boolean {
    return (
      typeof (type as any)?.prototype?.Equals === 'function' &&
      typeof (type as any)?.prototype?.GetHashCode === 'function'
    );
  }

  /**
   * Calculates a hash code for the given string.
   *
   * @static
   * @param {string} input
   * @return {*}  {number}
   * @memberof HashUtils
   */
  static stringToHash(input: string): number {
    let hash = 0;
    for (let i = 0; i < input.length; i++) {
      hash = input.charCodeAt(i) * 31 + hash * 2;
    }
    return hash;
  }
}

result-matching ""

    No results matching ""