Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Added negative index support to List_at()
  • Loading branch information
tj committed Aug 21, 2010
1 parent 581f071 commit 5b89a01
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/list.c
Expand Up @@ -115,15 +115,23 @@ List_find(List *self, void *val) {

ListNode *
List_at(List *self, int index) {
ListDirection direction = LIST_HEAD;

if (index < 0) {
direction = LIST_TAIL;
index = ~index;
}

if (index < self->len) {
ListIterator *it = ListIterator_new(self, LIST_HEAD);
ListIterator *it = ListIterator_new(self, direction);
ListNode *node = ListIterator_next(it);
while (index--) {
node = ListIterator_next(it);
};
ListIterator_destroy(it);
return node;
}

return NULL;
}

Expand Down
5 changes: 5 additions & 0 deletions test.c
Expand Up @@ -105,6 +105,11 @@ test_List_at() {
assert(b == List_at(list, 1));
assert(c == List_at(list, 2));
assert(NULL == List_at(list, 3));

assert(c == List_at(list, -1));
assert(b == List_at(list, -2));
assert(a == List_at(list, -3));
assert(NULL == List_at(list, -4));
}

static void
Expand Down

0 comments on commit 5b89a01

Please sign in to comment.