Skip to content

Instantly share code, notes, and snippets.

@lrhn
lrhn / expiring_cache.dart
Created October 5, 2021 09:13
Dart expiring cache
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: BSD-3-Clause
/// Cache for a value which invalidates itself after a predetermined duration.
///
/// The cache will store a [value], but after a specified keep-alive duration
/// has passed, the cache will invalidate itself and no longer provide access
/// to the cached value.
///
/// Reading [value] will return either the cached value, or `null` if the
@lrhn
lrhn / index_lookup_benchmark.dart
Last active February 19, 2021 23:25
Comparison of List.[] and List.elementAt.
main() async {
var list = [for (var i = 0; i < 10000; i++) i.isEven ? i : -i];
for (var i = 0; i < 5; i++) {
print("elementAt : ${bench1(list)}/ms");
await Future((){}); // Don't block browser.
print("operator[]: ${bench2(list)}/ms");
await Future((){});
}
}
@lrhn
lrhn / example.dart
Created February 17, 2021 10:11
Example of assigning callable object to nullable function type.
class C {
void call([int? x]) {
print("works!");
}
}
typedef VoidCallback = void Function();
void main() {
VoidCallback? f = C();
@lrhn
lrhn / conditional-rewrites.dart
Last active February 17, 2021 09:55
Conditional Expression With Boolean Literal Rewrites
// If you use a conditional expression, `e1 ? e2 : e3`,
// where one of the expressions is a boolean literal (`true` or `false),
// then you can (and *should*) always rewrite it to a shorter expression
// using only `||` or `&&`, and possibly an `!`.
void testConditionals(bool e1, bool e2) {
// Conditional Rewrite
expect( e1 ? e2 : false , e1 && e2 );
expect( e1 ? e2 : true , !e1 || e2 );
expect( e1 ? false : e2 , !e1 && e2 );
@lrhn
lrhn / perffunc.dart
Last active October 5, 2020 09:17
Compare local function to instance method or static method.
var a = -4;
int logicToGetA() => a;
class A {
final int flag;
A(this.flag);
int foo() {
int a = logicToGetA();
@lrhn
lrhn / null_safety_promotion.dart
Last active September 16, 2020 09:27
Dart Null Safety Promotion
main([args]) {
String? x = args == null ? 'foo' : null;
{
String? y = x;
ignore(y!); // Promotes along non-throwing branch;
print(y.length);
}
{
String? y = x;
@lrhn
lrhn / stream_load_balancer.dart
Created August 20, 2020 17:30
Dart load-balancing stream extension.
import "dart:async";
import "dart:collection" show Queue;
extension StreamExtension<T> on Stream<T> {
/// Create a load balanced stream.
///
/// A load balanced stream can be listened to multiple times,
/// and events are spread across actively listeninng
/// (non-cancelled, non-paused) subscriptions in a round-robin
/// order.
@lrhn
lrhn / stream_load_balancer.dart
Created August 19, 2020 20:16
Stream Load Balancer
import "dart:async" show StreamController, StreamSubscription;
import "dart:collection" show Queue;
/// Stream splitter with load balancing.
///
/// Spreads the events of one stream onto as many streams as
/// desired. Events are delivered in round-robin order to
/// all currently interested target streams.
///
/// Add a new potential target stream using [createTarget].
@lrhn
lrhn / cancelable_zone.dart
Created July 24, 2020 11:34
A cancelable zone which stops further async computations from running when it's cancelled
import "dart:async";
/// A cancelable zone.
///
/// A [Zone], and a [cancel] function which makes the zone stop processing events.
/// After calling [cancel], the zone's timers, microtasks and `run` methods
/// ([Zone.run], [Zone.runUnary] and [Zone.runBinary]) stop doing anything.
/// Calling the `run` methods will throw, and any scheduled timers or
/// microtasks will do nothing instead of calling the configured callback.
class CancelableZone {
@lrhn
lrhn / paraminfer.dart
Created January 16, 2020 12:30
Example: Inference of type argument based on arguments only.
void f<T>(List<T> value, List<T> value2) {
print("f<$T>(${value.runtimeType}, ${value2.runtimeType})");
}
main() {
f([2], [3]);
f([2], [3.1]);
f(["a"], [2]);
f([true], [null]);
}