Reduce Advanced - Part 4 of Functional Programming in JavaScript
Key Takeaways
This video demonstrates advanced usage of the reduce function in JavaScript, specifically using it to transform a tab-separated file into an object literal, and showcases the composition of higher-order functions like map and reduce.
Full Transcript
[Music] hello we're missing oh the plant I need that for lifestyle well it's Monday again for you guys for me it's Saturday evening and there is a lot of hiking gear behind me this episode will be released automatically to you guys on Monday while I am in a uh canoe traversing the Swedish Wilderness last time I showed you a basic example of reduce where we used it to summarize the property of a series of objects however reduce is not limited to reducing a list to uh a number it can reduce it to anything such as another array or an object and that is what we're going to do today I'm also going to throw a couple of other higher order functions into the mix I've talked previously about how higher order functions compose very well together and I'm going to give you some more examples of this today we're going to jump right into it on the left side of the screen we see data.txt this is a tab separated file so there is tabs here it's tabs oh tabs here here and here and this is just some file that we got out of some old system we having assigned a task we are going to turn it into something that looks a little bit like this so we're going to turn it into a uh object literal and every key in that object is going to be the name so Mark Johnson Mark Johnson here that's the same guy and his uh orders or or order items or whatever goes uh goes in an array so these orders here going to be turned into these so the first uh the first string tab separate string after the the item name is the price of the uh the item and the uh the second integer after the name of the item is going to be the quantity of that item this is our mission we're going to turn this file into this because we're dealing with a file here we need to import the uh FS Nam space from no uh I'm going to use a new requir syntax uh normally you would do something like this but we are going to use modern JavaScript which means that we do this instead so these are the same thing but we're going to use this one now to read from the file we just go fs. read file sync data.txt and it wants no hang on just let me show you what this looks like first also that log out [Music] book right and let's run that as you can see here we're we're getting a buffer uh of bites and that is not quite what we want we expected this to be the contents of the data.txt file and that is just because in in programming and in the computer strings are just a long set of bites it doesn't know how to interpret that into text unless it has some kind of mapping to an encoding TT table a character encoding the most common character encoding is utf8 let's run that again yes we have it let's start by uh I don't know splitting this into uh an [Music] array so split is just a method on the string object that splits the string into an array by uh splitting it using this character here and this is a a line break so if we run this we're going to see an array of straights there's an extra line here I it's because files always tend to have one final line break so we get rid of that by just calling uh trim on the string before we pass it into split and what trim does is that it just removes any line braks or space it at at the end and start of a string so if you run that that little string at the end is now gone before we start using reduce on these lines I would like to uh convert them into a more manageable object first using map I'm going to [Music] map every line and I'm going to split [Music] it on Tab characters see what that looks like okay cool now we have an array of arrays where each array is basically the equivalent of this let's reduce it remember that reduce takes two arguments first takes a function and it also takes a starting object and in the last episode we used a number as a starting object like this but in this case we are going to create an uh object literal so we're going to pass it an object the function that we passed to reduce one's two arguments the first one is the uh object that we are constructing the uh the end goal that we talked about in the beginning of this episode uh and it's uh it's this one and it's going to be passed here on the first Loop and the second argument is the uh the thing that we are iterating in this case it's going to be the line uh and my what I mean by that is these so reduce is going to receive this item on the this array on the first iteration it will receive this array on the second iteration and so on let's run that so far whoops it's returning undefined and that is because output will be whatever reduce Returns on its final iteration so let's return the customer object on it all right it's an empty object that is because we're returning it here and it's empty because we're not doing anything with it yet Just for kicks let me console log the line out on it bam so you'll see here that reduce iterates over the array of arrays that um this map function creates so for each iteration it receives an array another array that is the equivalent of the lines in data. dxt let's get rid of this console log I want to rename this customers cuz we're making a customer's object and for every customer we're going to make a property with their name remember that the first item of the line first part is the name we're going to make that an empty array let's run it okay cool we have have an empty array for Mark Johansson and we have an empty array for Nikita Smith and this is because even though it will get this line then this line then this line it will simply overwrite the mark Johansson property every time and uh the Nikita Smith property every time and now we want to pend the order items so we take this copy it and push to it we push an object so we want name that is the second part of the line and we want the price that is the third part of the line and we want the quantity which is the fourth part of the line and we uh run that H that's a bit hard to read I'm going to teach you a trick now check this out Json do string five null 2 run that again oh much better so what we did here was create a Json string from the uh the output uh with two spaces for indentation we have a bug because only the last item here and the part here is actually being um being added to the array and that is because we are overriding it here so we have to copy this one and just make sure that now we are reusing the existing array if there exists one otherwise we're assigning a new one and we have an output so waffle iron blender oh there's no quantity oh I have a bug find three getting tired right all right and we are done today we looked at a more advanced produ example where instead of using a number we used an object lateral here we also see some chaining going on here good functional code is made up of small functions that do one thing and you just B them all together and that is what we do here we have a trim we have a split we have a map which in turn uses split inside of it uh and we have a reduce the chain ability that you see here is something that you got going to see a lot of if you do functional programming I am going to nibble a bit on the um Jura Superstition whiskey that we are supposed to bring on the canoe trip the uh the other guys won't know that IBL uh because this episode doesn't come out until Monday where not here then so I am on vacation next we week so there won't be an episode next Monday but there will be the Monday after that so please tell me what you think that that episode should be about either comment down below or send me a tweet at mpj me oh and 2 weeks without an episode that's a long time you might forget about me so make sure that you subscribe clicky clicky there there or follow me on Twitter for some of you guys this is good morning and for me this is good night until next time stay [Music] curious
Original Description
💖 Support the show by becoming a Patreon
https://www.patreon.com/funfunfunction
In this video series, we learn how to do functional programming in JavaScript. In this fourth one, we spend a little bit more time on *reduce*.
Playlist of full series is here:
https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84
How to install and use io.js (for the arrow functions example)
http://davidwalsh.name/es6-io
You want to follow me on Twitter and Quora:
https://twitter.com/mpjme
http://www.quora.com/Mattias-Petter-Johansson
💛 Follow on Twitch
We record the show live Mondays 7 AM PT
https://twitch.tv/funfunfunction
💛 Fun Fun Forum
Private discussion forum with other viewers in between shows. https://www.funfunforum.com. Available to patron members, become one at https://www.patreon.com/funfunfunction
💛 mpj on Twitter
https://twitter.com/mpjme
💛 CircleCI (Show sponsor)
Robust and sleek Docker-based Continuous Integration as a service. I used CircleCI prior to them becoming a sponsor and I love that their free tier is powerful enough for small personal projects, even if they are private. Use this link when you sign up to let them know you came from here:
https://circleci.funfunfunction.com
💛 Quokka (Show sponsor)
Wonder how MPJ evaluates JavaScript inline his editor. Quokka is the answer - use this link when you buy to let them know you came from here:
http://quokka.funfunfunction.com
💛 FUN FUN FUNCTION
Since 2015, Fun Fun Function (FFF) is one of the longest running weekly YouTube shows on programming 🏅 thanks to its consistency and quality reaching 200,000+ developers.
🤦♂️ The Failing Together concept is what makes FFF unique. Most coding content out there focus on step-by-step tutorials. We think tutorials are too far removed from what everyday development is like. Instead, FFF has created a completely new learning environment where we grow from failure, by solving problems while intensively interacting with a live audience.
Tutoria
Playlist
Uploads from Fun Fun Function · Fun Fun Function · 5 of 60
1
2
3
4
▶
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Higher-order functions - Part 1 of Functional Programming in JavaScript
Fun Fun Function
Map - Part 2 of Functional Programming in JavaScript
Fun Fun Function
Reduce basics - Part 3 of Functional Programming in JavaScript
Fun Fun Function
Destructuring: What, Why and How - Part 1 of ES6 JavaScript Features
Fun Fun Function
Reduce Advanced - Part 4 of Functional Programming in JavaScript
Fun Fun Function
Closures - Part 5 of Functional Programming in JavaScript
Fun Fun Function
Too many tools and frameworks!
Fun Fun Function
Currying - Part 6 of Functional Programming in JavaScript
Fun Fun Function
Recursion - Part 7 of Functional Programming in JavaScript
Fun Fun Function
Promises - Part 8 of Functional Programming in JavaScript
Fun Fun Function
Staying relevant as a programmer
Fun Fun Function
Factory Functions in JavaScript
Fun Fun Function
Composition over Inheritance
Fun Fun Function
Software needs to be better - FunFunFunction #1
Fun Fun Function
Unit testing: How to get your team started - FunFunFunction #2
Fun Fun Function
Straight-line code over functions - FunFunFunction #3
Fun Fun Function
Clojure - FunFunFunction #5
Fun Fun Function
The growth stages of a programmer - FunFunFunction #6
Fun Fun Function
5 tips to quickly understand a new code base - FunFunFunction #7
Fun Fun Function
Semicolons cannot save you! - FunFunFunction #9
Fun Fun Function
Functors - FunFunFunction #10
Fun Fun Function
Functors: I was WRONG! - FunFunFunction #11
Fun Fun Function
Questions and Answers - FunFunFunction #12
Fun Fun Function
Streams - FunFunFunction #13
Fun Fun Function
Prototypes in JavaScript - FunFunFunction #16
Fun Fun Function
Fast or Flexible? - FunFunFunction #17
Fun Fun Function
Coders are herd animals - FunFunFunction #18
Fun Fun Function
Weekend Kubernetes Shenanigans - FunFunFunction #19
Fun Fun Function
Monad - FunFunFunction #21
Fun Fun Function
Moar Weekend Shenanigans - FunFunFunction #23
Fun Fun Function
Questions and Answers - FunFunFunction #24
Fun Fun Function
Losing motivation - FunFunFunction #25
Fun Fun Function
LONGEST KUBERNETES SHENANIGANS! - FunFunFunction #26
Fun Fun Function
Fast code is NOT important - FunFunFunction #27
Fun Fun Function
Pair Programming a Facebook Messenger Bot - FunFunFunction #28
Fun Fun Function
Writing unit tests for personal projects? - FunFunFunction #29
Fun Fun Function
Let's Code a Pomodoro Button - FunFunFunction #30
Fun Fun Function
What editor do you use? - FunFunFunction #31
Fun Fun Function
Arrow functions in JavaScript - What, Why and How - FunFunFunction #32
Fun Fun Function
Is Programming Art? - MPJ's Musings - FunFunFunction #33
Fun Fun Function
Generators in JavaScript - What, Why and How - FunFunFunction #34
Fun Fun Function
Haskell Basics - FunFunFunction #35
Fun Fun Function
Haskell - Baby's first functions - FunFunFunction #36
Fun Fun Function
Is Big O relevant to you? - Q&A Part 1 - FunFunFunction #37
Fun Fun Function
How much are you allowed to Google? - Q&A Part 2 - FunFunFunction #38
Fun Fun Function
Haskell lists - FunFunFunction #39
Fun Fun Function
var, let and const - What, why and how - ES6 JavaScript Features
Fun Fun Function
Why are some programming languages popular? - MPJ's Musings - FunFunFunction #41
Fun Fun Function
Does a developer need to be nice? - MPJ's Musings - FunFunFunction #42
Fun Fun Function
bind and this - Object Creation in JavaScript P1 - FunFunFunction #43
Fun Fun Function
Examples of this and bind - Object Creation in JavaScript P2 - FunFunFunction #44
Fun Fun Function
Prototype basics - Object Creation in JavaScript P3 - FunFunFunction #46
Fun Fun Function
Separation of concerns RANT - MPJ's Musings - FunFunFunction #47
Fun Fun Function
Cellular Automata - Pair Programming - FunFunFunction #49
Fun Fun Function
The 'new' keyword - Object Creation in JavaScript P4 - FunFunFunction #50
Fun Fun Function
__proto__ vs prototype - Object Creation in JavaScript P5 - FunFunFunction #52
Fun Fun Function
Unity game pair programming - Let's code - FunFunFunction #53
Fun Fun Function
Throw out your tools - MPJ's Musings - FunFunFunction #54
Fun Fun Function
Unit tests vs. Integration tests - MPJ's Musings - FunFunFunction #55
Fun Fun Function
Object.create - Object Creation in JavaScript P6 - FunFunFunction #57
Fun Fun Function
Related Reads
📰
📰
📰
📰
how to find in order you want
Dev.to · AlexfamDan
I Started Learning to Code — So I Built My Own Product | SkillLink
Dev.to · Mohamed Tarek
Senior Java Interview Questions Aren’t Hard. The Follow-Ups Are.
Medium · Programming
Cannot Assign Requested Address in Production: The Connection Failure Most Backend Engineers Blame…
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI