store a function within the confines of localstorage

I am currently working with objects that contain data to be displayed and manipulated in a browser. I want to store this data in local storage. To achieve this, I have been using JSON.stringify() to convert the objects into text, which has proven successful.

{
"bindingRef": [],
"primo": {
    "name": "primo",
    "modifiable": true,
    "binded": false,
    "isInteger": false,
    "label": "Numero di Primi"
},
"secondo": {
    "name": "secondo",
    "modifiable": true,
    "binded": false,
    "isInteger": false,
    "label": "Numero di Secondi"
}
}

Now, I am attempting to save a function by converting it to a string before storing it:

JSON.stringify(myFunction.toString());

However, the output looks like this:

"savedFunction": "function () {\n\t\t\t\tvar tot = menu.primo.get() * 6 + menu.secondo.get() * 8 + menu.dolce.get() * 4;\n\t\t\t\tif (menu.sconto.get()) {\n\t\t\t\t\treturn tot * 0.90;\n\t\t\t\t} else {\n\t\t\t\t\treturn tot;\n\t\t\t\t}\n\t\t\t}"

Is this the correct method for saving a function in local storage? Are there alternative approaches that may be more effective? If this is indeed the right way, is there a simple way to remove any tabs or indentation from the string, perhaps through the use of a regular expression?

Answer №1

In JavaScript, functions, like in many other functional languages, act as closures: they contain within them the contents of the environment scope at the time of definition, which includes temporary data such as database or file handles.

However, this can pose problems when it comes to JSON deserialization behavior. Therefore, it is important to carefully assess what is encompassed within the function and what needs to be explicitly defined.

For more insights on this topic, check out this SO thread.

Answer №2

If you want to store functions in localStorage, you can encapsulate the function within an object and utilize custom functions like storage.set and storage.get instead of using the standard localStorage.set and localStorage.get (as localStorage does not support adding functions directly, unlike JSON)..

The storage.set function will serialize an object containing functions before using localStorage.setItem().
Similarly, the storage.get function will deserialize an object containing functions after retrieving it with localStorage.getItem().

To enable functions to be stored, I have tailored the JSON.stringify and JSON.parse functions so that they can handle functions as well. This way, you can integrate these modified functions into other parts of your code seamlessly without any name changes. I have simply appended a 2 to the original functions for convenience.

JSON.stringify2 = JSON.stringify;
JSON.parse2 = JSON.parse;

JSON.stringify = function(value) {
    return JSON.stringify2(value, function(key, val) {
        return (typeof val === 'function') ? val.toString().replace(/\t|\n/g, '') : val;
    });
}

JSON.parse = function(value) {
    return JSON.parse2(value, function(key, val) {
        if (typeof val === 'string') {
            var regex = /^function\s*\([^()]*\)\s*{.*}$/;

            if (regex.exec(val) !== null)
                return eval('key = ' + val);
            else
                return val;
        } else
            return val;
    });
}

var storage = {};

storage.set = function(key, value) {
    if (typeof value === 'object')
        value = JSON.stringify(value);

    localStorage.setItem(key, value);
}

storage.get = function(key) {
    var value = localStorage.getItem(key);

    try {
        return JSON.parse(value);
    } catch (e) {
        return value;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...

Extract particular elements from an array and transform them into a new array

Presented below is an array: [{ "title": "Apple iPhone 7 Plus 32 GB", "category": "phone", "brand": "apple", "condition": "Used", "price": 800, "id": 0, "description": "Apple" }, { "title": "Apple Ipad Air 32 GB", "category": "tablet", "brand ...

Generating dynamic dropdown lists with JavaScript for variable arrays

I've been scouring the internet for quite some time now, both on this platform and through Google searches, but I can't seem to find what I'm looking for. (Apologies if I missed it and this comes across as a repetitive or annoying question.) ...

Guide to formatting the timestamp in outgoing JSON

Lately, I've been immersed in exploring Go and it truly is remarkable. One thing that has me scratching my head (even after scouring through documentation and blogs) is how to customize the formatting of the time.Time type when it's encoded using ...

Sending element information to jQuery.post callback function

My goal is to have this.item of an instance of the class filled with data received through the jQuery.post successor function. Currently, I am achieving this by using another user-defined function to set this.item with the received data. Query: Is there a ...

The ng-options loop in the array is unable to locate the specified value

In my C# controller, I generate a list and translate it to Json for Angular to receive at the front end. However, when using ng-options to loop through this array in order to get the array value, I always end up with the index instead. <select class="s ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

What are the steps to get an Angular.js application ready for deployment on Heroku?

I recently created an Angular.js quiz application by following a tutorial video. Although the app is functional on Mozilla Developer Edition, I have encountered issues with other browsers when running it locally. The root directory of my app includes the ...

I'm having issues with my Express.js API not being able to access the specified

My Express js server is not reading the res.body.signatureRequestId property. How can I submit this property to prevent the type error? I have shared my error log, JSON response, and Express js code below. Error log: { account: { account_id: ' ...

I'm encountering a problem with my vuejs application

I am currently working on a new vuejs 2 app and encountered an unexpected error. ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/Customers.vue Module build failed: S ...

Omitting the "undefined" values from an array enclosed within square brackets

Here is the array that I am working with. I am currently trying to remove the undefined value in row 2 of the array before tackling the duplicate square brackets issue. Despite attempting various methods, I am struggling to eliminate the undefined value - ...

Type Script is throwing an unidentified error being encountered

I am a beginner in Type Script and I'm attempting to convert a small piece of javascript code into typescript, but I keep encountering an error: typeError list[i] is undefined. Here is my original js code: function handleDragStart(e) { this.style.o ...

I am currently developing a project using vue-cli, and I have noticed that it takes a significant amount of time to build every time it refreshes. I am looking for a solution to prevent this delay

Working with the vue-cli2.9+ version of my project, I found that every time I started the project or made changes to the code, it would take a considerable amount of time for the modules to build before running the project again. I was looking for ways t ...

jQuery Ajax Redirect Form

I am currently developing an HTML application with a form. Upon clicking the submit button, I initiate a server-side call using jquery.ajax(). However, when the server returns an exception, such as a Status Code 500, I need to display an error message on t ...

The old DLL is causing a reference error when called upon

While working with a TwitchLib reference and utilizing Newtonsoft.Json 7.0.0, I encountered an error every time I visited the page that calls Twitch lab. The error message displayed is: "Could not load file or assembly 'Newtonsoft.Json, Version=7.0.0 ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

When trying to encode a JSON object with `json_encode`, it will return `

Issue occurs in my code where I create an array and encode it with json_encode. Strangely, json_encode returns null for this array unless I include the line "echo $responce->rows[0][0];" before encoding. If I remove this line, json_encode returns null! ...

Update the URL for the source of the Server-Sent event

Is there a way to modify the source set in the declaration of EventSource? I attempted this approach: var source = new EventSource("/blahblah.php?path=" + (window.location.pathname)); // A few lines below... source.url = "/blahblah.php?path=" + url; Nev ...

Adding Logging Features in ASP.NET

I am currently working with an .ascx file that contains both JavaScript and div elements. I need to add a log statement inside a function for troubleshooting purposes. Can someone please guide me on how to achieve this? Below is a snippet of my code: fu ...

Add up the monthly totals of an array of objects using JavaScript

I have a set of objects arranged in the following manner: var json = [ { day: '01-01-2018', hour: '00:00', value: '121' }, { day: '01-02-2018', hour: '05:24', value: '131' }, { day: '26-01-2 ...