Backbone Relational collection with duplicate ids - backbone.js

I'm using backbone relational for my collection handling.
I have a complex object which may have duplicated ids inside. e.g.
{
id: "things/1",
children: [
{
id: "things/2",
children: [
{
id: "things/3",
children: null
}
]
},
{
id: "things/4",
children: [
{
id: "things/3",
children: null
}
]
},
]
}
I then try and use this as a relational collection, like so. (written in TypeScript).
constructor(options?) {
// ...
this.idAttribute = 'Id';
this.relations = [{
type: Backbone.HasMany,
key: 'Children',
relatedModel: 'Application.Models.MyModel',
collectionType: 'Backbone.Collection'
}
];
super(options);
}
As soon as I get duplicate ids from the server, however, BBR angrily throws an exception and things just don't happen. "Duplicate id!"
Should I be perhaps generating some sort of fake id based on a guid for these models? Or is there a way to tell the Backbone Relational store to stop enforcing this rule? Maybe I can just turn off the store altogether.
I'm not using this to do any collection fetches, fetch relateds, or anything like that. I'm really using it as a nice way of parsing a recursive data structure.
I've ran into this problem often when writing Jasmine tests as well, but managed to get around it by adding a random *10 multiplyer for each test to make sure the ids are different. But it's a pain in the neck to have to do this. So hopefully any fixes here will help me in unit testing as well.
I'm not averse to trying a different framework, but some models in my project use BBR, so it'd need to play nice. If there's something else out there that'd be more appropriate, feel free to suggest it, too.

Your data structure implies a strict tree-like relationship, while the data clearly isn't organized like that. Either make your data an actual tree, where each node is unique, or represent it with a structure that can handle more complex relationships.
I would suggest you just send the objects as a flat array, where each node has a childrenIds array. Then you can easily restore the children arrays after receiving the objects.

My eventual answer to this was to move to Backbone Associations. After writing a d.ts file (available on the DefinitelyTyped repository) and some initial refactoring to change the relations blocks, things pretty much work off the bat! The only thing you need to remember is to set any collections by default to an empty array in the defaults function of your model. Hope this helps someone!

Related

How to store an inclusion/exclusion list in Mongo without storing every single item to represent a selection of "All"

My app has geofencing functionality. In the UI there is a table which lets the user add a country to either the "blocked" or the "allowed" list. The overwhelming majority of objects in the collection do not need geofencing and thus by default all countries should be in the allowed list for a new object.
How do I represent the 3 possible states (all, some, none) in Mongo? The last two are obvious - an array containing either some 2 letter country codes, or none. But what about the first case? I feel like it would be a massive waste of bytes to store however many (200+) country codes for each object.
The two alternatives I can come up with are:
Using a value of object.allowed_countries = [ 1 ] which also doesn't scream right to me.
Or storing an additional property to represent the global "all".
object: {
geofencing: {
enabled: true | false,
blocked_countries: [ ]
}
}
Is there anything smarter I'm not thinking of?
Thank you in advance!

Looping twice through a data structure from DB bad idea, how else?

this is probably a more general programming question and something that has been on my mind.
I only have 1 year of experience, and recently started reading the book "Clean Code" and stumbling upon The Big 0 Notation.
These two things basically say that you should never loop through something twice (Loop inside of loop), because the performance is terrible (O(2n) if i remember correctly).
My question is this:
If i have this structure which is an array of all of the orders on my app, and inside of this array, there is an object, this object contains another array, which is the individual product that was in that order.
[
orderOne: {
products: [
{name: "Life advice", price: 399},
{name: "Test", price: 429},
],
userInformation: {
name: "John",
age: 21
}
}
]
Now in order to display all of the orders in my view, I would need to first loop through the total orders, and then inside of that loop, I loop through the products array inside, which creates this double loop.
How would this be avoided? It feels inevitable that there is going to be an array inside of an array for data storing, which would always then mean a double loop.
I am trying to get better at understanding ways of structuring things instead of going head first and just writing double loops everywere.
Thank you so much for your time!
Stay safe!
It really depends on what you're trying to achieve...
If you're just displaying the orders then does each order need to display each item all at the same time?
Would it not be more logical to display the items of an order once it is selected?
It's best to consider the scope of your data when thinking about how to manipulate it. This way, you're only handling data upon the user needing to access it, which should reduce loading/refresh times.
There will be times when nested loops are required, but many cases where it seems like it's required you can actually defer the consumption of the data until a later date when it becomes more relevant.
You could also have a separate array of products, each with an ID and then the order object just has a dictionary of product IDs and quantities. This can then be resolved into a full list for displaying fairly quickly.

