Dart - Map vs Switch statement performance - dictionary

In our flutter project, with use a lot of enums and extensions. Some of us write switch statements, some others use maps. I was wondering what practice is considered the best one in terms of time, memory etc ?
enum Animal { cat, dog, bird }
Switch statement:
extension AnimalExtension on Animal {
String get name {
switch (this) {
case Animal.cat:
return 'Cat';
case Animal.dog:
return 'Dog';
case Animal.bird:
return 'Bird';
}
}
}
Map:
extension AnimalExtension on Animal {
String get name => {
Animal.cat: 'Cat',
Animal.dog: 'Dog',
Animal.bird: 'Bird',
}[this];
}
Also, for the map method, is it better to create a static const Map instead of instantiating it on the fly at every call?

I wouldn't worry about speed for something this small, not unless it's at the heart of the inner loop of your computation.
The switch has the chance to be more time efficient, the map will likely have less code (it reuses the Map.[] code). The map should definitely be const.
If you want to optimize performance and code size, I'd go with:
String get name => const ['cat', 'dog', 'bird'][this.index];

Related

Will using selectors to compute derived data from an API call perform better than doing within the reducer? (for this use-case)

Say I have a music store app where the user searches for guitars. On initial page load, I fetch a few varieties of guitars to display: (acoustic, electric, and bass). Pages of guitar results are returned together from a single API call but will never be displayed together. Therefore, they must be filtered at some point. To view different categories of guitars, the user will toggle the category they view from a react component.
There seems to be two major ways I can approach this problem with immutable and redux.
In Strategy 1, I filter the data on category when it arrives, and store it separately in the redux store. When I want to retrieve the data, I specify the category in the selector.
In Strategy 2, all API data that comes in is stored in an aggregate List "all". When I want to retrieve a particular category of guitars, I used a selector to filter and display from the aggregated data.
STRATEGY 1:
// REDUCER
export const GuitarReducer = (state, action) => {
const { payload, type } = state;
switch (type) {
case "acoustic": {
let existing = // GET EXISTING
return state.set("acoustic",
existing.concat(payload.filter(result => (result.category === "acoustic")))
)
}
case "electric": {
let existing = // GET EXISTING
return state.set("electric",
existing.concat(payload.filter(result => (result.category === "electric")))
)
}
case "bass": {
let existing = // GET EXISTING
return state.set("bass",
existing.concat(payload.filter(result => (result.category === "bass")))
)
}
}
}
// SELECTOR
export const selectCategory = createSelector(
[getCategory, getGuitarReducer],
(category, guitarReducer) => {
return GuitarReducer.get(category);
}
);
STRATEGY 2:
// REDUCER
export const GuitarReducer = (state, action) => {
const { payload, type } = state;
...
let existing = // GET EXISTING
...
return state.set("all",
existing.concat(payload)
)
}
// SELECTOR
export const selectCategory = createSelector(
[selectAllGuitars],
(category, guitars) => {
return guitars.filter(guitar => (guitar.category = category));
}
);
Will one pattern give better performance than another? What pattern better follows best practices for redux?
I have heard that it is best to prefer selectors for computing derived data, and that memoization will cache the results to use when another action is performed on the data such as toggling between tabs. Because of this, it is not clear to me which strategy to prefer.
I think selectors mainly focused of not re-computing derived data in your components (and the benefit of reusing it across other components).
Both in your example are good practices, so I would reframe it as follows. Do you want your datastore to look like in choice one or choice two (original API response). Do you want it to lazily load (choice two), or load categories for all guitars.
Choice 1
Pros
Stores in datastore in format more useful to your application.
Choice two recomputes on category change, choice one is computed at start and most likely more performant.
Cons
No access to original API response.
Performs filtering and categorizing on API request instead of lazily (Honestly not a big problem).
Choice 2
Pros
Stores in datastore original API response.
Lazily computes the required guitar category.
Cons
Performs computation again on category change. (Note reselect only has a cache size of 1).
Memoizing also takes additional memory.

How should I deep-duplicate state data in Redux?

I have several instances of state where I need to support actions that duplicate some slice of state. For example, my product is a survey builder, so when I duplicate a question, I'd also like to duplicate its answers, rather than have multiple questions pointing to the same answer instances.
The state is normalized:
questionsById: {
q01: {
...
answers: ["a01"],
...
}
}
answersById: {
a01: {...}
}
When dispatching an action of QUESTION_DUPLICATE, I'd like to also duplicate any answers. Currently my QUESTION_DUPLICATE action creator also creates a mapped list of new answer keys, and then the answer reducer consumes this.
This pattern seems unwieldy to me, especially when considering the possibility of deeper duplications (for example, duplicating a Page, which contains Questions, which contain Answers...). Is there a better pattern for deeply duplicating normalized data?
The answer may revolve around how you normally handle normalizing and denormalizing your data. For example, in my blog post Practical Redux, Part 8: Form Draft Data Management, I reuse my existing normalization logic (which leverages the redux-orm library) to copy an item to be edited between the "current" and "draft" slices in my state. So, similarly, one approach would be to denormalize the question you want to duplicate, and then re-normalize it (in either the action creator or the reducer, as you see fit).
I settled on using normalizr & I came up with a recursive duplicator function. It accepts an entity, schema, and keygen function, & recursively updates any nested entities based on the schemata by giving them new ids. In the base case (when there are no further nested entities) it will return the basic thing with its key updated.
const duplicator = (entity, schema, keygen) => {
const newEntity = {
...entity,
[schema._idAttribute]: keygen(entity, schema)
};
if (Object.keys(schema.schema).length === 0) {
return newEntity;
}
return Object.keys(schema.schema).reduce(
(acc, nestedKey) => {
if (!entity.hasOwnProperty(nestedKey)) {
return acc;
}
if (!Array.isArray(schema.schema[nestedKey])) {
return {
...acc,
[nestedKey]: duplicator(
entity[nestedKey],
schema.schema[nestedKey],
keygen
)
};
}
return {
...acc,
[nestedKey]: acc[nestedKey].map((nestedEntity, index) =>
duplicator(nestedEntity, schema.schema[nestedKey][0], keygen)
)
};
},
{ ...newEntity }
);
};
export default duplicator;
This currently doesn't support the schema.Array setup of normalizr for multiple entity types in an array. I'm not currently using schema.Array and this case would be pretty non-trivial to support, but I'll consider it in the future.

Simple, clean way to sync observables from different view models

Say I have two view models that each have an observable property that represents different, but similar data.
function site1Model(username) {
this.username = ko.observable(username);
....
}
function site2Model(username) = {
this.username = ko.observable(username);
....
}
These view models are independent and not necessarily linked to each other, but in some cases, a third view model creates a link between them.
function site3Model(username) = {
this.site1 = new site1Model(username);
this.site2 = new site2Model(username);
// we now need to ensure that the usernames are kept the same between site1/2
...
}
Here are some options that I've come up with.
Use a computed observable that reads one and writes to both:
site3Model.username = ko.computed({
read: function() {
return this.site1.username(); // assume they are always the same
},
write: function(value) {
this.site1.username(value);
this.site2.username(value);
},
owner: site3Model
}
This will keep the values in sync as long as changes always come through the computed. But if an underlying observable is changed directly, it won't do so.
Use the subscribe method to update each from the other:
site3Model.site1.username.subscribe(function(value) {
this.site2.username(value);
}, site3Model);
site3Model.site2.username.subscribe(function(value) {
this.site1.username(value);
}, site3Model);
This works as long as the observables suppress notifications when the values are the same; otherwise you'd end up with an infinite loop. You could also do the check earlier: if (this.site1.username() !== value) this.site1.username(value); This also has a problem that the observables have to be simple (it won't work right if site1 and site2 themselves are observables).
Use computed to do the subscribe and updates:
site3Model.username1Updater = ko.computed(function() {
this.site1.username(this.site2.username());
}, site3Model);
site3Model.username2Updater = ko.computed(function() {
this.site2.username(this.site1.username());
}, site3Model);
This format allows us to have other dependencies. For example, we could make site1 and site2 observables and then use this.site1().username(this.site2().username()); This method also requires a check for equality to avoid an infinite loop. If we can't depend on the observable to do it, we could check within the computed, but would add another dependency on the observable we're updating (until something like observable.peek is available).
This method also has the downside of running the update code once initially to set up the dependencies (since that's how computed works).
Since I feel that all of these methods have a downside, is there another way to do this that would be simple (less than 10 lines of code), efficient (not run unnecessary code or updates), and flexible (handle multiple levels of observables)?
It is not exactly 10 lines of code (although you could strip it down to your liking), but I use pub/sub messages between view models for this situation.
Here is a small library that I wrote for it: https://github.com/rniemeyer/knockout-postbox
The basic idea is just to create a ko.subscribable and use topic-based subscriptions. The library extends subscribables to add subscribeTo, publishOn and syncWith (both publish and subscribe on a topic). These methods will set up the proper subscriptions for an observable to automatically participate in this messaging and stay synchronized with the topic.
Now your view models do not need to have direct references to each other and can communicate through the pubsub system. You can refactor your view models without breaking anything.
Like I said you could strip it down to less than 10 lines of code. The library just adds some extras like being able to unsubscribe, being able to have control over when publishing actually happens (equalityComparer), and you can specify a transform to run on incoming values.
Feel free to post any feedback.
Here is a basic sample: http://jsfiddle.net/rniemeyer/mg3hj/
Ryan and John, Thank you both for your answers. Unfortunately, I really don't want to introduce a global naming system that the pub/sub systems require.
Ryan, I agree that the subscribe method is probably the best. I've put together a set of functions to handle the subscription. I'm not using an extension because I also want to handle the case where the observables themselves might be dynamic. These functions accept either observables or functions that return observables. If the source observable is dynamic, I wrap the accessor function call in a computed observable to have a fixed observable to subscribe to.
function subscribeObservables(source, target, dontSetInitially) {
var sourceObservable = ko.isObservable(source)
? source
: ko.computed(function(){ return source()(); }),
isTargetObservable = ko.isObservable(target),
callback = function(value) {
var targetObservable = isTargetObservable ? target : target();
if (targetObservable() !== value)
targetObservable(value);
};
if (!dontSetInitially)
callback(sourceObservable());
return sourceObservable.subscribe(callback);
}
function syncObservables(primary, secondary) {
subscribeObservables(primary, secondary);
subscribeObservables(secondary, primary, true);
}
This is about 20 lines, so maybe my target of less than 10 lines was a bit unreasonable. :-)
I modified Ryan's postbox example to demonstrate the above functions: http://jsfiddle.net/mbest/vcLFt/
Another option is to create an isolated datacontext that maintains the models of observables. the viewmodels all look to the datacontext for their data and refer to the same objects, so when one updates, they all do. The VM's dependency is on the datacontext, but not on other VMs. I've been doing this lately and it has worked well. Although, it is much more complex than using pub/sub.
If you want simple pub/sub, you can use Ryan Niemyer's library that he mentioned or use amplify.js which has pub/sub messaging (basically a messenger or event aggregator) built in. Both are lightweight and decoupled.
In case anyone needed.
Another option is to create a reference object/observable.
This also handle object that contains multiple observable.
(function(){
var subscriptions = [];
ko.helper = {
syncObject: function (topic, obj) {
if(subscriptions[topic]){
return subscriptions[topic];
} else {
return subscriptions[topic] = obj;
}
}
};
})();
In your view models.
function site1Model(username) {
this.username = syncObject('username', ko.observable());
this.username(username);
....
}
function site2Model(username) = {
this.username = syncObject('username', ko.observable());
this.username(username);
....
}

How to work with async code in Mongoose virtual properties?

