1// Copyright 2013 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5/** 6 * This function returns the first element index that >= target, when no element 7 * in the array >= target, return array.length. 8 * This function must be called in the shape of binarySearch(array, target). 9 * @param {number} target 10 * @return {number} 11 */ 12var binarySearch = function(target) { 13 'use strict'; 14 15 var left = 0; 16 var right = this.length - 1; 17 while (left <= right) { 18 var mid = Math.floor((left + right) / 2); 19 if (this[mid] < target) 20 left = mid + 1; 21 else if (this[mid] > target) 22 right = mid - 1; 23 else 24 return mid; 25 } 26 return left; 27}; 28 29/** 30 * Return the intersection set of two sorted arrays. 31 * @param {Array.<*>} left 32 * @param {Array.<*>} right 33 * @return {Array.<*>} 34 */ 35var intersectionOfSorted = function(left, right) { 36 var from = 0; 37 return left.reduce(function(previous, current) { 38 var idx = right.indexOf(current, from); 39 if (idx != -1) { 40 previous.push(current); 41 from = idx; 42 } 43 return previous; 44 }, []); 45}; 46 47/** 48 * Output object with indented format. 49 * @param {Object} obj 50 * @param {string} title 51 */ 52var inspect = function(obj, title) { 53 if (title) console.log(title); 54 console.log(JSON.stringify(obj, null, 2)); 55}; 56