HTML5 local storage sort - javascript

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.

Related

Dynamic Array in Local Session

I'm having issues with the logic of using Local session variables. So I understand that HTML5 allows you to set and get these local storage variables.
I've read through this post: adding objects to array in localStorage
and understood that by using SetItem, you will rewrite the variable that you have set and thus for a dynamic array, you will need to get the variable first before pushing a new value.
So the problem I'm having, and I dont't even know if it's possible, is that I want to have, for example, a index.html page which accepts a user input and adds it into an array that needs to be persistent. When the user reloads the same page, the previous input will still be in the same array. From what I read from the post mentioned previously, you will rewrite the variable if you use SetItem. However, if I don't use setItem, how will I be able to specify that the array is to be a local Storage variable... I'm sorry if I confused anyone... because I am quite confused myself. Thanks in advance.
All of your assumptions are correct. You can only write to localStorage using setItem, and when setItem is called, you overwrite whatever value exist there. Therefore, the only way to add an item to an array in localStorage is to get the array from localStorage, manipulate it and then put it back with the new items.
// Check if we already have an array in local storage.
var x = localStorage.getItem("myArray");
// If not, create the array.
if (x === null) x = [];
// If so, decode the array.
else x = JSON.parse(x);
// Add our new item.
x.push("value 1");
// Encode the array.
x = JSON.stringify(x);
// Add back to LocalStorage.
localStorage.setItem("myArray", x);
This could done by the following approach:
var myInput = document.getElementById("myInput").value; // user data
var myList = JSON.parse(localStorage.getItem("myList")); // retrieve the list from LS
if(!Array.isArray(myList)) { // if LS list is not ok, instantiate new array
myList = [];
}
myList.push(myInput); // append user data to the list
localStorage.setItem("myList", JSON.stringify(myList)); // save the list back to LS

Is there something similar to sessionStorage but with multidimensional keys?

I'd like to save off values of a tree-like structure locally, then retrieve them based on user interaction. After some research, I found that sessionStorage (or localStorage) might be a good way to go about doing this. But I'm having trouble saving nested data.
Normally you have:
sessionStorage['key'] = 'someString';
I tried to implement something like:
sessionStorage['key1'] = [];
sessionStorage['key1']['key2'] = 'someString';
but I got an undefined error.
I've checked out few other storage libraries, but they only offer that single key-value pair option. Is there anything I'm missing?
Use JSON to serialise the nested data into a string, then decode it when you need to access it as an object...
var nested = {some:{nested:'object'}}
var asJson = JSON.stringify(nested)
sessionStorage['data'] = asJson
var asObject = JSON.parse(sessionStorage['data'])
From developer.mozilla.com:
The DOM Storage mechanism is a means through which string key/value
pairs can be securely stored and later retrieved for use.
Hence I think you cannot store array/dictionary directly in session storage. I highly suggest you that check this link out:
https://developer.mozilla.org/en-US/docs/DOM/Storage

High performance JS map for int-string pairs

I need a high performance map in Javascript (hashmap or whatever) that maps int(s) to string(s). The map would be used to build some sections of the webpage after dom is ready. I know simple javascript object also works like a map but I need to work with best performance.
I would like to initialize the map with all data pairs just at once by appending a string to the webpage while generating the response page from server.
Any ways how to improve performance of javascript map for int- string pairs or are there any implementations for the same ?
--
Using jQuery 1.7
Ok, I'll post it here since it's more of an answer:
Use an array. Taken into account that any implementation will have to use js primitives and objects, you'll be hard pressed to find something more performant than that.
Arrays in most (all?) implementations of javascript can be sparse. So array.length will return the index of last element + 1, but in sparse case the array will not have all elements allocated and will use object property semantics to access it's elements (meaning, it's effectively a hashtable with ints as keys).
It basically gives you the behavior you're looking for.
In case of negative ints, use a second array.
In relation to a single statement initialization: you can't do it in general, since it bases itself on implicitly knowing the item index.
What you can do is to append something along the lines:
var arr = [];
arr[int1] = val1;
arr[int2] = val2;
arr[int3] = val3;
arr[int4] = val4;
...
arr[intn] = valn;
I mean you have to list (Number, String) pairs somehow anyway.
Please check out this jperf test case, and draw your conclusion.
Objects are also sparse. Arrays are simply specialized objects that account for their own length among other things.
I think you should use the following
var l_map = {};
to add an element use
l_map[<your integer>] = <your string>
and to retrieve is
var l_value = l_map[<your integer>];
This is one way to solve your problem.
The second way is quite simple just use an array (or list) because it stores the values based on position as follows:
var l_array = [];
to add element at the last use : l_array.push(<your string>);
to add element at a specified position : l_array.splice(<position>,0,<your string>);
and to retrieve use : l_array[<posit>];

Storing dynamic dates in javascript

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.

Storing JS arrays and objects in a database

I have an application that lets users build things in JS. I want the user to be able to save the current state of his work to reuse it or share it, but what he has is a collection of JS objects stored in a JS array, with very different properties (color, label, x/y position, size, etc.).
SQL seems terrible for that particular task, forcing me to maintain tables for every different object, and alas I know very little about NoSQL database. What tools would you use to perform this ? MongoDB sounds promising but before I learn a whole new DB paradigm I want to be sure that I am heading in the right direction.
Object to string:
You can store your objects in the DB as a JSON string. Here's a simple example:
var foo = new Object();
foo.Name = "James";
foo.Gender = "Male";
//Result: {"Name":"James","Gender":"Male"}
var stringRepresentation = window.JSON.stringify(foo);
Here's a working fiddle.
String to object:
To convert your string back to an object, simply call window.JSON.parse():
var myObject = window.JSON.parse(stringRepresentation);
Here's a working fiddle.
If you have no interest in quering the objects for their various properties but only persist them to save state, you can serialize the entire array to JSON and store it in any db you like as one string.
What's on the server?
Most languages have mature JSON implementations that convert JavaScript objects to native types, which you can then easily store in a SQL database.

Categories