From d694e6f78c881990115f299ffa0c71ba00509a72 Mon Sep 17 00:00:00 2001 From: John Foerch Date: Fri, 8 Oct 2010 15:04:16 -0400 Subject: [PATCH] array_find, array_find_index: two new utils array_find returns the first element in the given array that satisfies predicate p. returns null on failure. array_find_index returns the index of the first element in the array that satisfies predicate p. returns -1 on failure. --- modules/array.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/modules/array.js b/modules/array.js index c52d8b0..6f1d455 100644 --- a/modules/array.js +++ b/modules/array.js @@ -29,6 +29,33 @@ function make_array (ob) { return [ob]; } + +/** + * array_find returns the first element in the given array that satisfies + * predicate p. returns null on failure. + */ +function array_find (ar, p) { + for (var i = 0, n = ar.length; i < n; ++i) { + if (p(ar[i])) + return ar[i]; + } + return null; +} + + +/** + * array_find_index returns the index of the first element in the array + * that satisfies predicate p. returns -1 on failure. + */ +function array_find_index (ar, p) { + for (var i = 0, n = ar.length; i < n; ++i) { + if (p(ar[i])) + return i; + } + return -1; +} + + /** * remove_duplicates_filter returns a function that can be used in * Array.filter. It removes duplicates. Optional argument cmp is a -- 2.11.4.GIT