All files / lib/helpers normalize-extent.js

100% Statements 23/23
100% Branches 10/10
100% Functions 4/4
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671x   1x                       1x 1x   1x 17x   16x   16x 5x     11x   11x 1x     10x   10x 2x     8x       37x 37x 8x       5x                   1x                
const joi = require('joi')
 
const esriExtentSchema = joi.object({
  xmin: joi.number().required(),
  xmax: joi.number().required(),
  ymin: joi.number().required(),
  ymax: joi.number().required(),
  type: joi.string().optional(),
  spatialReference: joi.object().keys({
    wkid: joi.number().integer().optional(),
    latestWkid: joi.number().integer().optional()
  }).optional()
}).unknown()
 
const simpleArraySchema = joi.array().items(joi.number().required()).min(4)
const cornerArraySchema = joi.array().items(joi.array().items(joi.number()).length(2)).length(2)
 
module.exports = function (input, spatialReference) {
  if (!input) return undefined
 
  const { value: arrayExtent } = validate(input, simpleArraySchema)
 
  if (arrayExtent) {
    return simpleArrayToEsriExtent(arrayExtent, spatialReference)
  }
 
  const { value: cornerArrayExtent } = validate(input, cornerArraySchema)
 
  if (cornerArrayExtent) {
    return cornerArrayToEsriExtent(cornerArrayExtent, spatialReference)
  }
 
  const { value: esriExtent } = validate(input, esriExtentSchema)
 
  if (esriExtent) {
    return { spatialReference, ...esriExtent }
  }
 
  throw new Error(`Received invalid extent: ${JSON.stringify(input)}`)
}
 
function validate (input, schema) {
  const { error, value } = schema.validate(input)
  if (error) return { error }
  return { value }
}
 
function simpleArrayToEsriExtent (arrayExent, spatialReference) {
  return {
    xmin: arrayExent[0],
    ymin: arrayExent[1],
    xmax: arrayExent[2],
    ymax: arrayExent[3],
    spatialReference
  }
}
 
function cornerArrayToEsriExtent (cornerArrayExtent, spatialReference) {
  return {
    xmin: cornerArrayExtent[0][0],
    ymin: cornerArrayExtent[0][1],
    xmax: cornerArrayExtent[1][0],
    ymax: cornerArrayExtent[1][1],
    spatialReference
  }
}