Converting boolean integer to string value in javascript - boolean

I am reading a boolean integer value from database (0 or 1).
Is there an simple solution to convert a boolean int to boolean string?
When I was saving the value to my database I was able convert the string to an int using a javascript ternary operator.
var i = result ? 1 : 0;
Is it possible to preform the opposite?
My current work-around is:
function boolIntToString(i) {
if (i == 1) {
return true;
}
else {
return false;
}
}

The expression i != 0 evaluates to boolean false if i = 0, or true otherwise, so to get true or false, you could simply write:
var theBool = i != 0;
If you want a string, you can call .toString() on that boolean result. Wrapping this into your function, you get:
function boolIntToString(i) {
return (i != 0).toString();
}
console.log(boolIntToString(1));
Note that your own function returns a boolean, not a string.

Related

Dart Function Returning Set<bool> Instead of bool

I'm building a mobile client for a blog with a paid CMS that shows a number of articles all the time, plus a rotating article each week, and I've built a simple function to get the current week of the year and return a Boolean value if an article should be displayed this week:
bool displayArticle(StoredArticle article){
if (article.week < 0) {
return true;
}
DateTime now = DateTime.now();
DateTime janFirst = DateTime(now.year, 1, 1);
int weekNum = (now.difference(janFirst).inDays / 7).ceil();
if(article.week == weekNum || article.week == (weekNum - 1)){
return true;
}
return false;
}
I then use this function to filter a list of all the articles like so:
List<StoredArticle> articlessToDisplay = storedArticleObjs.where((article) => {
displayArticle(article)
}).toList();
This is all enclosed within a Stateful Widget.
However, using the function like this throws an error at the function call that The return type 'Set<bool>' isn't a 'bool', as required by the closure's context.
My first thought was that there was an issue with the displayArticle() function being a static member function to a stateful widget, but moving the function directly into the closure as follows did not impact the error.
List<StoredArticle> articlessToDisplay = storedArticleObjs.where((article) => {
if (article.week < 0) {
return true;
}
DateTime now = DateTime.now();
DateTime janFirst = DateTime(now.year, 1, 1);
int weekNum = (now.difference(janFirst).inDays / 7).ceil();
if(article.week == weekNum || article.week == (weekNum - 1)){
return true;
}
return false;
}).toList();
Next I thought it might be that the early return was confusing the inspector to belive it was returning multiple values, so I converted it to a single return function as follows, but that did nothing either.
bool displayArticle(StoredArticle article){
bool shouldDisplay = false;
if (article.week < 0) {
shouldDisplay = true;
}
DateTime now = DateTime.now();
DateTime janFirst = DateTime(now.year, 1, 1);
int weekNum = (now.difference(janFirst).inDays / 7).ceil();
if(article.week == weekNum || article.week == (weekNum - 1)){
shouldDisplay = true;
}
return shouldDisplay;
The only resources on similar issues have been referring to functions that return Future<T> instead of T. Putting aside the fact that my issue is with a Set<T> rather than a Future<T>, those errors have all been thrown by the return statement or the function definition rather than the function call.
I haven't been able to find any resources relating to this specific issue, though as I'm new to Flutter and Dart I suppose could be missing some specific terminology.
That being said, returning a set of the return type does not make any sense to me. Is this a quirk of implementation in a Stateful Widget?
The problem is that you have a few too many braces, and {"A"} is set-syntax in Dart.
You have:
storedArticleObjs.where((article) => {
displayArticle(article)
}).
Change that to:
storedArticleObjs.where((article) =>
displayArticle(article)
).
Note that the => function syntax doesn't use braces.
You could even probably write it more compactly using tear-offs like so:
storedArticleObjs.where(displayArticle).

Why does the identityHashCode function not work for the built-in type 'int' in Dart?

The documentation of the identityHashCode says:
And it indeed works for my custom type 'Integer':
class Integer {
int num;
Integer(this.num);
#override
int get hashCode {
return num;
}
#override
bool operator ==(Object other) {
if(other is Integer && this.num == other.num) {
return true;
}
return false;
}
}
void main() {
Integer n1 = Integer(1);
print(n1.hashCode); // print "1"
print(identityHashCode(n1)); // print "650939380", a different value!
}
But for the built-in type 'int', identityHashCode(int) seems to always return the same value as int.hashCode, which is the numerical value itself:
void main() {
int n = 1;
print(n.hashCode); // print "1"
print(identityHashCode(n)); // still print "1", the same value as n.hashCode!
}
Anyone know why this is happening? I'm confused now.😵
int is Built-in type (not a usual class)
In documentation identityHashCode has a note:
This hash code is compatible with [identical], which just means that
it's guaranteed to be stable over time.
For compiler all int values are constants. identical for the same constants shows true. So hashCode of int was made by own value (which also int).
print(identical(1, 1)); // true
According to this comment int (and double) has own condition for comparing in identical function.
By the same numeric value
Here's some code for example representation:
void main() {
int a = 1; // '1' is a constant
int b = 1;
int c = 2; // '2' is a constant
print(identical(a, b)); // true
print(identical(a, c)); // false
print(identical(1, 1)); // true
print(identical(1, 2)); // false <= 1 and 2 are constants
print(identical(a, 1)); // true
print(identical(c, 1)); // false
print(identical(c, 2)); // true
print(identityHashCode(a)); // 1
print(identityHashCode(b)); // 1
print(identityHashCode(c)); // 2
print(identityHashCode(1)); // 1
print(identityHashCode(2)); // 2
}

12.0 can't be identified as double nor int or numeric in flutter

I have this problem with dart. I created a simple calculator. If the result if a calculation is equal to, for example, -12.9 or 12.9. The app gives the correct answer and no error. But, if the answer given is 12.0 or -12.0, the app crashes. Why is that? I created a function to check if the string is an int or a double. It returns false.
bool isDouble(String number) {
try {
num n = num.parse(number);
if (n % 1 == 0) {
return false;
} else {
return true;
}
} catch (e) {
return false;
}
}
For the numeric, I used the isNumeric function in dart. Please help me.
As Riwen mentioned, any whole number % 1 is 0, even if it's a float. You can check the type of a variable with .runtimeType. I think when you parse the string to num, it automatically converts whole numbers to int, so you cant just check if runtimeType == "double". Also, to remove decimal values, you can just use .floor(), which will round down and convert the variable to an int.
This function seems to work:
bool isDouble(String number) {
if (int.tryParse(number) == null){
if (double.parse(number).isFinite) return true;
}
return false;
}

How to fix both Found 'DD'-anomaly and only one return statement

I have some difficulties when fixing PMD warnings, this was my simplified method:
public String rank(String keyword, int pageSize, int totalPage)
{
String result = "0"; // A: DataflowAnomalyAnalysis: Found 'DD'-anomaly for variable 'result'
if (isNotBlank(keyword))
{
boolean find = false; // B: DataflowAnomalyAnalysis: Found 'DD'-anomaly for variable 'find'
for (int page = 1; page < totalPage; page++)
{
int rank = getRank(keyword, pageSize, totalPage);
if (rank != 0)
{
find = true; // B(1)
result = String.valueOf(rank); // A(1)
break;
}
}
if (!find)
{
result = format("{0}+", totalPage * pageSize - 1); // A(2)
}
}
return result;
}
I tried this and got "OnlyOneReturn" warnings:
public String rank(String keyword, int pageSize, int totalPage)
{
if (isNotBlank(keyword))
{
for (int page = 1; page < totalPage; page++)
{
int rank = getRank(keyword, pageSize, totalPage);
if (rank != 0)
{
return String.valueOf(rank); // OnlyOneReturn
}
}
return format("{0}+", totalPage * pageSize - 1); // OnlyOneReturn
}
return "0";
}
How do I have to write this code please?
A 'DD'-anomaly an a dataflow analysis tells you that you assign a variable more than once without using it between the assignments. So all but the last assignment are unnecessary. It usually indicates that you didn't separate your scenarios properly. In your case you have three scenarios:
If the keyword is blank then the return value is "0".
Otherwise loop through all pages and if getRank() returns a rank other than zero then this is the return value.
Otherwise the return value is "totalPage * pageSize - 1+"
If you implement those scenarios one by one you end up with a method that has not any dataflow or other PMD issues:
public String rank(String keyword, int pageSize, int totalPage) {
String result;
if (isNotBlank(keyword)) {
result = "0";
} else {
int rank = 0;
for (int page = 1; page < totalPage && rank == 0; page++) {
rank = getRank(keyword, pageSize, totalPage);
}
if (rank != 0) {
result = String.valueOf(rank);
} else {
result = format("{0}+", totalPage * pageSize - 1);
}
}
return result;
}
If you take a closer look at the for loop you see that page is only used for looping. It is not used inside the loop. This indicates that the for loop is probably not necessary. getRank(keyword, pageSize, totalPage) should always return the same value as its arguments never change during the loop. So it might be enough to call getRank(...) just once.

Passing null vs nothing to named parameters

This is my class:
class Source {
final int value;
Source({this.value = 1}) {
print("source = $value");
}
}
This is how I'm passing values:
Source(value: null); // prints null
Source(); // prints 1
The question is if I am passing null to value in first call, why doesn't it print 1, aren't they equivalent?
In your definition you are creating a default parameter.
value is being defined as 1 and will be the default value in the absence of any other value being assigned to that parameter. When you actively provide it null as a value, it takes precedence over the default.
#adlopez15 is the correct answer.
But if you want null to result in 1 you can do this:
class Source {
final int value;
Source({int value}) : value = value ?? 1 {
print("source = ${this.value}");
}
}