diff --git a/example/example2.js b/example/example2.js new file mode 100644 index 0000000..bcfa1b9 --- /dev/null +++ b/example/example2.js @@ -0,0 +1,35 @@ +var bounds = require('../search-bounds') + +//Create an array +var array = [1, 2, 3, 3, 3, 5, 6, 10, 11, 13, 50, 1000, 2200] +console.log({array}) + +//Print all elements in array contained in the interval [3, 50) +console.log( + array.slice( + bounds.ge(array, 3), + bounds.lt(array, 50))) + +//Test if array contains the element 4 +console.log('indexOf(6)=', bounds.eq(array, 6)) +let index = bounds.eq(array, 4) +console.log('indexOf(4)=', index) + +function insert (array, value) { + let index = bounds.eq(array,value) + console.log({index}) + if (index < 0) array.splice(-index-1,0,value) + else array.splice(index,0,value) +} +console.log('Insert') +insert(array, 4) +console.log({array}) + +insert(array, 4) +insert(array, 4) +insert(array, 4) +insert(array, 0) +insert(array, 12) +insert(array, 200) +insert(array, 12200) +console.log({array}) diff --git a/example/example3.js b/example/example3.js new file mode 100644 index 0000000..a8920aa --- /dev/null +++ b/example/example3.js @@ -0,0 +1,36 @@ +var bounds = require('../search-bounds') + +// Create an array of objects +var creatures = [ + { legs: 8, name: 'spider' }, + { legs: 4, name: 'mouse' }, + { legs: 4, name: 'cat' }, + { legs: 2, name: 'Ben Franklin' }, + { legs: 4, name: 'table', isCreature: false }, + { legs: 100, name: 'centipede' }, + { legs: 4, name: 'dog' }, + { legs: 6, name: 'ant' } +] + +// Sort the array by number of legs +function byLegs(a,b) { return a.legs - b.legs } +creatures.sort(byLegs) + +// Find the next creature with more than 4 legs +console.log('What has more than 4 legs? Answer:', creatures[bounds.gt(creatures, {legs:4}, byLegs)]) + +let names = [ + 'jan', + 'piet', + 'koos', + 'klaas', + 'alta', + 'kaspaas' +] +function nameSort(a,b) { + return (a).localeCompare(b) +} +names.sort(nameSort) +console.log({names}) + +console.log('Who is before klaas?', names[ bounds.lt(names, 'klaas', nameSort)]) diff --git a/search-bounds.js b/search-bounds.js index c39ffbf..e08d818 100644 --- a/search-bounds.js +++ b/search-bounds.js @@ -21,7 +21,7 @@ function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) { } code.push("}") if(earlyOut) { - code.push("return -1};") + code.push("return -l - 1};") } else { code.push("return i};") }