Debian Codegraph @

deferred/profiler.js

raw
1 "use strict";
2
3 var partial = require("es5-ext/function/#/partial")
4 , forEach = require("es5-ext/object/for-each")
5 , pad = require("es5-ext/string/#/pad")
6 , deferred = require("./deferred");
7
8 var resolved, rStats, unresolved, uStats, profile;
9
10 exports.profile = function () {
11 resolved = 0;
12 rStats = {};
13 unresolved = 0;
14 uStats = {};
15 deferred._profile = profile;
16 };
17
18 profile = function (isResolved) {
19 var stack, data;
20
21 if (isResolved) {
22 ++resolved;
23 data = rStats;
24 } else {
25 ++unresolved;
26 data = uStats;
27 }
28
29 stack = new Error().stack;
30 if (
31 !stack.split("\n").slice(3).some(function (line) {
32 if (
33 line.search(/[/\\]deferred[/\\]/) === -1 &&
34 line.search(/[/\\]es5-ext[/\\]/) === -1 &&
35 line.indexOf(" (native)") === -1
36 ) {
37 line = line.replace(/\n/g, "\\n").trim();
38 if (!data[line]) {
39 data[line] = { count: 0 };
40 }
41 ++data[line].count;
42 return true;
43 }
44 return false;
45 })
46 ) {
47 if (!data.unknown) {
48 data.unknown = { count: 0, stack: stack };
49 }
50 ++data.unknown.count;
51 }
52 };
53
54 exports.profileEnd = function () {
55 var total, lpad, log = "";
56
57 if (!deferred._profile) {
58 throw new Error("Deferred profiler was not initialized");
59 }
60 delete deferred._profile;
61
62 log += "------------------------------------------------------------\n";
63 log += "Deferred usage statistics:\n\n";
64
65 total = String(resolved + unresolved);
66 lpad = partial.call(pad, " ", total.length);
67 log += total + " Total promises initialized\n";
68 log += lpad.call(unresolved) + " Initialized as Unresolved\n";
69 log += lpad.call(resolved) + " Initialized as Resolved\n";
70
71 if (unresolved) {
72 log += "\nUnresolved promises were initialized at:\n";
73 forEach(
74 uStats,
75 function (data, name) { log += lpad.call(data.count) + " " + name + "\n"; },
76 null,
77 function (data1, data2) { return this[data2].count - this[data1].count; }
78 );
79 }
80
81 if (resolved) {
82 log += "\nResolved promises were initialized at:\n";
83 forEach(
84 rStats,
85 function (data, name) { log += lpad.call(data.count) + " " + name + "\n"; },
86 null,
87 function (data1, data2) { return this[data2].count - this[data1].count; }
88 );
89 }
90 log += "------------------------------------------------------------\n";
91
92 return {
93 log: log,
94 resolved: { count: resolved, stats: rStats },
95 unresolved: { count: unresolved, stats: uStats }
96 };
97 };