Line data Source code
1 : // Copyright 2023 The terCAD team. All rights reserved. 2 : // Use of this source code is governed by a CC BY-NC-ND 4.0 license that can be found in the LICENSE file. 3 : 4 : import 'dart:convert'; 5 : 6 : extension MapExt on String { 7 1 : T _asType<T>(value) { 8 : return switch (T) { 9 2 : int => int.tryParse(value) as T, 10 2 : double => double.tryParse(value) as T, 11 2 : String => value.toString() as T, 12 : _ => null as T, 13 : }; 14 : } 15 : 16 1 : Map<T, K> toMap<T, K>() { 17 7 : final data = length > 0 ? substring(1, length - 1).split(',') : []; 18 1 : final Map<T, K> result = {}; 19 2 : for (final pair in data) { 20 1 : final parts = pair.split(':'); 21 3 : if (parts.length != 2 || parts[0] == null) { 22 : continue; 23 : } 24 3 : final key = _asType<T>(parts[0].trim()); 25 4 : result[key] = _asType<K>(parts[1].trim()); 26 : } 27 : return result; 28 : } 29 : 30 1 : String _wrap() { 31 1 : if (contains('{')) { 32 1 : RegExp pattern = RegExp(r"(\w+):\s*([\w\.\- ]+)"); 33 2 : return replaceAllMapped(pattern, (match) { 34 1 : String key = match.group(1) ?? '_'; 35 2 : String value = match.group(2)?.trim() ?? ''; 36 3 : return '"$key": ${num.tryParse(value) ?? '"$value"'}'; 37 : }); 38 : } 39 : return this; 40 : } 41 : 42 1 : List<T> toList<T>() { 43 5 : final data = length > 0 ? json.decode(_wrap()) : []; 44 1 : final List<T> result = []; 45 2 : for (final value in data) { 46 1 : result.add(value); 47 : } 48 : return result; 49 : } 50 : 51 0 : T toEnum<T>(List<T> values) => values.firstWhere((e) => e.toString() == this); 52 : 53 0 : int toInt() => int.parse(this); 54 : }