I'm trying to work with associating documents in different collections (not embedded documents) and while there is an issue for that in Mongooose, I'm trying to work around it now by lazy loading the associated document with a virtual property as documented on the Mongoose website.
The problem is that the getter for a virtual takes a function as an argument and uses the return value for the virtual property. This is great when the virtual doesn't require any async calls to calculate it's value, but doesn't work when I need to make an async call to load the other document. Here's the sample code I'm working with:
TransactionSchema.virtual('notebook')
.get( function() { // <-- the return value of this function is used as the property value
Notebook.findById(this.notebookId, function(err, notebook) {
return notebook; // I can't use this value, since the outer function returns before we get to this code
})
// undefined is returned here as the properties value
});
This doesn't work since the function returns before the async call is finished. Is there a way I could use a flow control library to make this work, or could I modify the first function so that I pass the findById call to the getter instead of an anonymous function?
You can define a virtual method, for which you can define a callback.
Using your example:
TransactionSchema.method('getNotebook', function(cb) {
Notebook.findById(this.notebookId, function(err, notebook) {
cb(notebook);
})
});
And while the sole commenter appears to be one of those pedantic types, you also should not be afraid of embedding documents. Its one of mongos strong points from what I understand.
One uses the above code like so:
instance.getNotebook(function(nootebook){
// hey man, I have my notebook and stuff
});
While this addresses the broader problem rather than the specific question, I still thought it was worth submitting:
You can easily load an associated document from another collection (having a nearly identical result as defining a virtual) by using Mongoose's query populate function. Using the above example, this requires specifying the ref of the ObjectID in the Transaction schema (to point to the Notebook collection), then calling populate(NotebookId) while constructing the query. The linked Mongoose documentation addresses this pretty thoroughly.
I'm not familiar with Mongoose's history, but I'm guessing populate did not exist when these earlier answers were submitted.
Josh's approach works great for single document look-ups, but my situation was a little more complex. I needed to do a look-up on a nested property for an entire array of objects. For example, my model looked more like this:
var TransactionSchema = new Schema({
...
, notebooks: {type: [Notebook]}
});
var NotebookSchema = new Schema({
...
, authorName: String // this should not necessarily persist to db because it may get stale
, authorId: String
});
var AuthorSchema = new Schema({
firstName: String
, lastName: String
});
Then, in my application code (I'm using Express), when I get a Transaction, I want all of the notebooks with author last name's:
...
TransactionSchema.findById(someTransactionId, function(err, trans) {
...
if (trans) {
var authorIds = trans.notebooks.map(function(tx) {
return notebook.authorId;
});
Author.find({_id: {$in: authorIds}, [], function(err2, authors) {
for (var a in authors) {
for (var n in trans.notebooks {
if (authors[a].id == trans.notebooks[n].authorId) {
trans.notebooks[n].authorLastName = authors[a].lastName;
break;
}
}
}
...
});
This seems wildly inefficient and hacky, but I could not figure out another way to accomplish this. Lastly, I am new to node.js, mongoose, and stackoverflow so forgive me if this is not the most appropriate place to extend this discussion. It's just that Josh's solution was the most helpful in my eventual "solution."
As this is an old question, I figured it might use an update.
To achieve asynchronous virtual fields, you can use mongoose-fill, as stated in mongoose's github issue: https://github.com/Automattic/mongoose/issues/1894

What is the equivalent of foreach (with keys) in ActionScript

I am looking for the equivalent of a foreach loop with keys in Actionscript. In PHP this would be:
foreach($array as $key => $value)
{
}
I found two solutions that will work, but I am wondering if there is a better way to do this. The first solution is to use the for..in loop. Which gives you the keys, but you still have to use the key to access the correct element in your structure. For example:
for(var key:String in results)
{
trace(key + ": " + results[key]);
}
The second option is the for each..in loop, which I believe is new in AS3. With this solution, I can't tell what the keys are. For example:
for each(var row:* in results)
{
trace(row);
}
For the time being, I am going to use for..in. I am just looking for a better way.
Thanks,
Rob
Update: Speed is not a huge deal, because the array is never going to be extremely large. Order does matter, and I would like to get keys in the order of insertion. Here is an example of the array:
sites = {'site1': 34, 'site2': 52, 'site3': 66}
I would like to use the key as well as the value of each entry.
I want to keep my array structure as simple as possible. I could change the sites array above to look like:
sites = {{'name': 'site1', 'id': 34},
{'name': 'site2', 'id': 52},
{'name': 'site3', 'id': 66}}
However, I would rather not go this route, because it adds more dimensions to my array structure.
It depends on your object type. If you're using a Dictionary, you have:
DictionaryUtil.getKeys(myObject)
I wouldn't use for...in unless you're just dumping or purely want the keys and nothing else. It is an object so sort isn't guaranteed and will vary. If sorting isn't an issue, this (for...in or dictionary) is your best bet.
Grant speaks more on dictionary here: http://www.gskinner.com/blog/archives/2006/07/as3_dictionary.html.
for(var i:String in myArray) // loops through the items in the array
myArry[i] += 'new message will show'
for each(var i:String in myArray) // creates a copy of the array as it loops
myArray[i] += 'this change will not show outside the loop';
The later is great for if you need to minipulate the variables during the loop but want to preserve the original object for the rest of your program. Especially handy for formatting or translating values for a specific part of your program.

Resources