how to use ternary operator to return a definite value or a block of code - operator-keyword

I was testing out the ternary operator in javascript to see if this would work. I want the function to return 1 if the number is zero or run through the loop and return the factorial. I don't know why it isn't working. please check the code below.
function factorialize(num) {
return (num==0)?1: (for( i=num-1; i>0; i--){
num*=i
console.log(num)
}
return num;)
}
factorialize(5);

Thanks, Misorude I made use of an IIFE and it worked. Here is the code
function factorialize(num){
return (num==0)?1: (()=>{for( i=num-1; i>0; i--){
num*=i
console.log(num);
}
return num;})();
}
console.log(factorialize(5));

Related

Break on ForEach() dart

I'm writing a function where I iterate thru a map and look test for valid values on an function. My question is there is a better way to correctly break from a foreach loop when an error is found?
('break' does not work on foreach())
Since I am not able to use the break function here so i had to place a bool marker :/
Any help in making this code nice looking would be appreciated :)
Future<bool> saveToKeychainFunc(Map data) {
bool saved = false;
bool error = false;
data?.keys?.forEach((item) async {
if (data[item] != null) {
await _storage.write(key: item.toString(), value: data[item].toString());
} else {
//TODO
// data error, we got null for a value!
error = true;
}
saved = true;
});
return (error == true) ? false : saved;
}
I've experienced this. My work around is using for loop instead.
ex:
for (int i = 0; i < jsonTransactions.length; i++) {
Transaction transaction = Transaction.fromJson(jsonTransactions[i]);
transactions.add(transaction);
}
You can just add conditions, and add your break inside the loop if conditions are met. Since you're using a map, my code should not be very different since Map also has .length

Dart: warning "info: This function has a return type of 'int', but doesn't end with a return statement")

I got a warning on the following piece of code, and I don't know why.
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
callNoInfo.forEach((item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
});
return 0;
}
The warning is:
This function has a return type of 'int', but doesn't end with a return statement. (missing_return at [project_name] lib\helper\call_no.dart:35)
Can anyone tell me why this happens? thanks in advance
In the forEach method, you are creating a lambda function without explicitly defining the return type, so Dart is attempting to infer it from the return statements. If we pull the function out of the forEach method, it might help to see what I mean:
...
(item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
}
...
The function includes a return statement that returns item[phoneNo], which is an int value. Using this, Dart infers that the return type of this lambda function is int. However, now that it knows this, it also notices that if the code execution does not enter the if block, there is no return statement to match the else side of the if condition. If the item object does not contain the key phoneNo, what is the method going to return?
(The answer is that the method will implicitly return null which is why the message is only a warning and not a compiler error, but the warning appears because this probably wasn't intentional by you the developer and also as a nudge to help you make your code less reliant on invisible Dart runtime magicks.)
To fix this, there needs to be another return outside of the if block:
...
(item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
return 0;
}
...
However, now there's a different problem. The forEach method on lists has the following signature:
forEach(void f(E element)) → void
In fact, there are two problems. First, the method passed as the parameter needs to have a return type of void, and the forEach method itself also has a return type of void. This means that you cannot return values from within the forEach method at all.
The thing about the forEach method is that it is intended to iterate over the collection and process each of the values within it. It's not meant to (and can't) search for a value and return it once it's found. Furthermore, the iteration is exhaustive, meaning once you start it, the method cannot be stopped until each and every element in the collection has been iterated over.
Which is why, as the other answers have pointed out, what you really should be doing is using a for or for in loop:
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
for(var item in callNoInfo) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
}
return 0;
}
(I'm not sure why you don't get a compiler error for assigning a lambda function with a return value of int to the forEach method which clearly is requesting a one with a void return type. But if I had to guess, I'd say the Dart runtime treats them as compatible and reconciles the difference in return type by simply discarding the return value of the lambda function.)
You don't have an else case for the if statement inside the forEach loop. Even though you might have one at the end, it still is expecting a case everywhere.
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
callNoInfo.forEach((item) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
// you don't have a case for here since it's in a callback
});
return 0;
}
However, you could do this which uses a for in loop:
List<Map<String, int>> callNoInfo = [];
int getCallNo(String phoneNo) {
for (var item in callNoInfo) {
if (item.containsKey(phoneNo)) {
return item[phoneNo];
}
}
return 0;
}

Javascript and Callback function

I’m a newbie in programming language and I’m learning Javascript. I’m trying to understand the concept of callback function. I realized that callback is intended a function passed as parameter, but when does it call?
In the below examples I used a classic approach to write functions and then I tried to use the arrow function. The callback is done() function, in the first example it is called after the parent function, in the second one after.
What is the reason? Can you give me an explanation? Thank you so much for the feedback
Example no. 1
function done(){
console.log("Done");
}
function increment(num, callBack){
for(var i = 0; i <= num; i++){
console.log(i);
}
return callBack();
}
increment(10, done);
Example no. 2
const done = () => {
console.log("Done");
}
const increment = (num, done) => {
for (var i = 0; i <= num; i++) {
console.log(i);
}
}
increment(10, done());
To use callback you need to specify that there'll be a callback function as a argument, and you need to call that somewhere in the parent function like this, and that's when it will be called:
function someFunction(callback){
//Do something if needed...
callback() //callback(someParameter) if you want to pass some parameter to the callback func
//Do something if needed...
}
In your 2nd example, it's actually not a proper way of using callback function because you did not call the callback function inside parent function. You can modify it to to make it work as 1st example like this:
const increment = (num, done) => {
for (var i = 0; i <= num; i++) {
console.log(i);
}
done(); //call the callback function
}
increment(10, done); //just pass the name of callback func, not call it like you did "done()"

What is the most efficient way to call another function in parent function to execute Palindrome function?

In programming, there are multiple ways of doing the same problem. The following problem is in regards to palindrome. Though I feel that I am on the right track, I am not able to completely solve the problem to get to requested solution.
What is a palindrome? A word written forward or backward is the same and returns true. Example, "racecar". Hence, I designed the following code in Javascript...
function palindrome(string) {
string = string.toLowerCase();
lowString = string.toLowerCase().split("").reverse().join("");
for (var i=0; i<string.length; i++) {
if (string[i] !== lowString[i]) {
return false;
}
}
}
return true;
}
The above code returns true if Palindrome exists and returns false if not.
Then, the problem says - Given various palindrome in a string or array, please return the longest palindrome. So, I wrote the following:
function longestPalindrome(newstring) {
splitString = newString.split(" ");
for (var i=0; i < splitString; i++) {
if (splitString[i] == palindrome(splitString[i]) {
console.log(splitString[i]);
}
}
}
longestPalindrome("This is a racecar ada");'
But in the above code, I am not able to get the required outcome because I believe I am not calling the function correctly.
I would appreciate clear directions or even a solution built off of my track as well as the track you deem fittest.

avoid Number Format Exception while parseing to integer

I'm trying to check if the text area has only numbers or not, but i got this problem Number Format Exception while clicking on the Edit Button, any Ideas how to solve it.
ArrayList<CarRental> List= CarRent.getList();
String text=EditTF.getText().trim();
char [] txt=text.toCharArray();
Character a=null;
boolean isnotDigit=false;
int index;
for(int i=0;i<txt.length;i++)
{
if(!a.isDigit(txt[i]))
{
isnotDigit=true;
break;
}
else
{
isnotDigit=false;
continue;
}
}
if(isnotDigit==false)
{
index=Integer.parseInt(text.trim());
PrintList_Summary.setIndex(index);
EditDetails.nameTF.setText(List.get(index).getName());
EditDetails.sizeCOB.setSelectedItem(List.get(index).getSize());
EditDetails.daysTF.setText(List.get(index).getDays()+"");
if(List.get(index).getCarType().equalsIgnoreCase("Luxury"))
{
EditDetails.LuxRB.setSelected(true);
}
else if(List.get(index).CarType().equalsIgnoreCase("Truck"))
{
EditDetails.truckRB.setSelected(true);
}
if(List.get(index).getDriver())
{
EditDetails.yesRB.setSelected(true);
}
else
{
EditDetails.noRB.setSelected(true);
}
EditDetails.Frame.setVisible(true);
}
else
{
JOptionPane warning=new JOptionPane();
warning.showMessageDialog(null,"Element Index CAN ONLY be an INTEGER.","Invalid Index",WIDTH);
}
Use try catch to handle exceptions.
try{
index = Integer.parseInt(text.trim());
//etc
}catch(NumberFormatException ex){
//whatever happens when the exception is thrown (not an integer)
}
You can use that instead of the if(!a.isDigit(txt[i])) for. If it can't be parsed, then it will go intro the catch.
Also, you can use !isnotDigit instead of isnotDigit == false.
I would use String.matches() for your check instead of doing it yourself. Scrap the for-loop and change your if-condtion from isnotDigit==false to text.matches("[0-9]+"). After this Integer.parseInt(text) should definitly work.
This uses a regular expression to check if your string consists only of digits and at least one digit. For further reference on regular expression see the javadoc for Pattern.