Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts

    Multiple conditions - is this right?

    FYI: THIS IS NOT HOMEWORK!

    Hi all,

    I am trying to make an all-in-one function that can use local storage and provide 4 functions:

    (1) read data
    (2) write data
    (3) erase specific data
    (4) erase all data

    Here's the code block I have (with alerts in place of the local storage code for debugging):

    Code:
    var storage = function (name, value) {
        if (name) {
            if (value === null) {
                return alert('erase');
            } else {
                if (value != null) {
                    return alert('write');
                } else {
                    return alert('read');
                }
            }
        } else {
            return alert('nuke');
        }
    };
    I want to use it like this:

    storage(); - erases ('nukes') everything
    storage('abc'); - reads data stored as 'abc'
    storage('abc', 'newvalue'); - stores 'newvalue' as 'abc'
    storage('abc', null); - erases data stored as 'abc' only

    It seems to work, but I have a funny feeling about trusting the difference between "==" and "===" to make it work.

    Am I wrong? Is there a real difference between == and === and am I doing this correctly?

    Thanks!

    -- Roger
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #2
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    Yes there is a real difference, and yes you are doing things correctly (albeit a bit hard to follow - but my brain is old ). The only danger would be if you send something to name that is 0, emptystring, false etc and you wouldn't want that to nuke...

    Here's my take on it:
    Code:
    var storage = function(){
      var a = arguments, action = 
        (!a.length && "nuke")
        || (a.length < 2 && "read")
        || (a[1] === null && "erase")
        || "write";
        
        alert(action);
    };
    Last edited by ironboy; 10-09-2011 at 03:37 AM.

  • Users who have thanked ironboy for this post:

    Krupski (10-09-2011)

  • #3
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by ironboy View Post
    Yes there is a real difference, and yes you are doing things correct (albeit a bit hard to follow - but my brain is old ). The only danger would be if you send something to name that is 0, emptystring, false etc and you wouldn't want that to nuke...

    Here's my take on it:
    Code:
    var storage = function(){
      var a = arguments, action = 
        (!a.length && "nuke")
        || (a.length < 2 && "read")
        || (a[1] === null && "erase")
        || "write";
        
        alert(action);
    };
    AH!!! I never thought of the possibility of a NAME being interpreted as empty... good catch!

    Edit:
    Here's the complete code which seems to work OK.... comments will be appreciated!

    Code:
    /***
     * support for HTML5 local storage
     * storage() - erase all stored data - always returns true
     * storage('name') - reads data stored as "name" - return false if does not exist
     * storage('name', value) - writes data "value" as "name" - return false if failed
     * storage('name', null) - erase data stored as "name" - return false if failed
     **/
    var storage = function (name, value) {
        var key = '123xyz'; // unique prefix... change as desired
        if (name !== undefined) {
            if (value === null) {
                localStorage.removeItem(key + '_' + name);
                return (storage(name) == false);
            } else {
                if (value != null) {
                    localStorage.setItem(key + '_' + name, value);
                    return (storage(name) == value);
                } else {
                    return localStorage.getItem(key + '_' + name) || false;
                }
            }
        } else {
            for (var x in localStorage) {
                localStorage.removeItem(x);
                return true;
            }
        }
    };
    Last edited by Krupski; 10-09-2011 at 03:50 AM. Reason: added xtra code
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #4
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    Your code works fine!

    I might have taken another approach though:
    Code:
    var Store = function(key){
      // Read an object from localStorage or create it
      var x = JSON.parse(localStorage.getItem(key) || '{}');
      for(var i in x){this[i] = x[i]};
      // Flush the object to localStorage
      this.flush = function(){
        localStorage.setItem(key,JSON.stringify(this));
      };
      // Remove obj properties and remove from localStorage
      this.nuke = function(){
        for(var i in this){
          if(typeof this[i] == 'function'){continue};
          delete this[i]
        };
        localStorage.removeItem(key);
      };
    };
    This would let me create different stores and store whole object structures in each store:
    Code:
    var myStore = new Store('abc');
    
    if(myStore.animal){
      console.log('Reading',myStore.animal)
    }
    else {
      myStore.animal = {
        legs: 4,
        tail: 1,
        barks: true
      };
      console.log('Writing', myStore.animal)
      myStore.flush();
    };

  • #5
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by ironboy View Post
    Your code works fine!

    I might have taken another approach though:

    [--- JSON stuff ---]
    Actually, an older version of that code (which was separate read, write and clear functions) had JSON support, but then (of course) MSIE threw a fit because it didn't support JSON, so I had to have Douglas Crockford's JSON support library loaded.

    Then, I decided to remove the JSON support and the library because all I store anyway is simple stuff like the client's desired text size, the height of a chatbox window and text editor data to be recalled in case the user makes a mistake.

    So, thanks again for the help and ideas.... I never had thought of what would happen if the data name evaluated to false. Granted, it probably would have never happened, but good code handles all exceptions.

    Thanks!

    -- Roger
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #6
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    B.t.w. for a stable cross-browser solution (that serializes data just as in my approach above - but allows older IE and Firefox browsers to play along) - have a look at:

    https://github.com/marcuswestin/stor...ster/README.md


    [EDIT]:
    Ah, I see you want really light-weight (and JSON needs the json2-library in IE<8). Makes sense then.

    [EDIT 2]:
    Actually, it DOESN'T MAKE SENSE - since JSON is native in IE8 and upwards and localStorage is only available in IE8 upwards...
    Last edited by ironboy; 10-09-2011 at 05:48 AM.

  • #7
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by ironboy View Post
    B.t.w. for a stable cross-browser solution (that serializes data just as in my approach above - but allows older IE and Firefox browsers to play along) - have a look at:

    https://github.com/marcuswestin/stor...ster/README.md


    [EDIT]:
    Ah, I see you want really light-weight (and JSON needs the json2-library in IE<8). Makes sense then.

    [EDIT 2]:
    Actually, it DOESN'T MAKE SENSE - since JSON is native in IE8 and upwards and localStorage is only available in IE8 upwards...
    Wow you are a fountain of cool stuff!

    By the way, I stumbled upon your code in another thread to fade things in and out. I've never been able to get that to work using setTimeout and now looking at your code I see why.

    Anyway, one of the pieces of code I use is a simple size limitation for images. I limit them with CSS to width:150px, but then they can be toggled full size or thumbnail.

    When I saw your fade in/out code, I had to try this... and it worked:

    Code:
    /***
     * zoom or shrink image preview
     **/
    var showImage = function (a) {
        fade(a, 100, 0, 500);
        setTimeout(function() {
            a.style.maxWidth = (getStyle(a, 'maxWidth') == '150px') ? '9999px' : '150px';
            fade(a, 0, 100, 500);
        }, 500);
    
    //  a.style.maxWidth = (getStyle(a, 'maxWidth') == '150px') ? '9999px' : '150px';
        a.title = (a.title == 'Click for full size') ? 'Click for thumbnail' : 'Click for full size';
    };
    It's too cool! Instead of the image snapping large / small / large, now it fades between the two! LOL!!

    Thanks again!

    -- Roger
    Last edited by Krupski; 10-09-2011 at 10:33 PM. Reason: fixed typo
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #8
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    Thanks for all the praise!

    Glad you could coolify your image snapping


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •