forEach instead of for loop - foreach

I am dealing with this function to see whether a certain number is in an array of numbers. If it is it should return true otherwise false.
I have this piece of code, that is perfectly working below. However, could you simplify it even more(e.g. avoid using a for loop and instead use forEach?)
Thanks
function findNumber(number){
for (var i=0;i<array.length;i++){
if (array[i] === number){
return true }
}
return false
}

Something that semantically is similar to your code and "looks functional" could be:
const findNumber = number => array.includes(number);
There really is no reason to use Array.prototype.forEach. And to be honest, in a "truly functional style" the Array.prototype.forEach is almost never used (since its purpose is to make side effects, and that is what you try to avoid with choosing FP).
References:
Array.prototype.includes()
Arrow functions

function findNumber(arr, number){
var result = false;
arr.forEach(function(item, index){
if(item === number) result = true;
});
return result;
}
Btw. I think it would be easier and more simple to simply use Array.prototype.indexOf() or Array.prototype.includes() methods.

// I guess var array is already declared
function findNumber(number){
let test = false
array.forEach(function(nbr){
if(nbr ==(=) number ){
test = true
}
})
if(test == true) {
return true
} else {
return false
}
}

Related

Equivalent of tuples in Dart [duplicate]

Is there a way to return several values in a function return statement (other than returning an object) like we can do in Go (or some other languages)?
For example, in Go we can do:
func vals() (int, int) {
return 3, 7
}
Can this be done in Dart? Something like this:
int, String foo() {
return 42, "foobar";
}
Dart doesn't support multiple return values.
You can return an array,
List foo() {
return [42, "foobar"];
}
or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.
See also either for a way to return a value or an error.
I'd like to add that one of the main use-cases for multiple return values in Go is error handling which Dart handle's in its own way with Exceptions and failed promises.
Of course this leaves a few other use-cases, so let's see how code looks when using explicit tuples:
import 'package:tuple/tuple.dart';
Tuple2<int, String> demo() {
return new Tuple2(42, "life is good");
}
void main() {
final result = demo();
if (result.item1 > 20) {
print(result.item2);
}
}
Not quite as concise, but it's clean and expressive code. What I like most about it is that it doesn't need to change much once your quick experimental project really takes off and you start adding features and need to add more structure to keep on top of things.
class FormatResult {
bool changed;
String result;
FormatResult(this.changed, this.result);
}
FormatResult powerFormatter(String text) {
bool changed = false;
String result = text;
// secret implementation magic
// ...
return new FormatResult(changed, result);
}
void main() {
String draftCode = "print('Hello World.');";
final reformatted = powerFormatter(draftCode);
if (reformatted.changed) {
// some expensive operation involving servers in the cloud.
}
}
So, yes, it's not much of an improvement over Java, but it works, it is clear, and reasonably efficient for building UIs. And I really like how I can quickly hack things together (sometimes starting on DartPad in a break at work) and then add structure later when I know that the project will live on and grow.
Create a class:
import 'dart:core';
class Tuple<T1, T2> {
final T1 item1;
final T2 item2;
Tuple({
this.item1,
this.item2,
});
factory Tuple.fromJson(Map<String, dynamic> json) {
return Tuple(
item1: json['item1'],
item2: json['item2'],
);
}
}
Call it however you want!
Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);
You can create a class to return multiple values
Ej:
class NewClass {
final int number;
final String text;
NewClass(this.number, this.text);
}
Function that generates the values:
NewClass buildValues() {
return NewClass(42, 'foobar');
}
Print:
void printValues() {
print('${this.buildValues().number} ${this.buildValues().text}');
// 42 foobar
}
The proper way to return multiple values would be to store those values in a class, whether your own custom class or a Tuple. However, defining a separate class for every function is very inconvenient, and using Tuples can be error-prone since the members won't have meaningful names.
Another (admittedly gross and not very Dart-istic) approach is try to mimic the output-parameter approach typically used by C and C++. For example:
class OutputParameter<T> {
T value;
OutputParameter(this.value);
}
void foo(
OutputParameter<int> intOut,
OutputParameter<String>? optionalStringOut,
) {
intOut.value = 42;
optionalStringOut?.value = 'foobar';
}
void main() {
var theInt = OutputParameter(0);
var theString = OutputParameter('');
foo(theInt, theString);
print(theInt.value); // Prints: 42
print(theString.value); // Prints: foobar
}
It certainly can be a bit inconvenient for callers to have to use variable.value everywhere, but in some cases it might be worth the trade-off.
you can use dartz package for Returning multiple data types
https://www.youtube.com/watch?v=8yMXUC4W1cc&t=110s
Dart is finalizing records, a fancier tuple essentially.
Should be in a stable release a month from the time of writing.
I'll try to update, it's already available with experiments flags.
you can use Set<Object> for returning multiple values,
Set<object> foo() {
return {'my string',0}
}
print(foo().first) //prints 'my string'
print(foo().last) //prints 0
In this type of situation in Dart, an easy solution could return a list then accessing the returned list as per your requirement. You can access the specific value by the index or the whole list by a simple for loop.
List func() {
return [false, 30, "Ashraful"];
}
void main() {
final list = func();
// to access specific list item
var item = list[2];
// to check runtime type
print(item.runtimeType);
// to access the whole list
for(int i=0; i<list.length; i++) {
print(list[i]);
}
}

