Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Last active October 12, 2020 11:17
Show Gist options
  • Save alexcmgit/7f08eb7d6debab20e240d6ddadcef588 to your computer and use it in GitHub Desktop.
Save alexcmgit/7f08eb7d6debab20e240d6ddadcef588 to your computer and use it in GitHub Desktop.
import 'package:url_launcher/url_launcher.dart';
import 'dart:math';
class Utils {
static int randomInt(int min, int max) {
final random = Random();
return random.nextInt(max - min + 1) + min;
}
static Function debounce<T>(Function f, Duration wait) {
Timer timer;
void debouncedFunction([T arg]) {
if (timer?.isActive ?? false) {
timer.cancel();
}
timer = Timer(wait, () => arg != null ? f(arg) : f());
}
return debouncedFunction;
}
static double randomDouble(double min, double max) {
final random = Random();
return ((max - min) * random.nextDouble()) + min;
}
static double Function(double xA) interpolate(
{List<double> xInterval, List<double> yInterval}) {
double x0 = xInterval[0];
double x1 = xInterval[1];
double y0 = yInterval[0];
double y1 = yInterval[1];
double getValueOfInterpolatioAt(double xA) {
if (xA > x1) {
xA = x1;
} else if (xA < x0) {
xA = x0;
}
double yA = y0 + (y1 - y0) * ((xA - x0) / (x1 - x0));
return yA;
}
return getValueOfInterpolatioAt;
}
static List<T> shuffleArray<T>(List<T> array) {
var currentIndex = array.length;
var tempValue;
var randomIndex;
while (0 != currentIndex) {
randomIndex = (Random().nextDouble() * currentIndex).floor();
currentIndex -= 1;
tempValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = tempValue;
}
return array;
}
static List getFlatList(List list) {
List internalList = List();
list.forEach((e) {
if (e is List) {
internalList.addAll(getFlatList(e));
} else {
internalList.add(e);
}
});
return internalList;
}
static Future<void> openUrl(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw Exception('Could not launch $url');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment