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 0 : T _asType<T>(value) { 8 : return switch (T) { 9 0 : int => int.tryParse(value) as T, 10 0 : double => double.tryParse(value) as T, 11 0 : String => value.toString() as T, 12 : _ => null as T, 13 : }; 14 : } 15 : 16 0 : Map<T, K> toMap<T, K>() { 17 0 : final data = length > 0 ? substring(1, length - 1).split(',') : []; 18 0 : final Map<T, K> result = {}; 19 0 : for (final pair in data) { 20 0 : final parts = pair.split(':'); 21 0 : if (parts.length != 2 || parts[0] == null) { 22 : continue; 23 : } 24 0 : final key = _asType<T>(parts[0].trim()); 25 0 : result[key] = _asType<K>(parts[1].trim()); 26 : } 27 : return result; 28 : } 29 : 30 0 : String _wrap() { 31 0 : if (contains('{')) { 32 0 : RegExp pattern = RegExp(r"(\w+):\s*([\w\.\- ]+)"); 33 0 : return replaceAllMapped(pattern, (match) { 34 0 : String key = match.group(1) ?? '_'; 35 0 : String value = match.group(2)?.trim() ?? ''; 36 0 : return '"$key": ${num.tryParse(value) ?? '"$value"'}'; 37 : }); 38 : } 39 : return this; 40 : } 41 : 42 0 : List<T> toList<T>() { 43 0 : final data = length > 0 ? json.decode(_wrap()) : []; 44 0 : final List<T> result = []; 45 0 : for (final value in data) { 46 0 : 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 : }