Skip to content

Commit

Permalink
Add equality and hash override #5
Browse files Browse the repository at this point in the history
  • Loading branch information
avdosev committed Nov 6, 2022
1 parent 5c2937c commit 06b4361
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,8 @@
## [0.3.0] - Add equality and hash override

Either now overrides equality and hash.
> Thanks to @memishood for creating the [issue](https://github.com/avdosev/either_dart/issues/5)
## [0.2.0] - Update Future[Either]

Updated to support `FutureOr<T>` instead of `Future<T>`:
Expand Down
11 changes: 11 additions & 0 deletions lib/src/either.dart
Expand Up @@ -82,6 +82,17 @@ abstract class Either<L, R> {
static Either<L, R> condLazy<L, R>(
bool test, Lazy<L> leftValue, Lazy<R> rightValue) =>
test ? Right(rightValue()) : Left(leftValue());

@override
bool operator ==(Object obj) {
return this.fold(
(left) => obj is Left && left == obj.value,
(right) => obj is Right && right == obj.value,
);
}

@override
int get hashCode => fold((left) => left.hashCode, (right) => right.hashCode);
}

/// Used for "failure"
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
@@ -1,6 +1,6 @@
name: either_dart
description: Error handler library for type-safe and easy work with errors on Dart and Flutter. Either is an alternative to Nullable value and Exceptions.
version: 0.2.0
version: 0.3.0
homepage: https://github.com/avdosev
repository: https://github.com/avdosev/either_dart

Expand Down
43 changes: 43 additions & 0 deletions test/either_test.dart
Expand Up @@ -102,4 +102,47 @@ void main() {
.isRight,
true);
});

group('equal', () {
test('Left and Left', () {
final x = Left('test');
final z = Left('test');
expect(x, z);
expect(x.hashCode, z.hashCode);
expect(x == z, true);
expect(x != z, false);
expect(Left('1111'), isNot(equals(Left('2222'))));
expect(Left('1111'), equals(Left('1111')));
expect(Left(null), Left(null));
expect(Left(null).hashCode, Left(null).hashCode);
});

test('Right and Left', () {
final x = Right('test');
final z = Left('test');
expect(x != z, true);
expect(x == z, false);

expect(Left('1111'), isNot(equals(Right('2222'))));
expect(Left('1111'), isNot(equals(Right('1111'))));
expect(Right('1111'), isNot(equals(Left('2222'))));
expect(Right('1111'), isNot(equals(Left('1111'))));
expect(Left(null), isNot(equals(Right(null))));
expect(Right(null), isNot(equals(Left(null))));
});

test('Right and Right', () {
final x = Right('test');
final z = Right('test');

expect(x, z);
expect(x.hashCode, z.hashCode);
expect(x == z, true);
expect(x != z, false);
expect(Right('1111'), isNot(equals(Right('2222'))));
expect(Right('1111'), equals(Right('1111')));
expect(Right(null), Right(null));
expect(Right(null).hashCode, Right(null).hashCode);
});
});
}

0 comments on commit 06b4361

Please sign in to comment.