forEach vs for in: Different Behavior When Calling a Method

I noticed that forEach and for in to produce different behavior. I have a list of RegExp and want to run hasMatch on each one. When iterating through the list using forEach, hasMatch never returns true. However, if I use for in, hasMatch returns true.
Sample code:
class Foo {
final str = "Hello";
final regexes = [new RegExp(r"(\w+)")];
String a() {
regexes.forEach((RegExp reg) {
if (reg.hasMatch(str)) {
return 'match';
}
});
return 'no match';
}
String b() {
for (RegExp reg in regexes) {
if (reg.hasMatch(str)) {
return 'match';
}
}
return 'no match';
}
}
void main() {
Foo foo = new Foo();
print(foo.a()); // prints "no match"
print(foo.b()); // prints "match"
}
(DartPad with the above sample code)
The only difference between the methods a and b is that a uses forEach and b uses for in, yet they produce different results. Why is this?
Although there is a prefer_foreach lint, that recommendation is specifically for cases where you can use it with a tear-off (a reference to an existing function). Effective Dart recommends against using Iterable.forEach with anything else, and there is a corresponding avoid_function_literals_in_foreach_calls lint to enforce it.
Except for those simple cases where the callback is a tear-off, Iterable.forEach is not any simpler than using a basic and more general for loop. There are more pitfalls using Iterable.forEach, and this is one of them.
Iterable.forEach is a function that takes a callback as an argument. Iterable.forEach is not a control structure, and the callback is an ordinary function. You therefore cannot use break to stop iterating early or use continue to skip to the next iteration.
A return statement in the callback returns from the callback, and the return value is ignored. The caller of Iterable.forEach will never receive the returned value and will never have an opportunity to propagate it. For example, in:
bool f(List<int> list) {
for (var i in list) {
if (i == 42) {
return true;
}
}
return false;
}
the return true statement returns from the function f and stops iteration. In contrast, with forEach:
bool g(List<int> list) {
list.forEach((i) {
if (i == 42) {
return true;
}
});
return false;
}
the return true statement returns from only the callback. The function g will not return until it completes all iterations and reaches the return false statement at the end. This perhaps is clearer as:
bool callback(int i) {
if (i == 42) {
return true;
}
}
bool g(List<int> list) {
list.forEach(callback);
return false;
}
which makes it more obvious that:
There is no way for callback to cause g to return true.
callback does not return a value along all paths.
(That's the problem you encountered.)
Iterable.forEach must not be used with asynchronous callbacks. Because any value returned by the callback is ignored, asynchronous callbacks can never be waited upon.
I should also point out that if you enable Dart's new null-safety features, which enable stricter type-checking, your forEach code will generate an error because it returns a value in a callback that is expected to have a void return value.
A notable case where Iterable.forEach can be simpler than a regular for loop is if the object you're iterating over might be null:
List<int>? nullableList;
nullableList?.forEach((e) => ...);
whereas a regular for loop would require an additional if check or doing:
List<int>? nullableList;
for (var e in nullableList ?? []) {
...
}
(In JavaScript, for-in has unintuitive pitfalls, so Array.forEach often is recommended instead. Perhaps that's why a lot of people seem to be conditioned to use a .forEach method over a built-in language construct. However, Dart does not share those pitfalls with JavaScript.)
👋 jamesdin! Everything you have shared about the limitations of forEach is correct however there's one part where you are wrong. In the code snippet showing the example of how you the return value from forEach is ignored, you have return true; inside the callback function for forEach which is not allowed as the callback has a return type of void and returning any other value from the callback is not allowed.
Although you have mentioned that returning a value from within the callback will result in an error, I'm just pointing at the code snippet.
Here's the signature for forEach
Also, some more pitfalls of forEach are:
One can't use break or continue statements.
One can't get access to the index of the item as opposed to using the regular for loop

How can I use a std::variant with non-trivial user objects (constructed at a later time), and having the visitor use an auto lambda?

I have code that is something like this:
using variant_t = std::variant<MyObj1, MyObj2, MyObj3>;
auto foo(){
variant_t var;
if (condition1){
var = MyObj1{"A String"};
// Other stuff
} else if (condition2) {
var = MyObj2{123, 12345};
// Other stuff
} else if (condition3) {
var = MyObj3{SomeObject};
// Other stuff
} else {
throw std::runtime_error{};
}
return var;
}
int main(){
auto var = foo();
std::visit([&](auto& v){v.call_shared_function_name();}, var);
}
Assuming all of the MyObj's are non-trivial, is there a way to get this to work?
I know std::monostate will allow you to initialize the variant in this way and actually populate it later. But if I do so, I can't have the clean auto& lambda in the visitor and will have to create a visitor/lambda for each type.
I know this might looks silly, or not that clean, but you actually need to initialize with one of those objects:
variant_t var = MyObj1{"A String"};
And it compiles fine, if you can't, please let me know and i'll remove the answer

If bool x = FALSE, how can I force if(x) to evaluate to TRUE?

This is something of an obtuse question, but I'm trying to write unit tests for the following method:
+ (BOOL)alwaysTrue:(NSError **)error {
BOOL alwaysFalse = FALSE;
if (alwaysFalse) {
if (error) {
//Assign a value to error
}
return FALSE;
}
return TRUE;
}
And I'm trying to determine if there is some way from outside the method to manipulate it such that alwaysFalse can be assigned a value of TRUE and the method can be made to return FALSE
If x = false, then x || true will always evaluate to true. If this is how you have to unit test though, I bet there is a better way to write your original function. Post it if you're looking for suggestions for improvement.

Checking if array contains two objects

I'm attempting to implement the containsObject but with two parameters, is this possible?
Currently I've got:
if ([ myArray containsObject:#"Object1", #"Object2"]){
return result;
} else {
return NO;
}
and apparently there's too many arguments. I've delved through Apple's docs but I'm yet to find anything. Any suggestions?
Why not just do this?
if ([ myArray containsObject:#"Object1" ] && [ myArray containsObject:#"Object 2" ] ){
return result;
} else {
return NO;
}
There is too many arguments, containsObject is for a single object. (You can read its official documentation here) To fix your problem, use the && operator and call containsObject on each object individually.
if ([myArray containsObject:#"Object1"] && [myArray containsObject#"Object2"]){
return result;
} else {
return NO;
}
You will have to evaluate them individually. Example:
bool MONNSArrayContainsAllObjectsIn(NSArray* const pArray, NSArray* const pSought) {
assert(pArray);
assert(pSought);
assert(0 < pSought.count);
for (id at in pSought) {
if (false == [pArray containsObject:at]) {
return false;
}
}
return true;
}
Then your code above becomes:
return MONNSArrayContainsAllObjectsIn(myArray, #[#"Object1", #"Object2"]);
If you are working with a known number of elements (2 in this case), then you can avoid creating the temporary array -- if you prefer to make that optimization and write out all variants you need, including parameters. Other answers detail this approach.
If you have large arrays and many comparisons to perform, NSSet may be better suited for your task.

Resources