jQuery cookie sets boolean value as string - javascript

I'm working with a cookie, setting other code varibles using the value of the cookie.
I have defined data about the default state of the cookie as so:
const Cookie = {
config: {
name: 'Test_Cookie',
expire: 1,
value: true,
},
...
}
When criteria are met, the cookie gets set for the first time, using this.config.value to set the value of the cookie to true:
setCookie: function () {
if (!this.isCookieSet()) {
$.cookie(this.config.name, this.config.value, this.config.expire);
}
},
However, I am finding when I return the cookie value in the code I get "true" back as a string rather than just true. For example (name changed in above example for simplicity):
If I try to do a comparison on the value of the cookie, and use === true I get a false result. If I do === "true" then I get a true result:
showStuff = $.cookie('Test_Cookie') === "true"; // showStuff = true;
OR
showStuff = $.cookie('Test_Cookie') === true; // showStuff = false;
Why does the variable type of the cookie value change when set?

Cookies are strings. You'll need to convert the cookie value to the type you want. The boolean values are being saved as true or false because that's the string representation of a boolean.
You can use the following.
var myBool = Boolean($.cookie('Test_Cookie'));
or
var myBool = ($.cookie('Test_Cookie') === "true");
EDIT
As suggested in the first comment by #DelightedD0D:
You could also try - $.cookie('Test_Cookie') === "true"

For future readers: You can check against the string value as noted in other answers or convert it to a Boolean value for greater flexibility.
function stringToBoolean(string) {
switch(string.toLowerCase()) {
case "false": case "no": case "0": case "": return false;
default: return true;
}
}
const isTrue = stringToBoolean("true");
const isFalse = !isTrue;
ref: How can I convert a string to boolean in JavaScript?

Related

Javascript search an array for a value starting with a certain value

I am looking for a way to search an array to see if a value is present that starts with the search term.
const array1 = ['abc','xyz'];
So a search for 'abcd' would return true on the above.
I have been playing about with includes, but that only seems to check the full value.
Also, startsWith I dont think will work as I believe that checks a string and not values in an array??
You can use the find() function which allows you to pass a custom function in parameter that will be tested on each value. This way you can use startsWith() on each value of the array as you intended to do.
Example:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
});
}
console.log(findStartWith("hello")); // undefined
console.log(findStartWith("abcd")); // abc
console.log(findStartWith("xyzz")); // xyz
If you want to return true or false instead of the value, you can check if the returned value is different from undefined.
function findStartWith(arg) {
return !!array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
The same snippet with a boolean:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
console.log(findStartWith("hello")); // false
console.log(findStartWith("abcd")); // true
console.log(findStartWith("xyzz")); // true

Storing and getting boolean with Redis

I'm trying to use Redis to store and get a boolean for my toggle function.
The dependecy what I'm using is redis-js I can set the value false with key to redis but getting the valu from redis is always false.
Say first store the key value to Redis
redis.set('myKey', 'false');
Get the value
let toggle = redis.get('myKey');
toggle = !toggle;
Store
redis.set('myKey', toggle);
Get
const checkStatus = redis.get('myKey');
return checkStatus;
I'm expecting the output will be true -> false if executed the function two times.
For your toogle to work you've to explicitly check if the value you get is equal to the string 'false'.
let toggle = redis.get('myKey');
toggle = toogle === 'false'
Converting the string 'false' to boolean results to true not false and negating it you get false.
From MDN
All other values, including any object or the string "false", create an object with an initial value of true
Here's an illustration:
const val = 'false'
const toggle = !val; // this is equivalent to !Boolean(val)
const bool = Boolean(val) // get boolean
const negated = !bool // negate
console.log('toggle: ', toggle);
console.log('bool: ', bool); // Boolean("false") gives true
console.log('negated: ', negated);
You run command redis.get, the return value type is String not Boolean.
So you should't use ! operator, you can compare with 'true' or 'false', then assign a value

How can I cast a variable to the type of another in Javascript

I want to be able to cast a variable to the specific type of another. As an example:
function convertToType(typevar, var) {
return (type typevar)var; // I know this doesn't work
}
so that convertToType(1, "15") returns 15, convertToType("1", 15) returns "15", convertToType(false, "True") returns true, etc.
To reiterate, I want to be able to dynamically cast variables to the types of other variables.
Is this possible?
function convertToType (t, e) {
return (t.constructor) (e);
}
note the first call when we wanted to convert 15 to a Number, we append a dot (.) to the first parameter
UPDATE: here's an even more complete example, with tests (requires Node 6+ or some transpilation to ES5): https://github.com/JaKXz/type-convert
You can use the typeof operator to get the right "casting" function:
function convertToTypeOf(typedVar, input) {
return {
'string': String.bind(null, input),
'number': Number.bind(null, input)
//etc
}[typeof typedVar]();
}
Try it out here: http://jsbin.com/kasomufucu/edit?js,console
I would also suggest looking into TypeScript for your project.
It follows my version of JaKXz answer that is supposedly more efficient by switching on inferred type. In the case of number and boolean the conversion is loose: in case of invalid input it will output NaN and false, respectively. You can work on this by adding your stricter validation and more types.
function convertToTypeOf(typevar, input)
{
let type = typeof typevar;
switch(type)
{
case "string":
return String.bind(null, input)();
case "number":
return Number.bind(null, input)();
case "boolean":
return input == "true" ? true : false;
default:
throw "Unsupported type";
}
}
console.log(convertToTypeOf("string", 1)); // Returns "1"
console.log(convertToTypeOf("string", true)); // Returns "true"
console.log(convertToTypeOf("string", false)); // Returns "false"
console.log(convertToTypeOf(1.2, "1")); // Returns 1
console.log(convertToTypeOf(1.2, "1.5")); // Returns 1.5
console.log(convertToTypeOf(true, "false")); // Returns false
console.log(convertToTypeOf(false, "true")); // Returns true
console.log(convertToTypeOf(1, "asd")); // Returns NaN
console.log(convertToTypeOf(true, "asd")); // Returns false

Object get the value by a key

I'm kinda stuck with an issue. This is the response for my AJAX call.
var test = [
{
"analytics.feature": "false"
},
{
"demo": "true"
},
{
"analytics.demo": "false"
}
]
Now I want to check if analytics.demo is enabled or disabled.
Can I use _.find?
_.find(test, {analytics.demo}); //returns error
I just want to do this
if(analytics.demo) {
//Do something
}
How do I do that? Can someone help?
Instead of iterating objects and comparing, can I use underscorejs/jQuery to get the exact value for a key?
const options = Object.assign(...test)
console.log(options) // { "analytics.feature": "false", demo: "true", "analytics.demo": "false" }
if (options['analytics.demo'] === 'true') {
// ...
}
(Note that this uses ES6. For ES5 use var options = Object.assign.apply(object, test) instead, and you also need to polyfill Object.assign.)
This uses Object.assign() with the spread operator to merge the objects into one, then get the "analytics.demo" option from the new single object. It has to be accessed using bracket notation because the key has a dot in. It is compared to the string true because "false" (string) is true but false (boolean) is false.
There is more information on SO about flattening arrays and converting strings to booleans.
PS is there any way you can get the Ajax call to use proper booleans instead of strings? It would be easier to work with.
You can check if any of the items in the array matches a certain condition like so:
var isDemoEnabled = test.some(function (item) {
return item['analytics.demo'] === 'true';
});
if (isDemoEnabled) {
// Do something
}
If the values were boolean, you could remove === 'true'
Assuming you're using underscore, check out the documentation regarding find:
http://underscorejs.org/#find
Find runs a predicate function for every element in an array and returns a new array that contains every value where the predicate function returned true.
In this case we want to find if the element has a field analytics.demo
To do this we can use the underscore function _.has:
http://underscorejs.org/#has
all in all:
var result = _.find(test, function(elem) {
return _.has(elem, "analytics.demo");
}
);
You could iterate over and check if the key is given and return then the result.
function getKeyValue(array, key) {
var value;
array.some(function (a) {
if (key in a) {
value = a[key];
return true;
}
});
return value;
}
var test = [{ "analytics.feature": "false" }, { "demo": "true" }, { "analytics.demo": "false" }]
console.log(getKeyValue(test, 'analytics.demo')); // 'false' a string with this value

How can I check if a variable is not null and also a number?

I am using the following:
$scope.option.selectedSubject != null && !isNaN($scope.option.selectedSubject)
Can someone tell me if there is another way to check if a variable is a valid defined number? Is there some way I can do this with just one check or how can I create a function to do this check and then call that ?
maybe this function might help you :
function isANumber(x) {
return ((+x)===x);
}
This might be useful to know: A variable can only be null when somewhere in your script it's being assigned, it will never be null by default.
var foo; // undefined
foo = null;
// null could be returned by a function too, which is the most common use of null
As zzzzBov stated in his comment, "isNaN will check if the numeric representation of the value is NaN. this means that isNaN('500') is false, while isNaN('foo') is true."
As to answer your question, check this table:
!isNaN(undefined); // false
!isNaN(null); // true
!isNaN(); // false
!isNaN(''); // true <= Watch out for this one !
!isNaN('test'); // false
!isNaN('10'); // true
!isNaN(10); // true
If you want to make sure it's a number, you should use typeof, then if this is a string, check if it has a length. Wrapping this all in a function would create something like:
function isNumber (num) {
// Return false if num is null or an empty string
if (num === null || (typeof num === "string" && num.length === 0)) {
return false;
}
return !isNaN(num);
}
isNumber(undefined); // false
isNumber(null); // false
isNumber(); // false
isNumber(''); // false
isNumber('test'); // false
isNumber('10'); // true
isNumber(10); // true
This would do the trick if you care only about numeric presentation.
!isNaN($scope.option.selectedSubject + "")
Notice the + ""

Categories

Resources