How can I receive count of elements? [duplicate] - cypress

This question already has answers here:
how can i count the elements so i can use the value later?
(3 answers)
Closed last month.
test.js:
cy.get('.ant-input-number-input')
.wait(2000)
.then(($input_field) => {
const count = $input_field.find('.ant-input-number-input').length;
cy.log(count)
})
cy.log:
log 0
I need to get count of elements. But I received '0'. How can I receive count of elements?

Assuming that you are only finding the length of the element .ant-input-number-input, you can do like this:
To get the length
cy.get('.ant-input-number-input')
.should('be.visible')
.its('length')
.then((len) => {
cy.log(len) //prints length
})
if you want to add assertions you can do:
//Length equal to 2
cy.get('.ant-input-number-input')
.should('be.visible')
.its('length')
.should('eq', 2)
//Length greater than 2
cy.get('.ant-input-number-input')
.should('be.visible')
.its('length')
.should('be.gt', 2)
//Length greater than or equal to 2
cy.get('.ant-input-number-input')
.should('be.visible')
.its('length')
.should('be.gte', 2)
//Length less than 2
cy.get('.ant-input-number-input')
.should('be.visible')
.its('length')
.should('be.lt', 2)
//Length less than or equal to 2
cy.get('.ant-input-number-input')
.should('be.visible')
.its('length')
.should('be.lte', 2)

You can use
const count = $input_field.find('.ant-input-number-input').its('length')

Related

can not convert const to number

I have a code which should give number 1 or 5 or 10 or 50.
rust compiler says "pattern 4_u8..=u8::MAX not covered"
the code:
use rand::Rng;
fn main() {
let rand_num: u8 = rand::thread_rng().gen_range(0, 4);
println!("{}", rand_num);
let coin: Coin;
match rand_num{
0 => coin = Coin::Penny,
1 => coin = Coin::Nickel,
2 => coin = Coin::Dime,
3 => coin = Coin::Quarter,
}
println!("{}", value_in_cents(coin));
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin{
Coin::Penny => return 1,
Coin::Nickel => return 5,
Coin::Dime => return 10,
Coin::Quarter => return 25,
}
}
i have no idea how can i fix it
Matches in rust need to be exhaustive. In other words they need to cover every possible case.
When you are matching on the enum Coin you are matching every variant in the enum - so it is valid.
But when you are matching on an integer (in this case, a u8) the possible values can be anywhere from 0 to 255. Consider what happens if the number generated passed to match is 9 - rust would attempt to match and find no matching branch. From there coin would be undefined and the rest of the program would be faulty.
Logically we know that the match will always be exhausted, since rand::thread_rng().gen_range(0, 4); will generate a number within that range. But either way the rules applied to match must be followed. In this case, you can add a fallback branch which will cover any remaining case.
match rand_num{
0 => coin = Coin::Penny,
1 => coin = Coin::Nickel,
2 => coin = Coin::Dime,
3 => coin = Coin::Quarter,
_ => panic!("Invalid coin");
}
This would allow your code to compile - but in the case that an invalid number is generated the program would crash.
As an aside, you could simplify this code by assigning the value of the match directly to the coin variable:
let coin = match rand_num{
0 => Coin::Penny,
1 => Coin::Nickel,
2 => Coin::Dime,
3 => Coin::Quarter,
_ => panic!()
}
Other answers are valid, except for the fact that there is a dedicated instruction for this kind of situations: unreachable!().
match rand_num {
0 => coin = Coin::Penny,
1 => coin = Coin::Nickel,
2 => coin = Coin::Dime,
3 => coin = Coin::Quarter,
_ => unreachable!(),
}
It won't change much, as if unreachable!() is actually reached, it will just panic. However, this greatly improves readability.
Match requires you to list out all possible values that your variable rand_num could match to. In your case, that would be all possible u8 values. The compiler doesn't know your random range cannot generate other numbers than the ones you listed, so it throws out an error. To solve this, use the wildcard pattern:
_ => {panic!()}

How do I memoize the last result in a chain of observables?

I've modelled a navigation concept reactively, (a user navigating forward and backward pages) but I'm having trouble optimizing it using Reactive Extensions. I'm sure it's some kind of buffering or sharing operator, but I'm not quite sure which one it is or where to shove it.
This is a working, simplified example of what I've implemented, in TypeScript and with rxjs.
Each time the user clicks, we increment it by one step. (In reality, there is a network request in here which might return a new step or none, hence why this is not a simple + 1.)
describe('navigate', () => {
it('should increment', () => {
const initial = Observable.of(0);
const plusOne = (ns: Observable<number>) => ns.pipe(map(n => n + 1), tap(x => console.log("Computed", x)));
const clicks = Observable.from([plusOne, plusOne, plusOne]);
const expected = cold("(wxyz|)", { w: 0, x: 1, y: 2, z: 3 });
const result = clicks.pipe(
scan(
(s: Observable<number>, x: (ns: Observable<number>) => Observable<number>) => x(s),
initial),
startWith(initial),
switchAll(),
)
expect(result).toBeObservable(expected);
})
})
It produces the correct output, and the test passes.
But in terms of execution, in the console you'll see this printed:
Computed 1
Computed 1
Computed 2
Computed 1
Computed 2
Computed 3
which makes sense, but if the plusOne operation is expensive (e.g. a network request) it won't do to have the plusOnes computed from the start every time.
How do I memoize the result of the last plusOne so that subsequent plusOnes need not calculate the entire chain again?
Or if I'm looking at this the wrong way, how should I be approaching this problem?
Attempt
Since the top of this question, I did think of one solution.
const result = clicks.pipe(
scan(
(s: Observable<number>, x: (ns: Observable<number>) => Observable<number>) => x(s).pipe(shareReplay(1)),
initial),
startWith(initial),
switchAll(),
)
which executes like:
Computed 1
Computed 2
Computed 3
However I think this leads to a chain which would look like:
xs.map(x => x + 1).shareReplay(1).map(x => x + 1).shareReplay(1).map(x => x + 1).shareReplay(1)
and which I don't think would be terribly efficient (if each shareReplay(1) caches a value). Is there a better way to do this?

