Skip to content

Instantly share code, notes, and snippets.

@qingant
Last active February 15, 2020 03:36
Show Gist options
  • Save qingant/dd40d4b8a9c487add1362971216cae48 to your computer and use it in GitHub Desktop.
Save qingant/dd40d4b8a9c487add1362971216cae48 to your computer and use it in GitHub Desktop.
const assignVehicles = (vehicles, drivers) => {
vehicles = JSON.parse(JSON.stringify(vehicles))
drivers = JSON.parse(JSON.stringify(drivers))
vehicles.sort((a, b) => a.year - b.year)
drivers.sort((a, b) => b.age - a.age)
// console.log('Sorted:', vehicles, drivers)
let result = {
vehicles: {},
drivers: {}
}
vehicles.map((v, i) => {
let driver = drivers[i] || drivers[drivers.length - 1]
result.vehicles[v.id] = driver.id
result.drivers[driver.id] = v.id
})
if (vehicles.length < drivers.length) {
drivers.slice(vehicles.length,).map((v, i) => {
let vehicle = vehicles[vehicles.length - 1]
result.drivers[v.id] = vehicle.id
})
}
return result
}
const vehicles = [
{
id: '1',
year: 1,
},
{
id: '2',
year: 3,
},
{
id: '3',
year: 10,
}
]
drivers = [
{
id: '1',
age: 30,
},
{
id: '2',
age: 24,
},
{
id: '3',
age: 40,
},
{
id: '4',
age: 31
}
]
const test = (a, b) => {
console.log(a, b);
let r = assignVehicles(a, b)
console.log(r)
}
test(vehicles, drivers.slice(0, vehicles.length))
test(vehicles, drivers.slice(0, vehicles.length - 1))
test(vehicles, drivers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment