Create a custom map/filter/reduce in JavaScript,Python and Ruby
ManuelMartinDev
Posted on September 2, 2021
When I learn a new language I like to create my own map/filter/reduce functions in it because is a great way to test my skills, working with functions,arrays,functions as arguments,etc.
So now I will compare how I would create it in all of them starting with JavaScript
// Map
function myMap(array,callback) {
newArray=[]
array.forEach(value => newArray.push(callback(value)))
return newArray
}
const transformed = myMap(["red","blue","purple"] , (color) => `Color ${color}`)
console.log(transformed)
//Filter
function myFilter(array,callback) {
newArray=[]
array.forEach(value => callback(value) && newArray.push(value))
return newArray
}
const filtered = myFilter([1,4,8,2,10,6] , number => number > 5)
console.log(filtered)
// Reduce
function myReduce(array,callback) {
let acc = 0
array.forEach(value => acc = callback(acc,value))
return acc
}
const reduced = myReduce([4,5,9,10] , (acc,current) => acc + current)
console.log(reduced)
Let's do it in python now
python is pretty much the same, just using lambdas instead arrow functions
# Map
def myMap(list,callback):
newList=[]
for item in list:
newList.append(callback(item))
return newList
transformed=myMap(["red","blue","purple"],lambda color: "Color " + color)
print(transformed)
#Filter
def myFilter(list,callback):
newList=[]
for item in list:
if callback(item) : newList.append(item)
return newList
filtered= myFilter([1,4,8,2,10,6],lambda number : number>5)
print(filtered)
#Reduce
def myReduce(list,callback):
acum=0
for el in list:
acum=callback(acum,el)
return acum
reduced = myReduce([4,5,9,10] , lambda current,actual:current+actual)
print(reduced)
And now Ruby
Ruby is a little bit more different, you pass blocks that act like anonymous functions, arguments are enclosed in | argname |
and they are called inside the function using the yield word
#Map
def myMap(array)
newarray=[]
for value in array do
result=yield(value)
newarray.push(result)
end
return newarray
end
transformed=myMap(["red","blue","purple"]) do | color | "Color #{color} " end
puts transformed.inspect
# Filter
def myFilter(array)
newarray=[]
for value in array do
newarray.push(value) if yield(value)
end
return newarray
end
filtered = myFilter([1,4,8,2,10,6]) do | number | number > 5 end
puts filtered.inspect
#Reduce
def myReduce(array)
acc = 0
for value in array do
acc = yield(acc,value)
end
return acc
end
reduced = myReduce([4,5,9,10]) do | acc,curr | acc+curr end
puts reduced.inspect
Here is a image that show that all of them have the same result
In general I had a lot of fun learning new things and I think it is such a great thing to do to improve your coding skills.
Posted on September 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024