I have two points in x,y,z format. If p1.x < p2.x I want my variable directionX = 1, otherwise directionX = -1.
“1” means later to increase p1.x in distance calculation until it becomes 15 (for example below). It’s find unknow point task where I have only distance and starting point coordinates. Basically I did this task. But I can’t refactor and orginize my code in better way =(
At first I want to find in what direction later to change x,y,z. By changing x,y,z I see how distance increases or decreases. This is my logic to find unknow point.
But I found difficult to refactor my “findDirection” function. It is huge and makes same work 3 times for x, y , z.
const p1 = { x: 11, y: 12, z: 2 }; const p2 = { x: 15, y: 10, z: 5 }; function calculateDistance(p1, p2) { const a = p2.x - p1.x; const b = p2.y - p1.y; const c = p2.z - p1.z; return Math.sqrt(a * a + b * b + c * c); } const distance = calculateDistance(p1, p2); let directionX = 1; let directionY = 1; let directionZ = 1; function findDirection(p1, p2, distance) { let newDistance = distance; p1.x += 1; newDistance = calculateDistance(p1, p2); if (newDistance > distance) { directionX = -1; } p1.x -= 1; p1.y += 1; newDistance = calculateDistance(p1, p2); if (newDistance > distance) { directionY = -1; } p1.y -= 1; p1.z += 1; newDistance = calculateDistance(p1, p2); if (newDistance > distance) { directionZ = -1; } p1.z -= 1; } findDirection(p1, p2, distance); console.log("directionX: " + directionX); console.log("directionY: " + directionY); console.log("directionZ: " + directionZ);
How to make like this
directionX = findDirection(p1, p2, distance, p1.x); // and have result 1 or -1;
Advertisement
Answer
I would extract the calculation for each coordinate into a separate function. I pass the coordinate
variable to it which chooses the corresponding key from the object. Also you don’t need to mutate the p1
object, so I create a copy of it, but increment the required coordinate by 1.
The resulting distance can also be an object rather than three separate variables.
const p1 = { x: 11, y: 12, z: 2 }; const p2 = { x: 15, y: 10, z: 5 }; function calculateDistance(p1, p2) { const a = p2.x - p1.x; const b = p2.y - p1.y; const c = p2.z - p1.z; return Math.sqrt(a * a + b * b + c * c); } function findDirectionForCoordinate(p1, p2, distance, coordinate) { const p = { ...p1 }; // make a copy of p1 so that we don't mutate the original object p[coordinate] += 1; // increment the coordinate if (calculateDistance(p, p2) > distance) { return -1; } return 1; } function findDirection(p1, p2) { const distance = calculateDistance(p1, p2); return { x: findDirectionForCoordinate(p1, p2, distance, 'x'), y: findDirectionForCoordinate(p1, p2, distance, 'y'), z: findDirectionForCoordinate(p1, p2, distance, 'z') }; } const direction = findDirection(p1, p2); console.log('directionX: ' + direction.x); console.log('directionY: ' + direction.y); console.log('directionZ: ' + direction.z);