utils

Overview

A collection of miscellaneous utility functions.

Summary

hashReturns a numeric hash of obj.
hashIterableReturns a numeric hash of the input iterable.
hashStringReturns a numeric hash of the input string.
keyExtracts a hash key from obj.

Detail

utils.hash(obj)

Returns a numeric hash of obj.

If obj is a number, it is simply returned.

If obj is a table with a __hash metamethod, that method is called with obj as an argument and the result is returned.

If obj is a table with no __hash metamethod, this function returns utils.hashString(tostring(obj)).

For all other cases, this function returns utils.hashString(tostring(obj)).

utils.hashIterable(iterable)

Returns a numeric hash of the input iterable.

This method accumulates the hash value by iterating, for each e in iter(iterable), hash = hash*prime + utils.hash(e).

If hash exceeds some large prime, it is reduced to math.mod(hash, largePrime) and accumulation continues.

The primes chosen for this function were selected arbitrarily.

utils.hashString(str)

Returns a numeric hash of the input string.

This method accumulates the hash value by iterating, for each index [1..string.len(str)], hash = hash*prime + string.byte(str, i).

If hash exceeds some large prime, it is reduced to math.mod(hash, largePrime) and accumulation continues.

utils.key(obj)

Extracts a hash key from obj.

If obj is not a table, it is simply returned. If obj is a table whose metatable, mt, has a __hash metamethod, mt.__hash(obj) is returned.

This is method is used to generate hash keys for HashMap and HashSet.