React redux nested array update good practice and perfs

I'have one simple question.
I need to update my redux state. In this state i have an array with object into it. If i need to update the valid property.
(... represent dummy values)
myArray: [
{valid: false, ...},
{valid: false, ...},
...
]
I've seen people using the .map(item, index).
I've seen people using the immutable-helpers
And people doing it with myArray[index] = {myNewObject}.
My question is what's the best in terms of performences and good practice.
The map seems ok for small array but what if i have 12000 items ? The helpers add a library and the last one seems overkill to replace a complete object to update only on attribute of it.
If you have some clue, reading, info it would help me a lot to settle this dilema.
Thank you!

What is the name of the anti-pattern of using a js object/dictionary/map to implement an array/vector

For ease of notation, I will use JSON in the following, though the anti-pattern can be programmed in many languages
Let's say that I have a sensible JSON such as
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": 42,
"Items": [
"ValueOfItem0", "ValueOfItem1"
]
}
It has simple entries and an array of items. An alternative way of representing the data, which I think is an anti-pattern and for which I search the name is
{
"someProperty": "someValue",
"someOtherProperty": 42,
"Item0": "valueOfItem0",
"Item1": "valueOfItem1",
"NumberOfItems": 2
}
Instead of by the array, the items are kept 'together' by the keys, which a consumer of the anti-pattern JSON would need to predict. For this reason, the NumberOfItems property has been added, though by using a TryGet-like technique, the property can be made obsolete. Why would anyone do this? Limitations of the serializer.
Comments:
My search has revealed nothing. The sort-of opposite direction is the "Arrject", therefore my humble suggestion for the described anti-pattern, if yet unnamed, would be "Orray", a name already used by Star Wars.

How to define types for the todo reducer without editing the code itself?

Redux example todo app has todo reducer like this:
https://github.com/reactjs/redux/blob/master/examples/todos/src/reducers/todos.js#L23
ADD_TODO action works without the state, but TOGGLE_TODO requires the state. How can i write a flowtype for a reducer like that without editing the code itself?
https://flowtype.org/try/#0MYewdgzgLgBFIBMQwLwwBTQIZQKYBoYtgoBLcASlQD4YBvAKBhggHdSpgALDYs8AHRQAngAdcVRs2bAsEXDADkAQQAiqgPoAVAPKqdigFxNpzAE64oAVzNh6J081IJDREuTADn+B47wAPKFc+DyFcQJ9HaVAAW1EAG0tcFxgAMyx4+V9mAF9fWXklXQBxYoAZAFFtPQNjKNJUjGw8LwQYAEIUNBDBZ0ls6QtrWxYoHFwBvIGhmzspKJgBJeaCAZkQOMS8FPaVgViEpIRJ3wRcdKt4oOnLWdHxkzyp0EhYeCQIVCaxvC+AbQAuoQemAqChaPM2BxuLx3IIROJ+qYCgoVOpqvojDdhnY-mtFssfqsFnBECB0FYwGdUqQwMlgXDQQMAfk5KiSuUqrpMXVHDMRnsYlhROhYOD8e9yVAGfwmVEKKdzlhLtcovy7CtHgwpuFRCAzLBqcqrqSPkA
I'm not sure what you mean by "without editing the code itself." You need to add type annotations in some places for Flow to typecheck your code. Anyway, here are the types I came up with for your example:
type Action = {
type: 'ADD_TODO',
id: number,
text: string,
} | {
type: 'TOGGLE_TODO',
id: number,
};
type State = {
id: number,
completed: boolean,
}
Here's the complete tryflow. I don't think there is any good way to express to Flow that you will only pass undefined to todo when action.type is ADD_TODO. It would be better to restructure the code somewhat.
Keep in mind that Flow is not a silver bullet. It is a great tool for preventing bugs and making development easier, but in return for the static checking you have to give up some patterns that it cannot understand. You will find that you often have to structure your code around what Flow can understand (incidentally, I believe this leads to better design choices and makes it easier for humans to understand as well). Type safety isn't free, and this is a fundamental limitation of all typecheckers. So, don't expect that it will be able to check everything without you "editing the code itself."

Resources