jrshikoku/lib/eachTrainInfoCoreLib/findReversalPoints.js

114 lines
3.4 KiB
JavaScript

// arrayは現在位置の駅ID(駅在宅の場合は1つの配列、駅間の場合は2つの配列)
// stopStationIDListは停車駅の駅IDの配列 [Y01,Y02,Y05,...]
export const findReversalPoints = (array, stopStationIDList) => {
try {
if (!stopStationIDList) return [];
// arrayが二次元配列だったら早期リターン
if (!array instanceof Array) return [];
if (!array) return [];
if (array[0] instanceof Array) return [];
const arrayNumber = array.map((d) => ({
line: d
.split("")
.filter((s) => "A" < s && s < "Z")
.join(""),
ID: d
.split("")
.filter((s) => "0" <= s && s <= "9")
.join(""),
}));
const stopStationIDListNumber = stopStationIDList.map((d) => {
if (!d) return { line: [], ID: [] };
return {
line: d
.split("")
.filter((s) => "A" < s && s < "Z")
.join(""),
ID: d
.split("")
.filter((s) => "0" <= s && s <= "9")
.join(""),
};
});
// 完全一致
if (array.length == 1) {
const index = stopStationIDList.indexOf(array[0]);
if (index != -1) return [index];
// 通過駅の場合
for (let i = 0; i < stopStationIDListNumber.length - 1; i++) {
if (stopStationIDListNumber[i].ID < arrayNumber[0].ID) {
if (stopStationIDListNumber[i + 1].ID > arrayNumber[0].ID) {
return [i + 1];
}
}
if (stopStationIDListNumber[i].ID > arrayNumber[0].ID) {
if (stopStationIDListNumber[i + 1].ID < arrayNumber[0].ID) {
return [i + 1];
}
}
}
}
// 駅間の場合
if (array.length == 2) {
const index1 = stopStationIDList.indexOf(array[0]);
const index2 = stopStationIDList.indexOf(array[1]);
if (index1 != -1 && index2 != -1) {
// 駅間で通過駅も無い場合
if (index1 < index2) {
if (index1 + 1 == index2) {
return [index2];
} else {
const returnArray = [];
for (let i = index1 + 1; i <= index2; i++) {
returnArray.push(i);
}
return returnArray;
}
}
if (index1 > index2) {
if (index2 + 1 == index1) return [index1];
else {
const returnArray = [];
for (let i = index2 + 1; i <= index1; i++) {
returnArray.push(i);
}
return returnArray;
}
}
} else {
const getNearStationID = (stationID) => {
for (let i = 0; i <= stopStationIDListNumber.length; i++) {
if (stopStationIDListNumber[i].ID < stationID) {
if (stopStationIDListNumber[i + 1].ID > stationID) {
return i + 1;
}
}
if (stopStationIDListNumber[i].ID > stationID) {
if (stopStationIDListNumber[i + 1].ID < stationID) {
return i + 1;
}
}
}
};
let newIndex1 = index1;
let newIndex2 = index2;
if (index1 == -1) {
newIndex1 = getNearStationID(arrayNumber[0].ID);
}
if (index2 == -1) {
newIndex2 = getNearStationID(arrayNumber[1].ID);
}
if (newIndex1 && newIndex2) {
return [newIndex1, newIndex2];
}
// 通過駅の場合
}
return [];
}
} catch (e) {
console.log(e);
}
};