-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared-position-utils.js
More file actions
70 lines (63 loc) · 2.13 KB
/
shared-position-utils.js
File metadata and controls
70 lines (63 loc) · 2.13 KB
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
67
68
69
70
// Shared position utilities for handling coordinate-based logic
/**
* Compare two position objects for equality
* @param {Object} pos1 - First position {x, y}
* @param {Object} pos2 - Second position {x, y}
* @returns {boolean} - True if positions are equal
*/
function positionsEqual(pos1, pos2) {
if (!pos1 || !pos2) return false;
return pos1.x === pos2.x && pos1.y === pos2.y;
}
/**
* Find an item in an array by its position
* @param {Array} array - Array of objects with position property
* @param {Object} targetPosition - Target position {x, y}
* @returns {Object|undefined} - Found item or undefined
*/
function findByPosition(array, targetPosition) {
return array.find(item => positionsEqual(item.position, targetPosition));
}
/**
* Filter array items that match a specific position
* @param {Array} array - Array of objects with position property
* @param {Object} targetPosition - Target position {x, y}
* @returns {Array} - Array of matching items
*/
function filterByPosition(array, targetPosition) {
return array.filter(item => positionsEqual(item.position, targetPosition));
}
/**
* Check if a position exists in an array of positioned objects
* @param {Array} array - Array of objects with position property
* @param {Object} targetPosition - Target position {x, y}
* @returns {boolean} - True if position exists in array
*/
function positionExists(array, targetPosition) {
return array.some(item => positionsEqual(item.position, targetPosition));
}
/**
* Generate a string identifier from position (for UI keys, maps, etc.)
* @param {Object} position - Position {x, y}
* @returns {string} - Position string like "x-y"
*/
function positionToString(position) {
return `${position.x}-${position.y}`;
}
/**
* Parse a position string back to position object
* @param {string} positionString - Position string like "x-y"
* @returns {Object} - Position {x, y}
*/
function stringToPosition(positionString) {
const [x, y] = positionString.split('-').map(Number);
return { x, y };
}
module.exports = {
positionsEqual,
findByPosition,
filterByPosition,
positionExists,
positionToString,
stringToPosition
};