bevacqua / local-storage

:left_luggage: A simplified localStorage API that just works
https://ponyfoo.com
MIT License
523 stars 62 forks source link

Added isSet Method #8

Closed jaruba closed 8 years ago

jaruba commented 8 years ago

This is useful for when you save a boolean value and:

if (!ls('myValue'))

can either mean the value is false or not set.. so checking only:

if (!ls.isSet('myValue'))

will now guarantee that the value is not set because if it wore false it would still return true

bevacqua commented 8 years ago

Your isSet method does exactly the same thing.

jaruba commented 8 years ago

Not sure I understand. I keep player settings in localStorage, most of them are boolean. But I want the default (if nothing is set in localStorage) to be true. The only way to check this now is by using:

if (ls('myValue') === null)

with this method the code would become:

if (!ls.isSet('myValue'))

The way .isSet checks for existence is by checking the localStorage value directly, before it is JSON.parse()'d, so instead of checking true / false it checks "true" / "false", thus returning existence, not truthy.

jaruba commented 8 years ago

Usage:

var ls = require('local-storage');

ls.set('foo', false);
// <- true

ls.isSet('foo');
// <- true

ls.remove('foo');
// <- true

ls.isSet('foo');
// <- false
jaruba commented 8 years ago

This is not only helpful for boolean, but also for int values of 0 that would also make if (ls('myValue')) return false if you want to check for existence.

bevacqua commented 8 years ago

Use !! outside this module

jaruba commented 8 years ago
if (!!ls('myValue'))

will still create the same issue.. the only way i could use !! outside this module would be doing:

if (!!localStorage['myValue'])

but that will just lead to confusing code. Why don't you see this method as being helpful? It is imo the only thing missing from the api..

jwillmer commented 8 years ago

I like @jaruba implementation and I agree that !!localStorage['myValue'] is an ugly workaround. I think the ls.isSet('x') method is a usefull enhancement of the API :+1:

luigiplr commented 8 years ago

@jwillmer I concur; I have many instances where this would reduce code and increase human readability.

KsaRedFx commented 8 years ago

+1