=============== Summary ===============
Change Set: LinkedList copyFromTo
Date: 10 January 2024
Author: Christoph Thiede
Adds efficient version of LinkedList>>#copyFrom:to: and tests edge cases.
=============== Diff ===============
LinkedList>>copyFrom:to: {copying} · ct 1/10/2024 17:55
+ copyFrom: startIndex to: stopIndex
+ "Optimized for copying in O(n) instead of O(n^2)."
+
+ | copy i |
+ startIndex <= 0 ifTrue: [^ self error: 'startIndex is out of bounds'].
+ stopIndex < 0 ifTrue: [^ self error: 'stopIndex is out of bounds'].
+ copy := self class new.
+ i := 0.
+ self linksDo: [:link |
+ (i := i + 1) >= startIndex ifTrue:
+ [i > stopIndex ifTrue: [^ copy].
+ copy addLast: link value]].
+ i + 1 < startIndex ifTrue: [^ self error: 'startIndex is out of bounds'].
+ i >= stopIndex ifTrue: [^ copy].
+ ^ self error: 'stopIndex is out of bounds'
LinkedListTest>>testCopyFromToBounds {tests - copying part of sequenceable} · ct 1/10/2024 17:31
+ testCopyFromToBounds
+ | collection |
+ collection := self collectionWithoutEqualElements .
+
+ self
+ should: [collection copyFrom: 0 to: -1]
+ raise: Error.
+ self assert: (collection copyFrom: 1 to: 0) isEmpty.
+ self assert: (collection copyFrom: 2 to: 1) isEmpty.
+ self assert: (collection copyFrom: collection size to: collection size - 1) isEmpty.
+ self assert: (collection copyFrom: collection size + 1 to: collection size) isEmpty.
+ self
+ should: [collection copyFrom: collection size + 2 to: collection size + 1]
+ raise: Error.
+
+ self
+ should: [collection copyFrom: 0 to: 0]
+ raise: Error.
+ self assert: (collection copyFrom: 1 to: 1) asArray = {collection first}.
+ self assert: (collection copyFrom: collection size to: collection size) asArray = {collection last}.
+ self
+ should: [collection copyFrom: collection size + 1 to: collection size + 1]
+ raise: Error.
+
+ self assert: (collection copyFrom: 1 to: collection size) = collection.
+ self
+ should: [collection copyFrom: 0 to: collection size]
+ raise: Error.
+ self
+ should: [collection copyFrom: 1 to: collection size + 1]
+ raise: Error.
+
+ self
+ should: [collection copyFrom: 1 to: -1]
+ raise: Error.
+ self assert: (collection copyFrom: 2 to: 0) isEmpty.
+ self assert: (collection copyFrom: collection size + 1 to: collection size - 1) isEmpty.
+ self
+ should: [collection copyFrom: collection size + 2 to: collection size]
+ raise: Error.
---
Sent from Squeak Inbox Talk
["LinkedList copyFromTo.1.cs"]