1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | var prettySize = function(bytes){
|
13 | if(bytes >= 9900) {
|
14 | return Math.round(bytes / 100) / 10 +"kb";
|
15 | }
|
16 | if(bytes > 200) {
|
17 | return Math.round(bytes / 10) / 100+"kb";
|
18 | }
|
19 | return bytes+"b";
|
20 | };
|
21 |
|
22 | var _ = require("lodash"),
|
23 | nodeSize = require("../node/size"),
|
24 | winston = require('winston');
|
25 | var getMostBundled = function(sharedGraph){
|
26 | if (!sharedGraph.length ) {
|
27 | return null;
|
28 | }
|
29 |
|
30 | var mostShared = sharedGraph.pop(),
|
31 | mostSize = 0,
|
32 | most;
|
33 |
|
34 |
|
35 |
|
36 | for ( var apps in mostShared ) {
|
37 | if ( mostShared[apps].size > mostSize ) {
|
38 | most = mostShared[apps];
|
39 | mostSize = most.size;
|
40 | }
|
41 | }
|
42 |
|
43 | winston.debug(' bundle for '+most.bundles+" "+prettySize(mostSize)+":");
|
44 |
|
45 |
|
46 | most.nodes = most.nodes.sort(function( f1, f2 ) {
|
47 | return f1.order - f2.order;
|
48 | });
|
49 |
|
50 | most.nodes.forEach(function(node){
|
51 | winston.debug(' + '+node.load.name);
|
52 | });
|
53 | return most;
|
54 | };
|
55 |
|
56 |
|
57 | module.exports = function(graph){
|
58 |
|
59 |
|
60 | var bundled = {};
|
61 |
|
62 | |
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | var makeSharedGraph = function(){
|
85 | var sharedGraph = [];
|
86 | for(var name in graph) {
|
87 |
|
88 | if(bundled[name]) {
|
89 | continue;
|
90 | }
|
91 | var node = graph[name];
|
92 |
|
93 | var sharedSet = setProp(sharedGraph, node.bundles.length, {});
|
94 |
|
95 |
|
96 | var bundlesName = node.bundles.sort().join(),
|
97 |
|
98 | sharing = setProp(sharedSet, bundlesName, function(){
|
99 | return {
|
100 | size: 0,
|
101 | nodes: [],
|
102 | bundles: node.bundles
|
103 | };
|
104 | });
|
105 |
|
106 | sharing.nodes.push(node);
|
107 | sharing.size += nodeSize(node);
|
108 | }
|
109 | return sharedGraph;
|
110 | };
|
111 |
|
112 |
|
113 | var bundles = [],
|
114 | bundle;
|
115 |
|
116 | while( ( bundle = getMostBundled( makeSharedGraph() ) ) ) {
|
117 |
|
118 |
|
119 | bundle.nodes.forEach(function(n){
|
120 | bundled[n.load.name] = true;
|
121 | });
|
122 |
|
123 | bundles.push(bundle);
|
124 | }
|
125 | return bundles;
|
126 | };
|
127 |
|
128 |
|
129 | var setProp = function(root, prop, raw, cb){
|
130 | if(!root[prop]){
|
131 | root[prop] = ( typeof raw === 'object' ?
|
132 | _.assign({},raw) :
|
133 | raw() );
|
134 | }
|
135 |
|
136 | if(cb) {
|
137 | cb( root[prop] );
|
138 | }
|
139 | return root[prop];
|
140 | };
|
141 |
|
142 |
|