@gamepark/rules-api
Version:
API to implement the rules of a board game
34 lines • 1.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.areNeighbors = exports.getNeighbors = void 0;
/**
* Given an item and an array, returns the 2 neighbors of the item.
* If the item starts or ends the array, the other starting of ending item is considered a neighbor.
* Example usage: getNeighbors(player, game.players)
* @param search Item to search for, or predicate to find the item
* @param array Array to search the neighbors in
* @returns the neighbors of the item in the array
*/
function getNeighbors(search, array) {
var index = array.findIndex(function (item) { return typeof search === 'function' ? search(item) : item === search; });
if (index === -1)
return [];
return array.filter(function (_, i) {
var distance = Math.abs(index - i);
return distance === 1 || distance === array.length - 1;
});
}
exports.getNeighbors = getNeighbors;
/**
* Test if 2 items are neighbors in a ring array
* @param item1 First item
* @param item2 Second item
* @param array Array to search the neighbors in
* @returns true if items are neighbors in the array
*/
function areNeighbors(item1, item2, array) {
var distance = Math.abs(array.indexOf(item1) - array.indexOf(item2));
return distance === 1 || distance === array.length - 1;
}
exports.areNeighbors = areNeighbors;
//# sourceMappingURL=neighbors.util.js.map