parseVectorText function

Vector parseVectorText(
  1. String s
)

Parse a vector from text of the form [1, 2, 3.5]. Accepts any JSON array of numbers.

Implementation

Vector parseVectorText(String s) {
  final trimmed = s.trim();
  if (trimmed.isEmpty) {
    throw const FormatException('empty vector literal');
  }
  final decoded = jsonDecode(trimmed);
  if (decoded is! List) {
    throw FormatException('vector literal must be a JSON array, got $decoded');
  }
  final buf = Float32List(decoded.length);
  for (var i = 0; i < decoded.length; i++) {
    final e = decoded[i];
    if (e is num) {
      buf[i] = e.toDouble();
    } else {
      throw FormatException('vector element $i is not a number: $e');
    }
  }
  return Vector(buf);
}