all files / mapbox-gl-draw/src/lib/ sort_features.js

100% Statements 15/15
100% Branches 6/6
100% Functions 4/4
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40               63×   63×     62×         457× 148× 55×           148×       148× 148×        
const area = require('geojson-area');
const Constants = require('../constants');
 
const FEATURE_SORT_RANKS = {
  Point: 0,
  LineString: 1,
  Polygon: 2
};
 
function comparator(a, b) {
  const score = FEATURE_SORT_RANKS[a.geometry.type] - FEATURE_SORT_RANKS[b.geometry.type];
 
  if (score === 0 && a.geometry.type === Constants.geojsonTypes.POLYGON) {
    return a.area - b.area;
  }
 
  return score;
}
 
// Sort in the order above, then sort polygons by area ascending.
function sortFeatures(features) {
  return features.map(feature => {
    if (feature.geometry.type === Constants.geojsonTypes.POLYGON) {
      feature.area = area.geometry({
        type: Constants.geojsonTypes.FEATURE,
        property: {},
        geometry: feature.geometry
      });
    }
    return feature;
  })
  .sort(comparator)
  .map(feature => {
    delete feature.area;
    return feature;
  });
}
 
module.exports = sortFeatures;