@@ -7,24 +7,54 @@ const seatCodeToBitmap = (seatCode) => {
7
7
. replace ( / R / g, 1 )
8
8
}
9
9
10
- const calcSeatId = ( { row, column } ) => row * 8 + column
10
+ // This is just binary to int
11
+ // const calcSeatId = ({ row, column }) => row * 8 + column
11
12
12
13
const getSeat = ( seatCode ) => {
13
14
// Seat codes are basically bitmaps, so convert them
14
15
const seatBitMap = seatCodeToBitmap ( seatCode )
15
16
16
- // First octect is row
17
+ // First septuplet is row
17
18
const row = parseInt ( seatBitMap . slice ( 0 , 7 ) , 2 )
18
19
// Last triplet is column
19
20
const column = parseInt ( seatBitMap . slice ( 7 ) , 2 )
20
21
21
22
return {
22
23
row,
23
24
column,
24
- id : calcSeatId ( { row , column } )
25
+ id : parseInt ( seatBitMap , 2 )
25
26
}
26
27
}
27
28
29
+ const findAvailableSeat = ( seats ) => {
30
+ // We could do some complicated logic to loop through a sorted
31
+ // list of seats comparing indexes to find the first one where there's
32
+ // a gap by looking for an off-by-one situation while excluding first
33
+ // and last rows:
34
+ //
35
+ // if (seat.row === 0 || seat.row === 127) return false
36
+ // // Find gap between this seat and previous
37
+ // return (
38
+ // (seat.id - 1) !== arr[idx - 1].id
39
+ // )
40
+ //
41
+ // Or we can just and a fake first row, and then look for any
42
+ // seat where the ID doesn't match the array index
43
+ //
44
+ const occupied = seats . map ( getSeat )
45
+ . sort ( ( a , b ) => a . id - b . id )
46
+ // The first seat is not in row 0, so add a bunch of
47
+ // fake rows at the front of the plane
48
+ occupied . unshift ( ...Array ( occupied [ 0 ] . id ) )
49
+ // Find the gap, ignoring the fake seats
50
+ return occupied . find ( ( seat , idx , arr ) => {
51
+ // !!seat filters out the fake ones since they're undefined
52
+ return ! ! seat && seat . id !== idx
53
+ // we can ignore rows at the back even if missing
54
+ } ) . id - 1 // The open seat will be immediately before the mismatched seat
55
+ }
56
+
28
57
module . exports = {
29
- getSeat
58
+ getSeat,
59
+ findAvailableSeat
30
60
}
0 commit comments