Skip to content

Commit

Permalink
fix: to_array in queue
Browse files Browse the repository at this point in the history
  • Loading branch information
Lampese committed Mar 26, 2024
1 parent 6b95f92 commit 1b4ee4f
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions queue/queue.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,33 @@ pub fn Queue::from_array[T](arr : Array[T]) -> Queue[T] {
}
let queue : Queue[T] = Queue::new()
queue.length = arr.length()
for i = arr.length(); i > 0; i = i - 1 {
let cell : Cell[T] = Cons({ content: arr[i - 1], next: queue.first })
queue.first = cell
queue.last = Cons({ content: arr[queue.length - 1], next: Nil })
queue.first = queue.last
for i = arr.length() - 2; i >= 0; i = i - 1 {
queue.first = Cons({ content: arr[i], next: queue.first })
}
queue.last = queue.first
queue
}

test "from_array_1" {
let queue : Queue[Int] = Queue::[1, 2, 3, 4]
let queue2 : Queue[Int] = Queue::[1]
@assertion.assert_eq(queue.length, 4)?
@assertion.assert_eq(queue.pop_exn(), 1)?
@assertion.assert_eq(queue.pop_exn(), 2)?
@assertion.assert_eq(queue.pop_exn(), 3)?
@assertion.assert_eq(queue.pop_exn(), 4)?
@assertion.assert_eq(queue2.pop_exn(), 1)?
@assertion.assert_eq(queue2.length, 0)?
}

test "from_array_2" {
let q = Queue::[1, 2, 3, 4]
q.push(11)
@assertion.assert_eq(q.pop_exn(), 1)?
@assertion.assert_eq(q.pop_exn(), 2)?
}

/// Tests if two queue cells are equal.
fn op_equal[T : Eq](self : Cell[T], other : Cell[T]) -> Bool {
loop self, other {
Expand All @@ -61,18 +80,6 @@ fn op_equal[T : Eq](self : Cell[T], other : Cell[T]) -> Bool {
}
}

test "from_array" {
let queue : Queue[Int] = Queue::[1, 2, 3, 4]
let queue2 : Queue[Int] = Queue::[1]
@assertion.assert_eq(queue.length, 4)?
@assertion.assert_eq(queue.pop_exn(), 1)?
@assertion.assert_eq(queue.pop_exn(), 2)?
@assertion.assert_eq(queue.pop_exn(), 3)?
@assertion.assert_eq(queue.pop_exn(), 4)?
@assertion.assert_eq(queue2.pop_exn(), 1)?
@assertion.assert_eq(queue2.length, 0)?
}

/// Clears the queue.
///
/// # Example
Expand Down

0 comments on commit 1b4ee4f

Please sign in to comment.