Map
# Ruby
def addTwoZeros(array)
array.map { |element| element * 100 }
end
// JavaScript
const addTwoZeros = array => {
return array.map((element) => {
return element * 100
})
}
The above functions/methods take in a list of numbers, add two zeros to the end of each number, and return a new list of transformed numbers. The main idea behind map
is transforming each member in an array and putting it into a new array. This new array will eventually hold a collection of transformed elements in the same order as the original array.
In the Ruby implementation, each element of the array goes through |element|
and undergoes the code to the right of |element|
. That is, each element goes through the pipes ||
and gets 100 multiplied to it.
In the JavaScript implementation, the map
function gets another function passed to it. Each element of the array gets passed through the (element)
of this secondary function. Then the element gets 100 multiplied to it.
Reduce
# Ruby
def getProduct(array)
array.reduce do |accumulator, element|
accumulator * element
end
end
// JavaScript
const getProduct = array => {
return array.reduce((accumulator, element) => {
return accumulator * element
})
}
The above functions/methods take in an array, multiply all the elements together, then return the result. The main idea behind reduce
is taking a bunch of things and reducing them down to a single value.
In the Ruby implementation, each element of the array goes through the element
part of |accumulator, element|
and gets multiplied to accumulator
.
In the JavaScript implementation, the reduce
function gets another function passed to it. Each element of the array gets passed through the (element)
of this secondary function, then multiplied to accumulator
.
Filter/Select
# Ruby
def getOddNums(array)
array.select { |element| element % 2 != 0 }
end
// JavaScript
const getOddNums = array => {
return array.filter((element) => {
return element % 2 !== 0
})
}
The above functions/methods take in an array and return only the elements that are odd. The main idea behind filter
/ select
is passing each element to a block; if the element makes the block truthy, the element is added to a new array.
In the Ruby implementation, each element of the array goes through |element|
and undergoes the code to the right of |element|
. If the element makes the code to the right of |element|
truthy, then that element is added to a new array. If the element does not make the code to the right of |element|
truthy, the element is not added to the new array.
In the JavaScript implementation, the filter
function gets another function passed to it. Each element of the array gets passed through the (element)
of this secondary function. If the element makes element % 2 !== 0
truthy, then that element is added to a new array. If the element does not make element % 2 !== 0
truthy, the element is not added to the new array.
Top comments (0)