Generate Nested Map from Path String in dart - dart

I want to create a map using the path
generateNestedMap("foo.bar.baz", "someValue")
and the output should be
Output: {'foo'{'bar':{'baz': 'someValue'}}}

Run this in dartpad. No recursion required. Just build it from inside-out:
void main() {
print(generateNestedMap("foo.bar.baz", "someValue"));
}
Map generateNestedMap(String path, String payload) {
var steps = path.split('.');
Object result = payload;
for (var step in steps.reversed) {
result = {step : result};
}
return result as Map;
}
EDIT: Or, as I suggested in one of the comments, a little fancier, but cool:
void main() {
print(generateNestedMap("foo.bar.baz", "someValue"));
}
Map generateNestedMap(String path, String payload) {
var steps = path.split('.');
var result = steps.reversed.fold(payload, (old, next) => {next: old});
return result as Map;
}

Related

Invoke top level function with dart:mirrors

I'm struggling with how to invoke a top level function in dart. I'd like to be able to annotate a function with #Route, find all the Route annotations, then check that the annotation is on a method, and then call that method by its symbol.
What I have so far is:
class Route {
final String url;
const Route(this.url);
}
#Route('/')
void handle() {
print('Request received');
}
void main() {
var mirrorSystem = currentMirrorSystem();
var lm = mirrorSystem.isolate.rootLibrary;
for (var mirror in lm.declarations.values) {
var metadata = mirror.metadata;
for (var im in metadata) {
if (im.reflectee is Route) {
print('Route found');
// how to invoke the function handle associated with the route annotation?
}
}
}
}
From this point i'm not sure how I would then call the method. If it was a class then I could use invoke and pass in the Symbol for the method, but that doesn't work as it's not a class.
Can anyone give me some clues? Information about the mirrors library in dart is fairly sparse unfortunately.
I worked this out. For anyone who finds this, you use the LibraryMirror on rootLibrary to invoke the top level function:
void main() {
var mirrorSystem = currentMirrorSystem();
var lm = mirrorSystem.isolate.rootLibrary;
for (var mirror in lm.declarations.values) {
var metadata = mirror.metadata;
for (var im in metadata) {
if (im.reflectee is Route && mirror is MethodMirror) {
lm.invoke(mirror.simpleName, []);
// prints 'Request received'
}
}
}
}

Conditional member access for map children?

Lets say you are trying to access deeply nested children in a map and you are not able to expect their parents to be there. Example:
Map awesomeMap = {
"this":{
"is":{
"sometimes":"not here"
}
}
}
Map notAwesomeMap = {
"this":{
"haha":{
"we":"switched"
}
}
}
When I go to access notAwesomeMap['this']['is']['sometimes'] it will return an error because ['this']['is'] is null, and you cannot look for the value ['sometimes'] of null.
So that's fine, but I was hoping to be able to use conditional member access operators...
notAwesomeMap['this']?.['is']?.['sometimes']
but that doesn't work...
Short of wrapping everything in a try block, is there a good way to handle these situations?
Edit: I tried playing around with this and I didn't find anything really illuminating, but maybe this gives someone an idea
void main() {
Map nestedMap = {
'this':{
'is':{
'sometimes':'here'
}
}
};
final mapResult = nestedMap['this'];
print(mapResult); //returns {is: {sometimes: here}}
final nullResult = nestedMap['this']['is an'];
print(nullResult); // returns null
final nullifiedResult = nullify(nestedMap['this']['is an']['error']);
print(nullifiedResult); // returns error, but is this possible another way?
final errorResult = nestedMap['this']['is an']['error'];
print(errorResult); // returns error
}
nullify(object){
try {
final result = object;
return result;
}
catch (e) {
return null;
}
}
One way would be
final result = (((nestedMap ?? const {})['this'] ?? const {})['is an'] ?? const {})['error'];
See also Null-aware operator with Maps
You could write a simple function to help do what you want:
R lookup<R, K>(Map<K, dynamic> map, Iterable<K> keys, [R defaultTo]);
Example usage:
final result = lookup(inputMap, ['this', 'is', 'something']);
Example implementation:
https://dartpad.dartlang.org/1a937b2d8cdde68e6d6f14d216e4c291
void main() {
var nestedMap = {
'this':{
'is':{
'sometimes':'here'
}
}
};
print(lookup(nestedMap, ['this']));
print(lookup(nestedMap, ['this', 'is']));
print(lookup(nestedMap, ['this', 'is', 'sometimes']));
print(lookup(nestedMap, ['this', 'is', 'error']));
// Bail out on null:
print(lookup(nestedMap, ['error'], 'Default Value'));
}
R lookup<R, K>(Map<K, dynamic> map, Iterable<K> keys, [R defaultTo]) {
dynamic current = map;
for (final key in keys) {
if (current is Map<K, dynamic>) {
current = current[key];
} else {
return defaultTo;
}
}
return current as R;
}
I like #matanlurey's approach, but have made two changes:
Drop the defaultTo since you can still use ?? which is more readable.
Swallow type-cast errors.
R lookup <R, K>(Map<K, dynamic> map, Iterable<K> keys) {
dynamic current = map;
for (final key in keys) {
if (current is Map<K, dynamic>) {
current = current[key];
}
}
try{
return current as R;
} catch(e){
// do nothing
}
}
Usage is similar
String someValue = lookup(nestedMap, ['some', 'value']) ?? 'Default Value';

