• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (c) 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'use strict';
6
7base.require('base.iteration_helpers');
8
9base.exportTo('base', function() {
10  /**
11   * Adds a {@code getInstance} static method that always return the same
12   * instance object.
13   * @param {!Function} ctor The constructor for the class to add the static
14   *     method to.
15   */
16  function addSingletonGetter(ctor) {
17    ctor.getInstance = function() {
18      return ctor.instance_ || (ctor.instance_ = new ctor());
19    };
20  }
21
22  function instantiateTemplate(selector) {
23    return document.querySelector(selector).content.cloneNode(true);
24  }
25
26  function tracedFunction(fn, name, opt_this) {
27    function F() {
28      console.time(name);
29      try {
30        fn.apply(opt_this, arguments);
31      } finally {
32        console.timeEnd(name);
33      }
34    }
35    return F;
36  }
37
38  function normalizeException(e) {
39    if (typeof(e) == 'string') {
40      return {
41        message: e,
42        stack: ['<unknown>']
43      };
44    }
45
46    return {
47      message: e.message,
48      stack: e.stack ? e.stack : ['<unknown>']
49    };
50  }
51
52  function stackTrace() {
53    var stack = new Error().stack + '';
54    stack = stack.split('\n');
55    return stack.slice(2);
56  }
57
58  return {
59    addSingletonGetter: addSingletonGetter,
60
61    tracedFunction: tracedFunction,
62    normalizeException: normalizeException,
63    instantiateTemplate: instantiateTemplate,
64    stackTrace: stackTrace
65  };
66});
67
68