Nodejs Array Search search(key)

Here you can find the source of search(key)

Method Source Code

Array.prototype.search = function(key) {
  'use strict';/*from  ww  w.  j a v a  2 s.  c  o m*/
  var max = this.length - 1;
  var min = 0;
  var count = 0;
  while (min <= max) {
    var mid = Math.floor((min + max) / 2);
    if (this[mid] === key) {
      return {
        index: mid,
        count: count,
        length: this.length
      };
    }

    if (this[min] === key) {
      return {
        index: min,
        count: count,
        length: this.length
      };
    }

    if (this[max] === key) {
      return { index: max, count: count, length: this.length };
    }
    if (this[mid] < key) {
      min = mid + 1;
      max = max - 1;
    } else if (this[mid] > key) {
      max = mid - 1;
      min = min + 1;
    }
    count++;
  }

  return {
    count: count,
    length: this.length,
    index: -1
  };
};

module.exports = {
  Array: Array
};

Related

  1. search(expression)
    Array.prototype.search=function(expression){
      var copy = expression;
      expression = expression.replace(/[a-zA-Z0-9]+/g, "#");
      var numbers = copy.split(/[^a-zA-Z0-9]+/).filter(function(n){return n});
      var operators = expression.split("#").filter(function(n){return n});
      var query = [],oi=0,ni=0;
      for(i = 0; i < expression.length; i++){
          if('-'==expression[i] || expression[i]=='+'){
              query.push(operators[oi++]);
    ...
    
  2. search(k)
    Array.prototype.search = function(k){
      var a = this;
      this.sort(a);
      var max=a.length-1,min=0,mid;
      while(min<=max){
        mid=(max+min)>>>1;
        if(k>a[mid])
          min = mid+1;
        else if(k<a[mid])
    ...
    
  3. search(key, value)
    Array.prototype.search = function (key, value) {
        return this.reduce(function (result, el) {
            if (result) return result;
            if (key) {
                if (typeof key === "function") {
                    if (key(el) === value) {
                        return el;
                } else {
    ...
    
  4. search(key, value)
    Array.prototype.search = function (key, value) {
        if (arguments.length == 1) {
            return this.filter(function (e) {
                return e == value;
            });
        if (arguments.length == 2) {
            var k = arguments[0];
            var value = arguments[1];
    ...
    
  5. search(n)
    Array.prototype.search = function(n) {
      var start = 0;
      var end = this.length - 1;
      var result = {count: 0, index: -1, length: this.length};
      while (start <= end) {
        mid = (start + end) / 2 >> 0;
        if (this[start] === n) {
          result.index = start;
          return result;
    ...
    
  6. search(search_func)
    Array.prototype.search = function(search_func){
        for (var i= 0; i<this.length; i++){
            if (search_func(this[i]) == 0)
                return this[i]
        return null;