Flutter: Reading a file, parsing as JSON, then converting to an object in order to use dot notation

I am trying to make a way to read a file with data saved in a specific format, parse it to JSON then convert it to an object so that I can use dot notation.
The problem here is using dot notation as it just returns null
CoreData.dart
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
#proxy
class CoreObject {
Map _data;
CoreObject([String source]) {
Map json = (source == null) ? new Map() : JSON.decode(source);
_data = new Map.from(json);
json.forEach((k, v) {
print(k);
_data[k] = v;
});
}
static encode(List<CoreObject> list) {
String result = "";
for (CoreObject item in list) {
result += "${item.toString()};";
}
return result;
}
#override toString() {
print(this._data);
return JSON.encode(this._data);
}
#override
noSuchMethod(Invocation invocation) {
var name = invocation.memberName.toString().replaceFirst('Symbol(\"', "");
print("_data.keys ${_data.keys}");
print("_data.values ${_data.values}");
if (invocation.isGetter) {
print("name ${name.replaceAll("\")", "")}");
var ret = _data[name.replaceAll("\")", "")];
print("ret $ret");
print(ret.toString());
return ret;
}
if (invocation.isSetter) {
_data[name.replaceAll("=\")", "")] = invocation.positionalArguments.first;
} else {
super.noSuchMethod(invocation);
}
}
}
class Person extends CoreObject {
Person([source]): super(source);
#override noSuchMethod(Invocation invocation) {
super.noSuchMethod(invocation);
}
}
class CoreContainer {
String _object;
var returnNew;
var path;
_map(String source) {
var result = [];
for (var line in source.split(";")) {
// print("line $line");
if (line != "") result.add(returnNew(line));
}
print("result $result");
return result;
}
encode(List<CoreObject> list) {
// print("list $list");
String result = "";
list.forEach((CoreObject item) {
// print("item ${item.toString()}");
result += "${item};";
});
// print("result $result");
return result;
}
CoreContainer(this._object, this.returnNew);
Future<File> _getFile() async {
String dir = path ?? (await getApplicationDocumentsDirectory()).path;
this.path = dir;
return new File('$dir/$_object.txt');
}
Future<List<CoreObject>> getAll() async {
return _getFile().then((File file) {
String contents = file.readAsStringSync();
print("contents $contents");
return this._map(contents);
})
.catchError((Error error) {
print('error: $error');
_getFile().then((File file) {
file.writeAsStringSync("");
});
return [];
});
}
save(List<CoreObject> data) async {
_getFile().then((file) {
try {
file.writeAsStringSync(this.encode(data));
}
catch (error) {
print("error: $error");
}
}).catchError((Error error) {
print("error: $error");
});
}
clear() async {
return _getFile().then((file) {
file.writeAsStringSync("");
}).catchError((Error error) {
print("error: $error");
});
}
Future<List<CoreObject>> get(query) async {
return this.getAll().then((List data) {
data.retainWhere(query);
return data;
}).catchError((error) {
print("error: $error");
});
}
Future<List<CoreObject>> remove(query) async {
return this.getAll().then((List data) {
// print(data);
data.removeWhere(query);
save(data);
return data;
}).catchError((error) {
print("error: $error");
});
}
Future<List<CoreObject>> add(obj) async {
return this.getAll().then((data) {
data.add(obj);
return save(data).then(() {
return data;
})
.catchError((Error error) {
throw error;
});
}).catchError((Error error) {
print("error: $error");
});
}
}
Using it:
CoreContainer corePerson = new CoreContainer("Person", (source) => new Person(source));
corePerson.getAll().then((List<CoreObject> array) {
var tempItems = [];
var i = 0;
print("array $array");
while (i < array.length) {
Person person = array[i];
print(person); //{"name":"<whatever 'i' is>"}
print(person.name); //null
tempItems.add(new ListTile(
title: new Text("$i"),
subtitle: new Text("${person.name}"),
));
i++;
}
print(tempItems.length);
count = tempItems.length;
setState(() {
items = tempItems;
});
}).catchError((Error error) {
print("error: $error, ${error.stackTrace}");
});
Code is hard to read because of a lot of print debugging.
But I suppose you need a way to convert JSON data into a Dart class.
You should use library like jaguar_serializer that do the job for you.
https://pub.dartlang.org/packages/jaguar_serializer
Dart doesn't use dot notation like dynamic languages (Python, JavaScript). In Python and JavaScript, for example, every single object is actually internally a HashMap, and . is actually a hash lookup of the property name:
a.bar // Loosely the same as a.lookup('bar')
The Python/JS VM though can "see" that a.bar is used like a property on a class-like object a, and optimize it to use a true property/field access - this is part of the "optimization" phase of a JIT (just-in-time compiler).
It is features like this that make it almost impossible to ahead-of-time compile either Python or JS - they require runtime profile information to generate fast code. Dart (and specifically Dart 2.0) is implementing a sound type system where a.bar, when a is known, is always a property accessor, not a hash lookup.
That means at runtime you can't take an arbitrary hash map and force it to act like an object, which is why your code seems awkward. I'd recommend using code generation if you need a typed object with . notation, or settling for a HashMap [] if you do not.
Check also mapping json into class objects answers for example of clean basic way of json -> dart class mapping.

How to implement dynamic properties in Dart?

I would like to be able to back a dynamic property with a Map using a lookup in noSuchMethod(). However the latest changes makes the incoming property reference name unavailable. I can understand the minification scenario requiring us to use Symbols rather than Strings for names, but this makes implementing serializable dynamic properties difficult. Anyone have good ideas on how to approach this problem?
I can't use String names since the String names are not fixed between calls to the minifier. (This would completely break serialization)
You can access the original name with MirrorSystem.getName(symbol)
So a dynamic class could look like :
import 'dart:mirrors';
class A {
final _properties = new Map<String, Object>();
noSuchMethod(Invocation invocation) {
if (invocation.isAccessor) {
final realName = MirrorSystem.getName(invocation.memberName);
if (invocation.isSetter) {
// for setter realname looks like "prop=" so we remove the "="
final name = realName.substring(0, realName.length - 1);
_properties[name] = invocation.positionalArguments.first;
return;
} else {
return _properties[realName];
}
}
return super.noSuchMethod(invocation);
}
}
main() {
final a = new A();
a.i = 151;
print(a.i); // print 151
a.someMethod(); // throws
}
You could do something like this:
import 'dart:json' as json;
main() {
var t = new Thingy();
print(t.bob());
print(t.jim());
print(json.stringify(t));
}
class Thingy {
Thingy() {
_map[const Symbol('bob')] = "blah";
_map[const Symbol('jim')] = "oi";
}
final Map<Symbol, String> _map = new Map<Symbol, String>();
noSuchMethod(Invocation invocation) {
return _map[invocation.memberName];
}
toJson() => {
'bob': _map[const Symbol('bob')],
'jim': _map[const Symbol('jim')]};
}
Update - dynamic example:
import 'dart:json' as json;
main() {
var t = new Thingy();
t.add('bob', 'blah');
t.add('jim', 42);
print(t.bob());
print(t.jim());
print(json.stringify(t));
}
class Thingy {
final Map<Symbol, String> _keys = new Map<Symbol, String>();
final Map<Symbol, dynamic> _values = new Map<Symbol, dynamic>();
add(String key, dynamic value) {
_keys[new Symbol(key)] = key;
_values[new Symbol(key)] = value;
}
noSuchMethod(Invocation invocation) {
return _values[invocation.memberName];
}
toJson() {
var map = new Map<String, dynamic>();
_keys.forEach((symbol, name) => map[name] = _values[symbol]);
return map;
}
}
If you only need "dynamic properties", it should be enough to use Symbols as keys in the Map. If you also want to serialize that map, then you need to keep track of the original String names and use those for serialization. When deserializing, you'd have to create new Symbols from those Strings.
Note that all these scenarios (and basically everything that involves new Symbol) require a compiler to create a mapping of original names to the minified ones and put this mapping into the program, which of course makes it bigger.
Thanks for the solution of #Alexandre Ardhuin, I made some modification to make it runnable.
import 'dart:mirrors';
class object {
final _properties = new Map<String, Object>();
object();
object.from(Map<String, Object> initial) {
initial.entries.forEach((element) => _properties[element.key] = element.value);
}
noSuchMethod(Invocation invocation) {
if (invocation.isAccessor) {
final realName = MirrorSystem.getName(invocation.memberName);
if (invocation.isSetter) {
// for setter realname looks like "prop=" so we remove the "="
final name = realName.substring(0, realName.length - 1);
_properties[name] = invocation.positionalArguments.first;
return;
} else {
return _properties[realName];
}
}
return super.noSuchMethod(invocation);
}
#override
String toString() {
return _properties.toString();
}
}
main() {
// we can't use var or object type here, because analysis will consider
// https://dart.dev/tools/diagnostic-messages#undefined_setter
// The setter 'i' isn't defined for the type 'object'
// So dynamic is required here!
dynamic a = object.from({'a': 123, 'b': 234});
a.i = 151;
print(a); // print {a: 123, b: 234, i: 151}
try {
a.someMethod(); // throws NoSuchMethodError
} catch (e) {
print(e);
}
}

