Skip to content

Commit

Permalink
computed_collections: fromPiecewiseComputed
Browse files Browse the repository at this point in the history
  • Loading branch information
mstniy committed Oct 2, 2024
1 parent 7f050c3 commit e967614
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
4 changes: 4 additions & 0 deletions packages/computed_collections/lib/computedmap.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ abstract class ComputedMap<K, V> {
factory ComputedMap.fromPiecewise(Iterable<K> domain, V Function(K key) f) =>
PiecewiseComputedMap(domain, f);

factory ComputedMap.fromPiecewiseComputed(
Iterable<K> domain, Computed<V> Function(K key) f) =>
ComputedMap.fromPiecewise(domain, f).mapValuesComputed((_, c) => c);

/// A computation representing the last change event on this map.
Computed<ChangeEvent<K, V>> get changes;

Expand Down
5 changes: 3 additions & 2 deletions packages/computed_collections/lib/src/piecewise.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ class PiecewiseComputedMap<K, V>
// This is not powerful enough to represent uncountably infinite domains :(
final Iterable<K> _domain;
final V Function(K) _f;
final _keyCache = ComputationCache<K, Option<V>>();
final _keyCache = ComputationCache<K, Option<V>>(assertIdempotent: false);
final _containsValueCache = ComputationCache<V, bool>();

PiecewiseComputedMap(this._domain, this._f) {
snapshot = $(() => IMap.fromKeys(keys: _domain, valueMapper: _f));
snapshot = Computed(() => IMap.fromKeys(keys: _domain, valueMapper: _f),
assertIdempotent: false);
}

Option<V> Function() _getKeyComputation(K key) =>
Expand Down
9 changes: 9 additions & 0 deletions packages/computed_collections/test/piecewise_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:computed/computed.dart';
import 'package:computed_collections/computedmap.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:test/test.dart';
Expand Down Expand Up @@ -58,4 +59,12 @@ void main() {
expect(await getValue(m[1]), 0);
expect(await getValue(m[-1]), null);
});

test('fromPiecewiseComputed works', () async {
expect(
await getValue(
ComputedMap.fromPiecewiseComputed([0, 1], (x) => $(() => x + 1))
.snapshot),
{0: 1, 1: 2}.lock);
});
}

0 comments on commit e967614

Please sign in to comment.