OLD | NEW |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 var chrome = requireNative('chrome').GetChrome(); | 5 var chrome = requireNative('chrome').GetChrome(); |
6 | 6 |
7 function forEach(dict, f) { | 7 function forEach(obj, f, self) { |
8 for (var key in dict) { | 8 // For arrays, make sure the indices are numbers not strings - and in that |
9 if (dict.hasOwnProperty(key)) | 9 // case this method can be more efficient by assuming the array isn't sparse. |
10 f(key, dict[key]); | 10 // |
| 11 // Note: not (instanceof Array) because the array might come from a different |
| 12 // context than our own. |
| 13 if (obj.constructor && obj.constructor.name == 'Array') { |
| 14 for (var i = 0; i < obj.length; i++) |
| 15 f.call(self, i, obj[i]); |
| 16 } else { |
| 17 for (var key in obj) { |
| 18 if (obj.hasOwnProperty(key)) |
| 19 f.call(self, key, obj[key]); |
| 20 } |
11 } | 21 } |
12 } | 22 } |
13 | 23 |
14 // Assuming |array_of_dictionaries| is structured like this: | 24 // Assuming |array_of_dictionaries| is structured like this: |
15 // [{id: 1, ... }, {id: 2, ...}, ...], you can use | 25 // [{id: 1, ... }, {id: 2, ...}, ...], you can use |
16 // lookup(array_of_dictionaries, 'id', 2) to get the dictionary with id == 2. | 26 // lookup(array_of_dictionaries, 'id', 2) to get the dictionary with id == 2. |
17 function lookup(array_of_dictionaries, field, value) { | 27 function lookup(array_of_dictionaries, field, value) { |
18 var filter = function (dict) {return dict[field] == value;}; | 28 var filter = function (dict) {return dict[field] == value;}; |
19 var matches = array_of_dictionaries.filter(filter); | 29 var matches = array_of_dictionaries.filter(filter); |
20 if (matches.length == 0) { | 30 if (matches.length == 0) { |
(...skipping 12 matching lines...) Expand all Loading... |
33 var parts = ref.split("."); | 43 var parts = ref.split("."); |
34 if (parts.length > 1) | 44 if (parts.length > 1) |
35 return chrome[parts.slice(0, parts.length - 1).join(".")]; | 45 return chrome[parts.slice(0, parts.length - 1).join(".")]; |
36 else | 46 else |
37 return currentApi; | 47 return currentApi; |
38 } | 48 } |
39 | 49 |
40 exports.forEach = forEach; | 50 exports.forEach = forEach; |
41 exports.loadRefDependency = loadRefDependency; | 51 exports.loadRefDependency = loadRefDependency; |
42 exports.lookup = lookup; | 52 exports.lookup = lookup; |
OLD | NEW |