Using streamreader to read line containing this "//"?

Read a Text file having any line starts from "//" omit this line and moved to next line.
The Input text file having some seprate partitions. Find line by line process and this mark.
If you are using .Net 3.5 you can use LINQ with a IEnumerable wrapped around a Stream Reader. This cool part if then you can just use a where statement to file statmens or better yet use a select with a regular expression to just trim the comment and leave data on the same line.
//.Net 3.5
static class Program
{
static void Main(string[] args)
{
var clean = from line in args[0].ReadAsLines()
let trimmed = line.Trim()
where !trimmed.StartsWith("//")
select line;
}
static IEnumerable<string> ReadAsLines(this string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
...
//.Net 2.0
static class Program
{
static void Main(string[] args)
{
var clean = FilteredLines(args[0]);
}
static IEnumerable<string> FilteredLines(string filename)
{
foreach (var line in ReadAsLines(filename))
if (line.TrimStart().StartsWith("//"))
yield return line;
}
static IEnumerable<string> ReadAsLines(string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
I'm not sure what you exactly need but, if you just want to filter out // lines from some text in a stream... just remember to close the stream after using it.
public string FilterComments(System.IO.Stream stream)
{
var data = new System.Text.StringBuilder();
using (var reader = new System.IO.StreamReader(stream))
{
var line = string.Empty;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
if (!line.TrimStart(' ').StartsWith("//"))
{
data.Append(line);
}
}
}
return data.ToString();
}
Class SplLineIgnorStrmReader:StreamReader // derived class from StreamReader
SplLineIgnorStrmReader ConverterDefFileReadStream = null;
{
//created the Obj for this Class.
Obj = new SplLineIgnorStrmReader(strFile, Encoding.default);
}
public override string ReadLine()
{
string strLineText = "", strTemp;
while (!EndOfStream)
{
strLineText = base.ReadLine();
strLineText = strLineText.TrimStart(' ');
strLineText = strLineText.TrimEnd(' ');
strTemp = strLineText.Substring(0, 2);
if (strTemp == "//")
continue;
break;
}
return strLineText;
This is if u want to read the Text file and omit any comments from that file(here exclude "//" comment).

Resources