Storing and getting boolean with Redis - javascript

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

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

Every function with Object.values not working

I have an object and I need to check if all the values are true.
{
condition1: true,
condition2: true,
condition3: false
}
Ive used Object.value to get an array of the true and false values. However I cant seem to get the every function to work, it always returns true.
const test = Object.values(equipmentSelection)
.every((element) => {
if (element = true) return true;
});
Just return the element without using conditional check, you can do like this
const test = Object.values(equipmentSelection)
.every(element => element)
});
You are using an assignment operator = instead of a logical == or === operator. So you are basically setting element to be equal to true and then use this same value (true) as the condition of if. So the if condition is always true and thus true is returned for each element in the array.
Since element is of type boolean, you don't need the if statement, just use its value:
.every(element => element);
You can do this.
const test = Object.values(equipmentSelection)
.every(element => element===true);
And like others have said,
.every( element => element);
Will return the elements value which is with true or false and that’s what you will get with the comparisons.

Why i'm getting undefined using Boolean object?

function boo(arr)
{
for(var i=0;i<arr.length;i++)
{
var bob = new Boolean(arr[i]);
if(bob === false)
{
console.log(arr[i]);
}
}
}
console.log(boo([0,"how",89,false]));
I want to check all the false values like false,null,undefined etc.from an array using Boolean Object and print it. How can i do it using Boolean Object?. How can i add multiple values for checking whether it is true or false in Boolean Object?
You can't compare Boolean objects that way in javascript. new Boolean(...) === false will always evaluate to false.
MDN has a good warning on the matter:
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.
For instance (given value = arr[i]), if you need to see if something is truthy just use !!value. For falsey, use !value. If you need to see if something is really true use value === true, likewise for false, but not a Boolean instance.

jQuery cookie sets boolean value as string

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?

Optional parameters in JavaScript [duplicate]

This question already has answers here:
Set a default parameter value for a JavaScript function
(29 answers)
Closed 6 years ago.
Question
What is a good way of assigning a default value to an optional parameter?
Background
I'm playing around with optional parameters in JavaScript, and the idea of assigning a default value if a parameter is not specified. My method in question accepts two parameters, the latter of which I deem to be optional, and if unspecified should default to false. My method looks something like this...
// selects the item, appropriately updating any siblings
// item to select [, toggle on / off]
this.selectItem = function(item, toggle)
{
toggle = toggle && typeof toggle === 'boolean';
if (toggle)
{
// ...
}
}
Testing
After running a few tests on this jsFiddle, using the following principal for default value assigning:
function checkParamIsBoolean(param)
{
param = param && typeof param === 'boolean';
}
checkParamIsBoolean('me'); // boolean
checkParamIsBoolean([]); // boolean
checkParamIsBoolean(true); // boolean
checkParamIsBoolean(false); // boolean
checkParamIsBoolean(1 == 1); // boolean
checkParamIsBoolean(1); // boolean
checkParamIsBoolean(null); // object
checkParamIsBoolean(undefined); // undefined
​
As you can, the results vary, and aren't desired.
Expected
null = false
undefined = false
Actual
null = object
undefined = undefined
Summary
Are there any alternative approaches to assigning a default value to an optional parameter if it's unspecified; would it be better to use _toggle as the parameter and then assign the value to var toggle within the method?
Better solution is to use named arguments wraped in a object. It keeps your code clean and prevents errors in case of complex functions (with many default and non-default arguments). Otherwise you need to remember about the order of arguments and assign default values based on the types of arguments present (that's what you're trying to do).
That method is a primary way of passing params jQuery and jQuery's plugins.
function test(options) {
// set up default options
var defaults = {
param1: 'test',
param2: 100
};
// combine options with default values
var options = $.extend({}, defaults, options); // If you're not using jQuery you need different function here
alert(options.param1)
alert(options.param2)
}
test({'param2': 200}) // Call the function with just the second param
You can use this construction for optional parameters in your code:
//...
optionalParam = optionalParam || 'some default value';
In your concrete exaple it would be something like this:
this.selectItem = function(item, toggle)
{
toggle = toggle || false;
// ...
}
But in your case you could use toogle (optional parameter) directly in if statement (since you only want to check for its existence. Or optionally you could enforce boolean value like this toogle = !!toogle (double negation).
A very simple way to check if toggle is undefined, and if it is then set a default value:
if (toggle === undefined) toggle = "<your default value>";
Note that this does not change toggle if it is specified but of another type than what you expected.
Try it the other way around:
param = typeof param === 'boolean' && param;
This will make sure all are a boolean, see this fiddle
Why do you check the parameter to be boolean, if you expect an other result? The usual way would be checking for typeof toggle != "undefined", but in your case
toggle = Boolean(toggle);
should do the task. You can also use the shortcut !!toggle, or use it directly in the if-clause:
if (toggle) { // will evaluate to "false" for undefined
...
BTW, no need for a _toggle parameter; you can just reassign to toggle.
You can replace
param = param && typeof param === 'boolean';
with
param = !!(param && typeof param === 'boolean');
This will convert the result of the statement to the boolean negate, and then negate it back again.
If you consider null(as well as no args passed), undefined and ""(empty string) as "not an argument has passed to my function" use this statement:
toggle = toggle&&toggle||default_value
Now if you pass null, undefined or "" to your function as toggle arg, this line fills it with default_value.
Take a look at jQuery extend and how they handle optional parameters.
It can easilly be done with ArgueJS:
this.selectItem = function()
{
arguments = __({item: undefined, toggle: [Boolean, false})
if (arguments.toggle)
{
// ...
}
}
You can also check the type of item by changing undefined by the desired type.

Categories

Resources