OLD | NEW |
| (Empty) |
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 */ | |
12 var 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 arrays. | |
31 * @param {Array.<*>} left | |
32 * @param {Array.<*>} right | |
33 * @return {Array.<*>} | |
34 */ | |
35 var intersection = function(left, right) { | |
36 return left.reduce(function(previous, current) { | |
37 if (right.indexOf(current) != -1) | |
38 previous.push(current); | |
39 return previous; | |
40 }, []); | |
41 }; | |
42 | |
43 /** | |
44 * Return the difference set of left with right. | |
45 * Notice: difference(left, right) differentiates with difference(right, left). | |
46 * @param {Array.<*>} left | |
47 * @param {Array.<*>} right | |
48 * @return {Array.<*>} | |
49 */ | |
50 var difference = function(left, right) { | |
51 return left.reduce(function(previous, current) { | |
52 if (right.indexOf(current) == -1) | |
53 previous.push(current); | |
54 return previous; | |
55 }, []); | |
56 }; | |
57 | |
58 /** | |
59 * Output object with indented format. | |
60 * @param {Object} obj | |
61 * @param {string} title | |
62 */ | |
63 var inspect = function(obj, title) { | |
64 if (title) console.log(title); | |
65 console.log(JSON.stringify(obj, null, 2)); | |
66 }; | |
OLD | NEW |