Last active
February 24, 2019 11:57
-
-
Save AndriiBozh/584b67df2cb9c7e217ddafb50af15ef7 to your computer and use it in GitHub Desktop.
CodeWars: working with subarrays, Bus Stop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ASSIGNMENT | |
_______________________________ | |
There is a bus moving in the city, and it takes and drop some people in each bus stop. | |
You are provided with a list (or array) of integer arrays (or tuples). | |
Each integer array has two items which represent number of people get into bus (The first item) | |
and number of people get off the bus (The second item) in a bus stop. | |
Your task is to return number of people who are still in the bus after the last bus station (after the last array). | |
Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D | |
_______________________________ | |
SOLUTION | |
_______________________________ | |
let numberOfPassengers = function(busStops){ | |
return arr.map((item) => item.reduce((a, b) => a - b)).reduce((c, d) => c + d, 0); | |
}; | |
numberOfPassengers([[10,0],[3,5],[5,8]]); | |
_______________________________ | |
//we need to pass 0 as the initial value to the summing reduce, | |
//so that our function will still work if we pass an empty array: | |
// numberOfPassengers([]) will return 0, not 'TypeError: reduce of empty array with no initial value' | |
_______________________________ | |
_______________________________ | |
also could be without using 'reduce()' for mapping: | |
let numberOfPassengers = function(busStops){ | |
return busStops.map(([a, b]) => a - b).reduce((c, d) => c + d, 0); | |
}; | |
numberOfPassengers([[10,0],[3,5],[5,8]]); | |
_______________________________ | |
We can further shorten the above by fusing the map into the reduce: | |
let numberOfPassengers = function(busStops){ | |
return busStops.reduce((c, [a, b]) => c + a - b, 0); | |
}; | |
numberOfPassengers([[10,0],[3,5],[5,8]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment