Skip to content

Instantly share code, notes, and snippets.

@minikin
Last active July 4, 2019 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minikin/9a7bbcb6dc07a40546743a3b0958966f to your computer and use it in GitHub Desktop.
Save minikin/9a7bbcb6dc07a40546743a3b0958966f to your computer and use it in GitHub Desktop.
Reduce boilerplates for operator == and hashCode
/// Generates a hash code for multiple [objects].
int hashValues(Iterable objects) => _finish(
objects.fold(0, (hash, element) => _combine(hash, element.hashCode)));
// Jenkins hash functions
int _combine(int hash, int value) {
hash = 0x1fffffff & (hash + value);
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
return hash ^ (hash >> 6);
}
int _finish(int hash) {
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
hash = hash ^ (hash >> 11);
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
class Item {
final String id;
final String title;
final int numberOfparts;
final double weight;
final bool composable;
const Item({
this.id,
this.title,
this.numberOfparts,
this.weight,
this.composable,
});
@override
bool operator ==(dynamic other) =>
identical(other, this) ||
other.id == id &&
other.title == title &&
other.numberOfparts == numberOfparts &&
other.weight == weight &&
other.composable == composable;
@override
int get hashCode =>
hashValues([id, title, numberOfparts, weight, composable]);
}
void main() {
final item1 = Item(
id: '1',
title: 'Item 1',
numberOfparts: 5,
weight: 10.45,
composable: true);
final item2 = Item(
id: '1',
title: 'Item 1',
numberOfparts: 5,
weight: 10.45,
composable: true);
item1 == item2 ? print('Equal') : print('Not Equal');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment