Coordinates converter

by evgkch

JavaScript

function convertToKey(x, y){
	if (Math.abs(x) < 32768 && Math.abs(y) < 32768)
  /*
   * Convert two numbers into one if each number less then 32768 (2 ** 14)
   *
   * |2nd number sign|---2nd number fraction--|1st number sign|---1st number fraction--|
   *         ^                   ^                    ^                   ^
   * |<----1 bit---->|<--------15 bit-------->|<----1 bit---->|<--------15 bit-------->|
   *         ^                   ^                    ^                   ^
   * |<---32th bit-->|<-----17..31th bits---->|<---16th bit-->|<-----1..15th bits----->|
   */
  {
    const xSign = x < 0 ? 1 << 15 : 0;
    const ySign = y < 0 ? 1 << 31 : 0;
    const xValue = x < 0 ? ~x : x;
    const yValue = (y < 0 ? ~y : y) << 16;
    return xSign | xValue | ySign | yValue;
  }
	else
  	return `${x},${y}`;
}

function parseKey(key){
	if (typeof(key) == 'number')
  {
  	const isXNegative = (1 << 15) & key;
    const isYNegative = (1 << 31) & key;
    const xValue = ((1 << 15) - 1) & key;
    const yValue = ((1 << 15) - 1) & (key >>> 16);
    return [
      isXNegative ? ~xValue : xValue,
      isYNegative ? ~yValue : yValue,
    ];
  }
	else
  	return key.split(',').map(Number);
}

console.log(parseKey(convertToKey(34,-354)))

const stringObject = {};
const stringMap = new Map;
const numberObject = {};

for (let i = -1000; i < 1000; i++)
{
	for (let j = -1000; j < 1000; j++)
  {
		stringObject[`${i},${j}`] = true;
    stringMap.set(`${i},${j}`,);
	}
}