How to create a function to run an undefined amount of coordinates through a function to format them in JS

huangapple go评论66阅读模式
英文:

How to create a function to run an undefined amount of coordinates through a function to format them in JS

问题

我试图创建一个函数通过一个未定义数量的坐标运行先通过一个函数将它们标准化然后用第二个函数格式化它们这是第一个函数用于标准化坐标为其目的而工作:

function normalizeCoord(value) {
  // 代码部分不需要翻译
}

这是我想用来运行未确定数量的坐标的函数不起作用:

function formatCoords(...values) {
  // 代码部分不需要翻译
}

console.log(
  formatCoords(
    normalizeCoord("42.9755,-77.4369", "[-62.1234, 42.9755]", "300,-9000")
  )
);

我真的不确定我该怎么做我尝试上面的方法希望也许能取得一些进展当然不是预期的结果但我希望能得到标准化的坐标然后进行格式化),但我只得到了第一组标准化的坐标-77.4369, 42.9755),然后是"Uncaught Error: Invalid latitude at normalizeCoord"的错误
英文:

I'm trying to create a function run an undefined amount of coordinates through a function that normalizes them, and then format them with the second function. This is the first function, to normalize the coordinates (Working for it's purpose):

function normalizeCoord(value) {
  let noBrackets = value.replace(/[\[\]]+/g, "").replace(/ +/g, "");
  let splitValue = noBrackets.split(",");
  let lat1 = splitValue[0];
  let long1 = splitValue[1];
  let lat2 = splitValue[1];
  let long2 = splitValue[0];
  let result1 = `(${lat1}, ${long1})`;
  let result2 = `(${lat2}, ${long2})`;

  if (result1.charAt(0) === "-" || result2.charAt(0) === "-") {
    result = result2;
  } else {
    result = result1;
  }

  let latInt1 = parseInt(lat1, 10);
  let latInt2 = parseInt(lat2, 10);
  let longInt1 = parseInt(long1, 10);
  let longInt2 = parseInt(long2, 10);

  if (latInt1 < -90 || latInt1 > 90 || latInt2 < -90 || latInt2 > 90) {
    throw new Error("Invalid latitude");
  }

  if (longInt1 < -180 || longInt2 > 180 || longInt2 < -180 || longInt2 > 180) {
    throw new Error("Invalid latitude");
  }

  return result;

This is the function that I want to use to run the undetermined amount of coordinates through (not working):

function formatCoords(...values) {
  let coords = values;

  for (var i = 0, n = coords.length; i < n; i++) {
    normalizeCoord(coords);
  }

  return coords;
}

console.log(
  formatCoords(
    normalizeCoord(("42.9755,-77.4369", "[-62.1234, 42.9755]", "300,-9000"))
  )
);

I'm honestly not sure on how I'm meant to go about this. I tried the above, expecting to maybe get somewhere (not the intended result of course, but of normalized coordinates that I could then format) but I only get back the first set of normalized coordinates (-77.4369, 42.9755), then the throw error of "Uncaught Error: Invalid latitude at normalizeCoord"

答案1

得分: 1

需要使用normalizeCoord的返回值。目前,您进行了规范化,然后只是丢弃了结果。

另外,一次只传递单个坐标:

for (var i = 0, n = coords.length; i < n; i++) {
    try {
        const normalized = normalizeCoord(coords[i]);
        coords[i] = normalized;
    } catch (error) {
        // 出错,不执行任何操作
    }
}
英文:

You need to consume the return value from normalizeCoord. Right now you do the normalization and then just throw away the result.

Also, pass just the single coords at a time:

for (var i = 0, n = coords.length; i &lt; n; i++) {
    try {
        const normalized = normalizeCoord(coords[i]);
        coords[i] = normalized;
    } catch (error) {
        // Error, do nothing
    }
}

答案2

得分: 1

你需要使用 try.. catch

function normalizeCoord( strVals ) {
  const rgxfns = /[+-]?\d+(\.\d+)?/g; // 提取浮点数值
  let
    [v1,v2]   = strVals.match(rgxfns).map(Number),
    [lat,lon] = (v1 < 0 || v2 < 0) ? [v2,v1] : [v1,v2]; // .?
  if (lat < -90  || lat > 90  )  throw new Error('Invalid latitude');
  if (lon < -180 || lon > 180 )  throw new Error('Invalid longitude');

  return `(${lat}, ${lon})`;
}

function formatCoords(...values) {
  const coords = [];
  values.forEach( val => {
    try {
      let coord = normalizeCoord( val );
      coords.push({in:val, out: coord })
    } catch (err) {
      coords.push({in:val, out: err.message })  
    }
  })
  return coords;
}

console.log(
  formatCoords( '42.9755,-77.4369', '[-62.1234, 42.9755]', '300,-9000' )
);
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
英文:

you need to use a try.. catch

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function normalizeCoord( strVals ) 
  {
  const rgxfns = /[+-]?\d+(\.\d+)?/g; // extract floats values
  let
    [v1,v2]   = strVals.match(rgxfns).map(Number) 
  , [lat,lon] = (v1 &lt; 0 || v2 &lt; 0) ? [v2,v1] : [v1,v2]  // .?
    ;
  if (lat &lt; -90  || lat &gt; 90  )  throw new Error(&#39;Invalid latitude&#39;);
  if (lon &lt; -180 || lon &gt; 180 )  throw new Error(&#39;Invalid longitude&#39;);
 
  return `(${lat}, ${lon})`;
  }

function formatCoords(...values)
  {
  const coords = []
    ;
  values.forEach( val =&gt; 
    {
    try 
      {
      let coord = normalizeCoord( val );
      coords.push({in:val, out: coord })
      }
    catch (err) 
      {
      coords.push({in:val, out: err.message })  
      }
    })
  return coords;
  }

console.log(
  formatCoords( &#39;42.9755,-77.4369&#39;, &#39;[-62.1234, 42.9755]&#39;, &#39;300,-9000&#39; )
  );

<!-- language: lang-css -->

.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 22:38:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定