Created
October 8, 2018 01:52
-
-
Save cemolcay/e5aa0952018df09c824467035640697e to your computer and use it in GitHub Desktop.
An array subscript extension that returns the element from the positive or negative circular index.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Array { | |
/// An array subscript extension that returns the element from the positive or negative circular index. | |
public subscript(circular index: Int) -> Element? { | |
guard count > 0 else { return nil } | |
let mod = index % count | |
let offset = index >= 0 ? 0 : count | |
let idx = mod == 0 ? 0 : mod + offset | |
return self[idx] | |
} | |
} | |
// Examples | |
let a = [0, 1, 2, 3, 4, 5] | |
a[circular: 0] // 0 | |
a[circular: 1] // 1 | |
a[circular: 2] // 2 | |
a[circular: 3] // 3 | |
a[circular: 4] // 4 | |
a[circular: 5] // 5 | |
a[circular: 6] // 0 | |
a[circular: 7] // 1 | |
a[circular: 8] // 2 | |
a[circular: 12] // 0 | |
a[circular: -1] // 5 | |
a[circular: -2] // 4 | |
a[circular: -3] // 3 | |
a[circular: -4] // 2 | |
a[circular: -5] // 1 | |
a[circular: -6] // 0 | |
a[circular: -7] // 5 | |
a[circular: -12] // 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment