react / react-0.13.3 / examples / basic-commonjs / node_modules / browserify / node_modules / deps-sort / index.js
80713 viewsvar through = require('through2');1var shasum = require('shasum');23module.exports = function (opts) {4if (!opts) opts = {};5var rows = [];6return through.obj(write, end);78function write (row, enc, next) { rows.push(row); next() }910function end () {11var tr = this;12rows.sort(cmp);13sorter(rows, tr, opts);14}15};1617function sorter (rows, tr, opts) {18var expose = opts.expose || {};19if (Array.isArray(expose)) {20expose = expose.reduce(function (acc, key) {21acc[key] = true;22return acc;23}, {});24}2526var hashes = {}, deduped = {};27var sameDeps = depCmp();2829if (opts.dedupe) {30rows.forEach(function (row) {31var h = shasum(row.source);32sameDeps.add(row, h);33if (hashes[h]) {34hashes[h].push(row);35} else {36hashes[h] = [row];37}38});39Object.keys(hashes).forEach(function (h) {40var rows = hashes[h];41while (rows.length > 1) {42var row = rows.pop();43row.dedupe = rows[0].id;44row.sameDeps = sameDeps.cmp(rows[0].deps, row.deps);45deduped[row.id] = rows[0].id;46}47});48}4950if (opts.index) {51var index = {};52var offset = 0;53rows.forEach(function (row, ix) {54if (has(expose, row.id)) {55row.index = row.id;56offset ++;57if (expose[row.id] !== true) {58index[expose[row.id]] = row.index;59}60}61else {62row.index = ix + 1 - offset;63}64index[row.id] = row.index;65});66rows.forEach(function (row) {67row.indexDeps = {};68Object.keys(row.deps).forEach(function (key) {69var id = row.deps[key];70row.indexDeps[key] = index[id];71});72if (row.dedupe) {73row.dedupeIndex = index[row.dedupe];74}75tr.push(row);76});77}78else {79rows.forEach(function (row) { tr.push(row) });80}81tr.push(null);82}8384function cmp (a, b) {85return a.id + a.hash < b.id + b.hash ? -1 : 1;86}8788function has (obj, key) {89return Object.prototype.hasOwnProperty.call(obj, key);90}9192function depCmp () {93var deps = {}, hashes = {};94return { add: add, cmp: cmp }9596function add (row, hash) {97deps[row.id] = row.deps;98hashes[row.id] = hash;99}100function cmp (a, b, limit) {101if (!a && !b) return true;102if (!a || !b) return false;103104var keys = Object.keys(a);105if (keys.length !== Object.keys(b).length) return false;106107for (var i = 0; i < keys.length; i++) {108var k = keys[i], ka = a[k], kb = b[k];109var ha = hashes[ka];110var hb = hashes[kb];111var da = deps[ka];112var db = deps[kb];113114if (ka === kb) continue;115if (ha !== hb || (!limit && !cmp(da, db, 1))) {116return false;117}118}119return true;120}121}122123124