I wish to store if a specific date is loaded via Javascript. How this boolean is saved/accessed has no difference, however I'm not sure as to what the best solution is performance-wise.
I could know I could store it like this and loop through each object, however I guess this wouldn't really be efficient.
var loaded = { {d:23, m:11, y:2012}, {d:24, m:11, y:2012} };
Another idea I have is to store this in an array, like so:
loaded[2012][11][23] = true;
But I'm sure there are better ways to accomplish this, so I'd appreciate any guidance
Unless you have to list available years, available months or available days, you could always use an Object as a dictionary for storing dates as UNIX timestamp numbers (which you can convert to and from Date objects) or "YYYYMMDD" strings.
Related
There is a users: any[] = [] array in my angular code which will be filled up dynamically with the person objects.
someMethod.subscribe((user) => {
this.users.push(user);
})
But one of my colleagues preferred the below approach to push the object
someMethod.subscribe((user) => {
this.users.push(JSON.parse(JSON.stringify(user)));
})
May I know - which would be the best approach & why?
The former. The latter is sometimes used to deep-clone an object, but if you're not modifying the objects in the array, there's no need. And it also carries some risks: you can lose some data that's not available in JSON, such as functions, regex, symbols, and undefined; you could end up with some altered data, like NaN becoming null, and it'll mess with dates depending on the date format. It's also slow (compared to methods from utility libraries): Financial Times did a writeup on their tech blog in 2018 showing that having a JSON.parse(JSON.stringify(... on the data returned from every request slowed their site down by 10 times.
If you do need to clone the objects before pushing them, you could use a library like Lodash, or use push({...user}), depending on your exact needs.
I'm trying to write to Firestore all the prices from different stocks. Structure should look something like this (although this might not be the best fitted for it, still thinking of it as in SQL) :
const d1 = new Date();
const result = d1.getTime();
console.log('Epochtime',result);
database.collection("stock1").doc("exchange1").collection(date).doc('prices').set({"price":"price_value"})
Now the problem is that I can't create a collection with a name that's a variable that contains date. I tried all the different types of it and I presumed that epoch time should work, as this is a number like: 1636213439908. I always get the error: Value for argument "collectionPath" is not a valid resource path. Path must be a non-empty string. Although the exact same variable can be written as a value in a collection. So not sure what am I doing wrong here.
Document IDs in Firestore must be strings, so you'll have to convert the data to a string. While date.toString() will work, I highly recommend using a ISO-8601 format for the dates, such as date.toISOString(). These formats are designed to be both humanly readable and machine sortable.
Take for example a case where I have thousands of students.
So I'd have an array of objects.
students = [
{ "name":"mickey", "id","1" },
{ "name":"donald", "id","2" }
{ "name":"goofy", "id","3" }
...
];
The way I currently save this into my localstorage is:
localStorage.setItem('students', JSON.stringify(students));
And the way I retrieve this from the localstorage is:
var data = localStorage.getItem('students');
students = JSON.parse(data);
Now, whenever I make a change to a single student, I must save ALL the
students to the localStorage.
students[0].name = "newname";
localStorage.setItem('students', JSON.stringify(students));
I was wondering if it'd be better instead of keeping an array, to maybe have
thousands of variables
localStorage.setItem('student1', JSON.stringify(students[0]));
localStorage.setItem('student2', JSON.stringify(students[1]));
localStorage.setItem('student3', JSON.stringify(students[2]));
...
That way a student can get saved individually without saving the rest?
I'll potentially have many "students".. Thousands. So which way is better,
array or many variables inside the localstorage?
Note: I know I should probably be using IndexedDB, but I need to use LocalStorage for now. Thanks
For your particular case it would probably be easier to store the students in one localStorage key and using JSON parse to reconstruct your object, add to it, then stringifying it again and it would be easier than splitting it up by each student to different keys.
If you don't have so many data layers that you really need a real local database like IndexedDB, a single key and a JSON string value is probably OK for your case.
There is limitation for the size of local storage and older browsers won't support it.
It is better to store in an array for couple reasons:
Can use loops to process them
No JSON needed
Always growable
I need to implement a simple way to handle localization about weekdays' names, and I came up with the following structure:
var weekdaysLegend=new Array(
{'it-it':'Lunedì', 'en-us':'Monday'},
{'it-it':'Martedì', 'en-us':'Tuesday'},
{'it-it':'Mercoledì', 'en-us':'Wednesday'},
{'it-it':'Giovedì', 'en-us':'Thursday'},
{'it-it':'Venerdì', 'en-us':'Friday'},
{'it-it':'Sabato', 'en-us':'Saturday'},
{'it-it':'Domenica', 'en-us':'Sunday'}
);
I know I could implement something like an associative array (given the fact that I know that javascript does not provide associative arrays but objects with similar structure), but i need to iterate through the array using numeric indexes instead of labels.
So, I would like to handle this in a for cycle with particular values (like j-1 or indexes like that).
Is my structure correct? Provided a variable "lang" as one of the value between "it-it" or "en-us", I tried to print weekdaysLegend[j-1][lang] (or weekdaysLegend[j-1].lang, I think I tried everything!) but the results is [object Object]. Obviously I'm missing something..
Any idea?
The structure looks fine. You should be able to access values by:
weekdaysLegend[0]["en-us"]; // returns Monday
Of course this will also work for values in variables such as:
weekdaysLegend[i][lang];
for (var i = 0; i < weekdaysLegend.length; i++) {
alert(weekdaysLegend[i]["en-us"]);
}
This will alert the days of the week.
Sounds like you're doing everything correctly and the structure works for me as well.
Just a small note (I see the answer is already marked) as I am currently designing on a large application where I want to put locals into a javascript array.
Assumption: 1000 words x4 languages generates 'xx-xx' + the word itself...
Thats 1000 rows pr. language + the same 7 chars used for language alone = wasted bandwitdh...
the client/browser will have to PARSE THEM ALL before it can do any lookup in the arrays at all.
here is my approach:
Why not generate the javascript for one language at a time, if the user selects another language, just respond(send) the right javascript to the browser to include?
Either store a separate javascript with large array for each language OR use the language as parametre to the server-side script aka:
If the language file changes a lot or you need to minimize it per user/module, then its quite archivable with this approach as you can just add an extra parametre for "which part/module" to generate or a timestamp so the cache of the javascript file will work until changes occures.
if the dynamic approach is too performance heavy for the webserver, then publish/generate the files everytime there is a change/added a new locale - all you'll need is the "language linker" check in the top of the page, to check which language file to server the browser.
Conclusion
This approach will remove the overhead of a LOT of repeating "language" ID's if the locales list grows large.
You have to access an index from the array, and then a value by specifying a key from the object.
This works just fine for me: http://jsfiddle.net/98Sda/.
var day = 2;
var lang = 'en-us';
var weekdaysLegend = [
{'it-it':'Lunedì', 'en-us':'Monday'},
{'it-it':'Martedì', 'en-us':'Tuesday'},
{'it-it':'Mercoledì', 'en-us':'Wednesday'},
{'it-it':'Giovedì', 'en-us':'Thursday'},
{'it-it':'Venerdì', 'en-us':'Friday'},
{'it-it':'Sabato', 'en-us':'Saturday'},
{'it-it':'Domenica', 'en-us':'Sunday'}
];
alert(weekdaysLegend[day][lang]);
I am using local storage to store user entries and am displaying the entries on another page. I need a way to sort them based on the most recent date and time of edit. Is there a way to do this with HTML5. If not, what's the easiest/most effective way to do so?
Thanks for the inputs.
If your keys/values have an inherent order to them (alphabetical, numerical, etc), then putting a timestamp in them may be superfluous. Although the Storage object has no sort method, you can create a new Array() and then sort that.
function SortLocalStorage(){
if(localStorage.length > 0){
var localStorageArray = new Array();
for (i=0;i<localStorage.length;i++){
localStorageArray[i] = localStorage.key(i)+localStorage.getItem(localStorage.key(i));
}
}
var sortedArray = localStorageArray.sort();
return sortedArray;
}
The disadvantage to this is that the array is not associative, but that is by nature of the JavaScript Array object. The above function solves this by embedding the key name into the value. This way its still in there, and the functions you'd use to display the sorted array can do the footwork of separating the keys from the values.
You've got to pair the timestamp with the stored value somehow, you can create a wrapper object for each value and store the value and the timestamp in a single object. Assuming you have a value myvalue you want to store with reference myref:
var d=new Date();
var storageObject = {};
storageObject.value = myvalue;
storageObject.timestamp = d.getTime();
localStorage.setItem(myref, JSON.stringify(storageObject));
On the other page you then need to rehydrate your objects into an array and implement your compareFunction function.
Your other option would be to use Web SQL Database and Indexed Database API which lets you more naturally store and query this sort of multifaceted info, but you would probably have to create some sort of abstract wrapper to make things work easily cross browser.