From c4d2bb7a3db30a0e2e74b19e721e74f65f7edad4 Mon Sep 17 00:00:00 2001 From: rlx <0x0073@0x2620.org> Date: Thu, 18 Jul 2013 12:52:47 +0000 Subject: [PATCH] add Ox.nextValue --- source/Ox/js/Array.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/source/Ox/js/Array.js b/source/Ox/js/Array.js index 41b6ce86..b23e4be8 100644 --- a/source/Ox/js/Array.js +++ b/source/Ox/js/Array.js @@ -568,6 +568,35 @@ Ox.makeArray = function(value) { return ret; }; +/*@ +Ox.nextValue Next value, given an array of numbers, a number and a direction + (array, value, direction) -> Next value + array <[n]> Sorted array of numbers + value Number + direction Direction (-1 for left or 1 for right) + > Ox.nextValue([0, 2, 4, 6, 8], 5, -1) + 4 + > Ox.nextValue([], 1, 1) + void 0 +@*/ +Ox.nextValue = function(array, value, direction) { + var found = false, nextValue; + direction = direction || 1; + direction == -1 && array.reverse(); + Ox.forEach(array, function(v) { + if (direction == 1 ? v > value : v < value) { + nextValue = v; + found = true; + return false; // break + } + }); + direction == -1 && array.reverse(); + if (!found) { + nextValue = array[direction == 1 ? 0 : array.length - 1]; + } + return nextValue; +}; + /*@ Ox.range Python-style range (stop) -> <[n]> range