@@ -1444,19 +1444,18 @@ pub fn[T] Array::extract_if(self : Array[T], f : (T) -> Bool) -> Array[T] {
14441444/// let arr : Array[Int] = []
14451445/// inspect(arr.chunks(3), content="[]")
14461446/// ```
1447- pub fn [T ] Array ::chunks (self : Array [T ], size : Int ) -> Array [Array [T ]] {
1447+ pub fn [T ] Array ::chunks (self : Array [T ], size : Int ) -> Array [ArrayView [T ]] {
14481448 guard size > 0
1449- let chunks = []
1450- let mut i = 0
1451- while i < self .length () {
1452- let chunk = Array ::new (capacity = size )
1453- for j = 0 ; j < size && i < self .length (); j = j + 1 {
1454- chunk .push (self [i ])
1455- i = i + 1
1456- }
1457- chunks .push (chunk )
1449+ let len = self .length ()
1450+ if len == 0 {
1451+ return []
14581452 }
1459- chunks
1453+ let num_chunks = (len + size - 1 ) / size
1454+ Array ::makei (num_chunks , i => {
1455+ let start = i * size
1456+ let end = Int ::min (start + size , len )
1457+ self [start :end ]
1458+ })
14601459}
14611460
14621461///|
@@ -1486,19 +1485,19 @@ pub fn[T] Array::chunks(self : Array[T], size : Int) -> Array[Array[T]] {
14861485pub fn [T ] Array ::chunk_by (
14871486 self : Array [T ],
14881487 pred : (T , T ) -> Bool raise ?,
1489- ) -> Array [Array [T ]] raise ? {
1488+ ) -> Array [ArrayView [T ]] raise ? {
14901489 let chunks = []
1491- let mut i = 0
1492- while i < self . length () {
1493- let chunk = []
1494- chunk . push ( self [ i ])
1495- i = i + 1
1496- while i < self . length () && pred (self [i - 1 ], self [i ]) {
1497- chunk .push (self [i ])
1498- i = i + 1
1490+ if self . is_empty () {
1491+ return chunks
1492+ }
1493+ let mut start = 0
1494+ for i in 1 .. < self . length () {
1495+ if ! pred (self [i - 1 ], self [i ]) {
1496+ chunks .push (self [start : i ])
1497+ start = i
14991498 }
1500- chunks .push (chunk )
15011499 }
1500+ chunks .push (self [start :self .length ()])
15021501 chunks
15031502}
15041503
0 commit comments