Combining expand with other operators in rxjs

Let's say I have a set of rewriting rules that I want my Observable to implement:
A => B B
B => C
That is, whenever there's an A on the observable, output two Bs. Whenever there's a B (even when it comes from an A), output a C. This
seems like natural use case for expand, and it's pretty easy to implement. As expected, each A turns into ABCBC.
But what if I want to combine the expansion with another operator? Let's say my rules are:
A => B repeated N times, where N is the number of "A"s so far.
B => C, but only if the number of "B"s so far is divisible by 10.
Grouping values by whether they're As or Bs sounds like a job for groupBy, and counting the number of outputs for each sounds like scan, but how do I combine those operators with expand?
Two years late and not strictly an answer to your question, but another approach that yields the same result and might be easier to build upon.
Building streams recursively:
This approach builds out your stream recursively. Kind of the same idea you may use to build a nieve parser.
function recursiveOperator(){
return s => s.pipe(
mergeMap(val => concat(
of(val),
streamFor(val)
))
)
}
function streamFor(x){
let stream;
if (x == 'A') {
stream = from(['B','B']);
}else if (x == 'B') {
stream = of('C');
}else{
stream = EMPTY;
}
return stream.pipe(
recursiveOperator()
)
}
zip(
timer(0, 4000),
from(['A','B','A'])
).pipe(
map(([x,y]) => y),
recursiveOperator()
).subscribe(console.log);
output:
abcbc // Then wait 4 seconds
bc // Then wait 4 seconds
abcbc
Using a Subject:
I'm pretty sure that as-is, this introduces a race condition. They're resolved consistently since JS is single-threaded and the event loop is predictable, but you're having two streams each pushing values to the same subject and I haven't yet built in anything that ensures no unwanted interleaving.
With some tweaking, however, this can be much more performant for large inputs.
const valueSubject = new Subject<string>();
valueSubject.subscribe(console.log);
zip(
timer(0, 4000),
from(['A', 'B', 'A'])
).pipe(
map(([x,y]) => y)
).subscribe(val => valueSubject.next(val));
valueSubject.pipe(
tap(val => {
if (val == 'A') {
valueSubject.next('B');
valueSubject.next('B');
}else if (val == 'B') {
valueSubject.next('C');
}
})
).subscribe();
output:
abcbc // Then wait 4 seconds
bc // Then wait 4 seconds
abcbc

Difference Between two numbers without positive or negative in Ruby

I want to find the difference between two numbers (positive integers) without returning any positive or negative sign.
Just like
Diff(2,5) => 3
Diff(5,2) => 3.
And Not
(2 - 5) => -3
You should simply return absolute value:
def diff(a, b)
(a - b).abs
end
diff(2, 5)
# => 3

Sort list of tuples based on second element while alternating over third element

Given a list of tuples:
val mylist = List(('orange', 0.9, 10), ('apple', 0.8, 10), ('mellon', 0.7, 10),
('car', 0.5, 2), ('truck', 0.5, 2),('tablet', 0.3, 3))
I would like to sort them in descending order with respect to the second element of the tuple. However, I would like to pick them by category, one at a time (third element) alternatively. The output should be the following list:
('orange', 0.9, 10)
('car', 0.5, 2)
('tablet', 0.3, 3)
('apple', 0.8, 10)
('truck', 0.5, 2)
('mellon', 0.7, 10)
What would be the functional way of doing it in Scala?
PS: Notice that the the result must reflect the ordering of the third element, that is, 10 appears before 2, and 2 before 3.
You can do this by adding two indices to each item in the list:
The item's category position among all existing categories (i.e. 0 for category 10, 1 for 2 and 2 for 3)
The item's index within its category by descending value of the second tuple element
Once these are added, you can order by them both (with the index withn the category taking precedence)
// traverse once to get a map of Category -> CategoryIndex
val categoryOrder: Map[Int, Int] = mylist.map(_._3).distinct.zipWithIndex.toMap
val result: List[(String, Double, Int)] = mylist
.groupBy(_._3).mapValues(_.sortBy(-_._2).zipWithIndex) // add the index of each item within its category
.toList.flatMap(_._2) // remove group keys and flatMap to get back to tuples
.sortBy { case (t, indx) => (indx, categoryOrder(t._3)) } // order by index in category and category index
.map(_._1) // remove indices
println(result)
// List((orange,0.9,10), (car,0.5,2), (tablet,0.3,3), (apple,0.8,10), (truck,0.5,2), (mellon,0.7,10))

Resources