Up2Bottom and Left2Right Sorting Algorithm


// ========================================================
// Up2Bottom and Left2Right Sorting Algorithm
// addressing (weakly) sparse rectangles
// —
// Usage: Select the objects, then run the script
// Target: InDesign CS4/CS5/CS6/CC
// ========================================================

const CS = +CoordinateSpaces.SPREAD_COORDINATES,
AP_MIN = +AnchorPoint.TOP_LEFT_ANCHOR,
AP_CENTER = +AnchorPoint.CENTER_ANCHOR,
AP_MAX = +AnchorPoint.BOTTOM_RIGHT_ANCHOR;

var sel = app.properties.selection || null,
data = [],
r, i, j, k, t, n, w, vMax;

if( sel && 1 < (n=sel.length) ) { // Collect coordinates and IDs // --> {min:[xLeft, yTop], weight:[x,y], max:[xRight,yBottom], id}[]
for(i=0 ; i < n && (t=sel[i]) ; ++i ) { data[i] = { min: t.resolve(AP_MIN,CS)[0], weight: t.resolve(AP_CENTER,CS)[0], max: t.resolve(AP_MAX,CS)[0], id: t.id }; } // Find rows and columns [i.e. y-weights and x-weights] // --- for( j=0 ; j < 2 ; ++j ) { // Sort by center coordinate // --- data.sort(function(a,b){return a.weight[j] - b.weight[j]}); // min > max ==> w++
// —
for(vMax=(t=data[0]).max[j], t.weight[j]=(w=0), i=1 ; (i < n)&&(t=data[i]) ; ++i ) { if( t.min[j] > vMax ){ ++w; vMax=t.max[j]; }
t.weight[j] = w;
}
}

// Compute final weights, clean up data, create ID-to-weight access
// —
for( i=0 ; (i < n)&&(t=data[i]) ; ++i ) { w = n*t.weight[1] + t.weight[0]; // final weight (y first) k = '_'+t.id; // ID key (t.min.length=0)||(t.weight.length=0)||(t.max.length=0); delete t.min; delete t.weight; delete t.max; delete t.id; delete data[i]; data[k] = w; // ID-to-weight } // Apply sort --> r
// —
r = sel.sort(function(a,b){return data[‘_’+a.id]-data[‘_’+b.id];});

// Show the resulting order
// —
for( i=0 ; i < n ; ++i ) { app.select(r[i]); $.sleep(1000); } }


답글 남기기

이메일 주소는 공개되지 않습니다.