Last active
July 4, 2019 12:34
-
-
Save minikin/9a7bbcb6dc07a40546743a3b0958966f to your computer and use it in GitHub Desktop.
Reduce boilerplates for operator == and hashCode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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