{"componentChunkName":"component---src-templates-about-page-js","path":"/about/","result":{"data":{"sitePage":{"id":"SitePage /about/"}},"pageContext":{"url":"/about/","relativePath":"about.md","relativeDir":"","base":"about.md","name":"about","frontmatter":{"title":"About Me","img_alt":"Felipe Image","about-img":"images/headshot.jpg","seo":{"title":"About Me","description":"This is the about me page","extra":[{"name":"og:type","value":"website","keyName":"property"},{"name":"og:title","value":"About Me","keyName":"property"},{"name":"og:description","value":"This is the about me page","keyName":"property"},{"name":"og:image","value":"images/about.jpg","keyName":"property","relativeUrl":true},{"name":"twitter:card","value":"summary_large_image"},{"name":"twitter:title","value":"About Me"},{"name":"twitter:description","value":"This is the about me page"},{"name":"twitter:image","value":"images/about.jpg","relativeUrl":true}]},"template":"about-page"},"html":"<p>Before becoming a software engineer I worked with nationally recognized organizations including the American Bankers Association and the Congressional Hispanic Caucus Institute. After working over 4 years at Capitol Hill in human development and then 3 years in eLearning for the banking industry, I felt I was ready for the next challenge. As an entrepreneur and creative individual, I was moved by technology and its potential to bring positive change in our world🌎.</p>\n<p>How I prepared to break into tech was a process that spanned a period of over a couple of years. First I completed Information Systems studies at George Washington University, Business School. There, I participated (and won 🏆) many entrepreneurship competitions that brought a perspective of the importance of tech in understanding and bringing solutions to the problem domain.</p>\n<p>Thereafter, I completed a coding bootcamp with the number one school in the country for 2019-20, namely Flatiron School. We focused on several stacks, ranging from Ruby/Rails to JavaScript and React. I built several high quality projects ranging from Catoro (a professional coffee cupping app), a street artist tracker, an online iChing and even published a Ruby Gem that has been downloaded over three-thousand times to date! 📈. Right after graduation, I doubled my portfolio and added the MERN stack to my skills by completing various Node/Express/MongoDB projects. I also further increased my understanding of other libraries including Gatsby, SCSS and serverless technologies such as Firebase.</p>\n<p>Currently I'm working as a full stack developer for a large scale application that uses Angular for the frontend and NestJS powered by GraphQL for the backend. I'm also working on expanding my React Native skills to launch Catoro coffee app FREE on the app store!</p>\n<p>I do not forget my commitment to give back and bring positive change🤝🏼. So these days you can also see me volunteering for Bridge of Kindness non-profit, assisting their MERN donation platform or even being featured as a technical writer on <a href=\"https://careerkarma.com/blog/author/felipe-bohorquez/\">CareerKarma</a>, a famous tech website for non-traditional students, to help them break into tech! 👨🏽‍💻</p>\n<p>I'm always open to lend a hand, don't hesitate to connect and say hi 👋🏼!</p>\n<h3>Reference</h3>\n<p>I use PDF Snake to prepare blog documents for professional printing. <a href=\"https://www.pdfsnake.com/?_gl=1*1gue3ke*_ga*MTI5NjkyNzg3Mi4xNjk0NDk4ODc3*_ga_X69TS6D1SW*MTY5NDU0MTczNC4yLjEuMTY5NDU0MjYwMS4wLjAuMA..*_gcl_aw*R0NMLjE2OTQ0OTM0NTcuQ2owS0NRanc5ZnFuQmhEU0FSSXNBSGxjUVlSWUd2U2UxU0tJOWdYTzloVll2Y2pqVG10RlBiWTB3ejM3b0k5ZkRZcHRFNmhvQzloYndRWWFBakFaRUFMd193Y0I.*_gcl_au*MTA3MDczNDc5Ny4xNjk0NDk4ODc1\">Try it now too!</a></p>","pages":[{"url":"/style-guide/","relativePath":"style-guide.md","relativeDir":"","base":"style-guide.md","name":"style-guide","frontmatter":{"title":"Style Guide","subtitle":"The style guide provides you with a blueprint of default post and page styles. The style guide is also a great reference for suggested typographic treatment and styles for your content.","seo":{"title":"Theme Style Guide","description":"A reference for suggested typographic treatment and styles for your content","extra":[{"name":"og:type","value":"website","keyName":"property"},{"name":"og:title","value":"Theme Style Guide","keyName":"property"},{"name":"og:description","value":"A reference for suggested typographic treatment and styles for your content","keyName":"property"},{"name":"og:image","value":"images/1.jpg","keyName":"property","relativeUrl":true},{"name":"twitter:card","value":"summary_large_image"},{"name":"twitter:title","value":"Theme Style Guide"},{"name":"twitter:description","value":"A reference for suggested typographic treatment and styles for your content"},{"name":"twitter:image","value":"images/1.jpg","relativeUrl":true}]},"template":"page"},"html":"<p><strong>This is a paragraph</strong>. Pellentesque habitant morbi <em>tristique senectus et netus et malesuada</em> fames ac turpis egestas. Vestibulum <a href=\"https://www.google.com\">tortor quam</a>, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit <mark>amet est et sapien ullamcorper</mark> pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi.</p>\n<h1>This is an H1</h1>\n<p>Quisque facilisis erat a dui. Nam malesuada ornare dolor. Cras gravida, this is marked text ornare, erat elit consectetuer erat, id egestas pede nibh eget odio. Proin tincidunt, velit vel porta elementum, magna diam molestie sapien, non aliquet massa pede eu diam. Aliquam iaculis. Fusce et ipsum et nulla tristique facilisis.</p>\n<h2>This is an H2</h2>\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim. Suspendisse id velit vitae ligula volutpat condimentum. Aliquam erat volutpat. Sed quis velit. Nulla facilisi. Nulla libero.</p>\n<h3>This is an H3</h3>\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim. Suspendisse id velit vitae ligula volutpat condimentum. Aliquam erat volutpat. Sed quis velit. Nulla facilisi. Nulla libero.</p>\n<h4>This is an H4</h4>\n<p>Quisque facilisis erat a dui. Nam malesuada ornare dolor. Cras gravida, diam sit amet rhoncus ornare, erat elit consectetuer erat, id egestas pede nibh eget odio. Proin tincidunt, velit vel porta elementum, magna diam molestie sapien, non aliquet massa pede eu diam. Aliquam iaculis.</p>\n<h2>Quoting</h2>\n<blockquote>\n<p>Creativity is allowing yourself to make mistakes. Design is knowing which ones to keep. <cite>Scott Adams</cite></p>\n</blockquote>\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim. Suspendisse id velit vitae ligula volutpat condimentum. Aliquam erat volutpat. Sed quis velit. Nulla facilisi. Nulla libero.</p>\n<hr />\n<h2>Unordered Lists</h2>\n<ul>\n<li>Donec non tortor in arcu mollis feugiat</li>\n<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</li>\n<li>Donec id eros eget quam aliquam gravida</li>\n<li>Vivamus convallis urna id felis</li>\n<li>Nulla porta tempus sapien</li>\n</ul>\n<h2>Ordered Lists</h2>\n<ol>\n<li>Donec non tortor in arcu mollis feugiat</li>\n<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</li>\n<li>Donec id eros eget quam aliquam gravida</li>\n<li>Vivamus convallis urna id felis</li>\n<li>Nulla porta tempus sapien</li>\n</ol>\n<h2>Code Blocks</h2>\n<p>Blocks of code are either fenced by lines with three back-ticks, or are indented with four spaces.</p>\n<pre><code>&#x3C;!-- Some example CSS code -->\nbody {\n  color: #333;\n  font-family: Cabin, Helvetica, Arial, sans-serif;\n  line-height: 1.5;\n}\n</code></pre>\n<h2>Tables</h2>\n<div class=\"responsive-table\">\n  <table>\n    <caption>Simple table with caption and header</caption>\n    <thead>\n      <tr>\n        <th>Column 1</th>\n        <th>Column 2</th>\n        <th>Column 3</th>\n      </tr>\n    </thead>\n    <tbody>\n      <tr>\n        <td>Row 1, Cell 1</td>\n        <td>Row 1, Cell 2</td>\n        <td>Row 1, Cell 3</td>\n      </tr>\n      <tr>\n        <td>Row 2, Cell 1</td>\n        <td>Row 2, Cell 2</td>\n        <td>Row 2, Cell 3</td>\n      </tr>\n    </tbody>\n  </table>\n</div>"},{"url":"/404/","relativePath":"404.md","relativeDir":"","base":"404.md","name":"404","frontmatter":{"title":"Not Found (404)","img_alt":"Not Found","template":"page"},"html":"<p>PAGE NOT FOUND! PLEASE GO BACK :(</p>"},{"url":"/thank-you/","relativePath":"thank-you.md","relativeDir":"","base":"thank-you.md","name":"thank-you","frontmatter":{"title":"Thank You!","img_path":"images/thank-you.jpg","img_alt":"Thank You Led Signage","template":"page"},"html":"<p>Thank you for contacting me! I will get back in touch with you soon.</p>\n<p><strong>Have a great day!</strong></p>"},{"url":"/contact/","relativePath":"contact.md","relativeDir":"","base":"contact.md","name":"contact","frontmatter":{"title":"Contact","hide_title":false,"sections":[{"section_id":"contact-form","type":"section_form","content":"To get in touch please fill the form below.","form_id":"contactForm","form_action":"/thank-you","form_fields":[{"input_type":"text","name":"name","label":"Name","default_value":"Your name","is_required":true},{"input_type":"email","name":"email","label":"Email","default_value":"Your email address","is_required":true},{"input_type":"select","name":"subject","label":"Subject","default_value":"Please select","options":["Error on the site","Sponsorship","Other"]},{"input_type":"textarea","name":"message","label":"Message","default_value":"Your message"},{"input_type":"checkbox","name":"consent","label":"I understand that this form is storing my submitted information so I can be contacted."}],"submit_label":"Send Message"}],"seo":{"title":"Contact","description":"This is the contact page","extra":[{"name":"og:type","value":"website","keyName":"property"},{"name":"og:title","value":"Contact","keyName":"property"},{"name":"og:description","value":"This is the contact page","keyName":"property"},{"name":"twitter:card","value":"summary"},{"name":"twitter:title","value":"Contact"},{"name":"twitter:description","value":"This is the contact page"}]},"template":"advanced"},"html":""},{"url":"/posts/2019-05-14-do_we_choose_what_we_do_or_is_it_the_other_way_around/","relativePath":"posts/2019-05-14-do_we_choose_what_we_do_or_is_it_the_other_way_around.markdown","relativeDir":"posts","base":"2019-05-14-do_we_choose_what_we_do_or_is_it_the_other_way_around.markdown","name":"2019-05-14-do_we_choose_what_we_do_or_is_it_the_other_way_around","frontmatter":{"title":"Who chose what?","template":"post","date":"2019-05-14 23:31:03 -0400","permalink":"do_we_choose_what_we_do_or_is_it_the_other_way_around"},"html":"<blockquote>\n<p>Do we choose what we do? or is it the other way around?</p>\n</blockquote>\n<p>My interest in computer programming started when I was fresh out of college. Back then, a process improvement opportunity came up and it volunteer myself in a project involving implementing a Moodle Platform as part of a curriculum development for a leadership program. I winged this project by looking at forums for help regarding every single aspect of its implementation, from configuration of site to hosting, and to SMPT configuration. I even got the opportunity to break the site once, while doing an update, and then probably a couple of times more while trying to make changes, upgrades or modifications to it. </p>\n<p>What actually happened from that project is that it brought to me my first experience with technology. As I was reading online about eLearning I came across MOOCs and then somehow stumbled onto an edX course on Computer Programming. That was my first experience and this course proved very difficult, so I actually never got to finish it. However, a spark has been born and since then I've been interested in one way or another in information systems, coding and its business applications. </p>\n<p><strong><em>So why did I decide to learn coding?</em></strong> Software development is a little bit like education. You are <em>'teaching'</em> the computer to do certain things, somehow computers if given the correct instructions can do amazing things and makes things easier. Coding is a powerful tool to have and it is indeed an empowering skill to develop. Being creative, solving problems and makes things better is a passion for me, that is why I decided to learn software development or maybe the other way around. </p>"},{"url":"/","relativePath":"index.md","relativeDir":"","base":"index.md","name":"index","frontmatter":{"title":"Home","hide_title":true,"is_home":true,"sections":[{"section_id":"hero","type":"section_hero","title":"Hi, I'm Felipe Bohórquez.","content":"I am a passionate software engineer and social entrepreneur with a mission to make our world a better place."},{"section_id":"about","type":"section_content","extraclass":"block-about","section_image":"https://i.imgur.com/Yy3m5Pg.png","title":"About me 🙋‍♂️","content":"I am a passionate **software engineer** and social entrepreneur. I am proud of my beginnings as a youth developer with inner-city kids then through education within the halls of congress and now in software engineering.\n\nAs a full-stack software engineer with a focus on React, Angular, Node.js, Typescript and JavaScript, I've built a robust portfolio including a professional coffee cupping app. I've also built custom library projects in other languages such as Ruby that have been used widely by the developer community.\n\nAs a social entrepreneur I have co-launched different projects in areas such as health (MomBox), sustainability (PowerToThePeople), specialty food through art ([ArtesanoSpirit](https://artesanospirit.com/)) and performing arts. Many of such ventures have been awarded in business competitions.\n\nAs a passionate writer, I've been an author for [CareerKarma](https://careerkarma.com/blog/author/felipe-bohorquez/) and I've done weekly articles on a variety topics on top [Medium Publications](https://fbohorqu.medium.com/).","actions":[{"label":"Connect With Me","url":"https://www.linkedin.com/in/fbohz/","style":"button"}]},{"section_id":"projects","type":"section_projects","title":"Highlighted Projects 💻","posts_number":4,"content":"This is the \"about\" excerpt. It can be used to provide a paragraph about yourself that people can read on the homepage to get a sense of who you are. There also exists a dedicated about page where you can write more about yourself for those who are interested.","actions":[{"label":"See More","url":"about","style":"link"}]},{"section_id":"recent-posts","type":"section_posts","title":"Recent Posts ✍️","posts_number":4,"actions":[{"label":"View Blog","url":"blog","style":"button"}]}],"seo":{"title":"Felipe Bohórquez","description":"Felipe's Professional Portfolio and Writing","extra":[{"name":"og:type","value":"website","keyName":"property"},{"name":"og:title","value":"Felipe Bohórquez","keyName":"property"},{"name":"og:description","value":"Coding, Technology and Entrepreneurship","keyName":"property"},{"name":"og:image","value":"images/4.jpg","keyName":"property","relativeUrl":true},{"name":"twitter:card","value":"summary_large_image"},{"name":"twitter:title","value":"Felipe Bohórquez"},{"name":"twitter:description","value":"Coding, Technology and Entrepreneurship"},{"name":"twitter:image","value":"images/4.jpg","relativeUrl":true}]},"template":"advanced"},"html":""},{"url":"/about/","relativePath":"about.md","relativeDir":"","base":"about.md","name":"about","frontmatter":{"title":"About Me","img_alt":"Felipe Image","about-img":"images/headshot.jpg","seo":{"title":"About Me","description":"This is the about me page","extra":[{"name":"og:type","value":"website","keyName":"property"},{"name":"og:title","value":"About Me","keyName":"property"},{"name":"og:description","value":"This is the about me page","keyName":"property"},{"name":"og:image","value":"images/about.jpg","keyName":"property","relativeUrl":true},{"name":"twitter:card","value":"summary_large_image"},{"name":"twitter:title","value":"About Me"},{"name":"twitter:description","value":"This is the about me page"},{"name":"twitter:image","value":"images/about.jpg","relativeUrl":true}]},"template":"about-page"},"html":"<p>Before becoming a software engineer I worked with nationally recognized organizations including the American Bankers Association and the Congressional Hispanic Caucus Institute. After working over 4 years at Capitol Hill in human development and then 3 years in eLearning for the banking industry, I felt I was ready for the next challenge. As an entrepreneur and creative individual, I was moved by technology and its potential to bring positive change in our world🌎.</p>\n<p>How I prepared to break into tech was a process that spanned a period of over a couple of years. First I completed Information Systems studies at George Washington University, Business School. There, I participated (and won 🏆) many entrepreneurship competitions that brought a perspective of the importance of tech in understanding and bringing solutions to the problem domain.</p>\n<p>Thereafter, I completed a coding bootcamp with the number one school in the country for 2019-20, namely Flatiron School. We focused on several stacks, ranging from Ruby/Rails to JavaScript and React. I built several high quality projects ranging from Catoro (a professional coffee cupping app), a street artist tracker, an online iChing and even published a Ruby Gem that has been downloaded over three-thousand times to date! 📈. Right after graduation, I doubled my portfolio and added the MERN stack to my skills by completing various Node/Express/MongoDB projects. I also further increased my understanding of other libraries including Gatsby, SCSS and serverless technologies such as Firebase.</p>\n<p>Currently I'm working as a full stack developer for a large scale application that uses Angular for the frontend and NestJS powered by GraphQL for the backend. I'm also working on expanding my React Native skills to launch Catoro coffee app FREE on the app store!</p>\n<p>I do not forget my commitment to give back and bring positive change🤝🏼. So these days you can also see me volunteering for Bridge of Kindness non-profit, assisting their MERN donation platform or even being featured as a technical writer on <a href=\"https://careerkarma.com/blog/author/felipe-bohorquez/\">CareerKarma</a>, a famous tech website for non-traditional students, to help them break into tech! 👨🏽‍💻</p>\n<p>I'm always open to lend a hand, don't hesitate to connect and say hi 👋🏼!</p>\n<h3>Reference</h3>\n<p>I use PDF Snake to prepare blog documents for professional printing. <a href=\"https://www.pdfsnake.com/?_gl=1*1gue3ke*_ga*MTI5NjkyNzg3Mi4xNjk0NDk4ODc3*_ga_X69TS6D1SW*MTY5NDU0MTczNC4yLjEuMTY5NDU0MjYwMS4wLjAuMA..*_gcl_aw*R0NMLjE2OTQ0OTM0NTcuQ2owS0NRanc5ZnFuQmhEU0FSSXNBSGxjUVlSWUd2U2UxU0tJOWdYTzloVll2Y2pqVG10RlBiWTB3ejM3b0k5ZkRZcHRFNmhvQzloYndRWWFBakFaRUFMd193Y0I.*_gcl_au*MTA3MDczNDc5Ny4xNjk0NDk4ODc1\">Try it now too!</a></p>"},{"url":"/posts/2019-06-26-my_goal_with_understanding_metaprogramming_in_ruby/","relativePath":"posts/2019-06-26-my_goal_with_understanding_metaprogramming_in_ruby.markdown","relativeDir":"posts","base":"2019-06-26-my_goal_with_understanding_metaprogramming_in_ruby.markdown","name":"2019-06-26-my_goal_with_understanding_metaprogramming_in_ruby","frontmatter":{"title":"My Goal with Understanding Metaprogramming in Ruby","template":"post","date":"2019-06-26 16:52:11 -0400","permalink":"my_goal_with_understanding_metaprogramming_in_ruby"},"html":"<p>Article on <a href=\"https://medium.com/@fbohorqu/my-goal-with-understanding-metaprogramming-in-ruby-3c3e8fefbbe2?postPublishedType=initial\">Medium</a></p>\n<blockquote class=\"embedly-card\"><h4><a href=\"https://medium.com/@fbohorqu/my-goal-with-understanding-metaprogramming-in-ruby-3c3e8fefbbe2?postPublishedType=initial\">My Goal with Understanding Metaprogramming in Ruby - Felipe Bohórquez - Medium</a></h4><p>First things first let's dissect and define what .tap is doing here: .tap instantiates a new object and immediately pass it to a block. You see it right after object instantiation. Return value is automatically the object you modified (tapped). So it gets a new object a block level variable and whatever you tapped is the return value.</p></blockquote>\n<script async src=\"//cdn.embedly.com/widgets/platform.js\" charset=\"UTF-8\"></script>"},{"url":"/posts/2020-01-08-javascript_this_in_regular_arrow_functions_and_methods/","relativePath":"posts/2020-01-08-javascript_this_in_regular_arrow_functions_and_methods.markdown","relativeDir":"posts","base":"2020-01-08-javascript_this_in_regular_arrow_functions_and_methods.markdown","name":"2020-01-08-javascript_this_in_regular_arrow_functions_and_methods","frontmatter":{"title":"JavaScript ‘this’ in Regular, Arrow functions and Methods","template":"post","date":"2020-01-08 18:23:24 -0500","permalink":"javascript_this_in_regular_arrow_functions_and_methods"},"html":"<p>Article on <a href=\"https://medium.com/@fbohorqu/implementing-facebook-js-sdk-login-frontend-rails-api-backend-62bcbaa3f7da\">Medium</a></p>\n<blockquote class=\"embedly-card\"><h4><a class=\"embedly-card\" data-card-controls=\"0\" href=\"https://medium.com/@fbohorqu/javascript-this-a-quick-example-regular-arrow-functions-and-methods-95fdfae01c98\"> For those new to JavaScript the concept of this can take a while to settle in. A great way to understand how it behaves, is through a simple example of this in the context of regular functions, ES6 arrow functions and methods within objects.</a>\n<script async src=\"//cdn.embedly.com/widgets/platform.js\" charset=\"UTF-8\"></script></p></blockquote>"},{"url":"/posts/2019-12-23-implementing_facebook_javascript_sdk_login_frontend_rails_api_backend/","relativePath":"posts/2019-12-23-implementing_facebook_javascript_sdk_login_frontend_rails_api_backend.markdown","relativeDir":"posts","base":"2019-12-23-implementing_facebook_javascript_sdk_login_frontend_rails_api_backend.markdown","name":"2019-12-23-implementing_facebook_javascript_sdk_login_frontend_rails_api_backend","frontmatter":{"title":"Implementing Facebook JavaScript SDK Login Frontend + Rails API Backend","template":"post","date":"2019-12-24 00:36:18 +0000","permalink":"implementing_facebook_javascript_sdk_login_frontend_rails_api_backend"},"html":"<p>Article on <a href=\"https://medium.com/@fbohorqu/implementing-facebook-js-sdk-login-frontend-rails-api-backend-62bcbaa3f7da\">Medium</a></p>\n<blockquote class=\"embedly-card\"><h4><a class=\"embedly-card\" data-card-controls=\"0\" href=\"https://medium.com/@fbohorqu/implementing-facebook-js-sdk-login-frontend-rails-api-backend-62bcbaa3f7da\"> I’m going to talk about my experience building Yijing-Ball Z, a Single Page Application (SPA) with a Vanilla JavaScript Frontend and Rails API backend. More specifically, I’m going to share how I was able to implement a login interface frontend through FB authentication!</a>\n<script async src=\"//cdn.embedly.com/widgets/platform.js\" charset=\"UTF-8\"></script></p></blockquote>"},{"url":"/posts/2020-02-21-learning_about_react_hooks_a_coffee_lover_s_perspective copy/","relativePath":"posts/2020-02-21-learning_about_react_hooks_a_coffee_lover_s_perspective copy.markdown","relativeDir":"posts","base":"2020-02-21-learning_about_react_hooks_a_coffee_lover_s_perspective copy.markdown","name":"2020-02-21-learning_about_react_hooks_a_coffee_lover_s_perspective copy","frontmatter":{"title":"Learning About React Hooks — A Coffee Lover’s Perspective","template":"post","date":"2020-02-21 20:27:30 +0000","permalink":"learning_about_react_hooks_a_coffee_lover_s_perspective"},"html":"<p>Article on <a href=\"https://medium.com/swlh/learning-about-react-hooks-a-coffee-lover-perspective-c699f699fb3d\">Medium</a></p>\n<blockquote class=\"embedly-card\"><h4><a class=\"embedly-card\" data-card-controls=\"0\" href=\"https://medium.com/swlh/learning-about-react-hooks-a-coffee-lover-perspective-c699f699fb3d?postPublishedType=repub\">I became interested in hooks after I read Smart and Dumb Components while learning about React and building Catoro, a coffee tasting app.</a>\n<script async src=\"//cdn.embedly.com/widgets/platform.js\" charset=\"UTF-8\"></script></p></blockquote>"},{"url":"/posts/2019-10-22-active_storage_integration_with_google_cloud_storage_fast-track/","relativePath":"posts/2019-10-22-active_storage_integration_with_google_cloud_storage_fast-track.markdown","relativeDir":"posts","base":"2019-10-22-active_storage_integration_with_google_cloud_storage_fast-track.markdown","name":"2019-10-22-active_storage_integration_with_google_cloud_storage_fast-track","frontmatter":{"title":"Active Storage integration with Google Cloud Storage — Fast-Track","template":"post","date":"2019-10-22 18:45:04 -0400","permalink":"active_storage_integration_with_google_cloud_storage_fast-track"},"html":"<p>Article on <a href=\"https://medium.com/@fbohorqu/active-storage-integration-with-google-cloud-storage-fast-track-5198580031e1\">Medium</a></p>\n<blockquote class=\"embedly-card\"><h4><a class=\"embedly-card\" data-card-controls=\"0\" href=\"https://medium.com/@fbohorqu/active-storage-integration-with-google-cloud-storage-fast-track-5198580031e1\">Today we’re going to talk about how to setup Google Cloud Storage to host images on your Rails app. This builds from my experience hosting pictures for Uff! a Ruby on Rails web app to discover street artists.</a>\n<script async src=\"//cdn.embedly.com/widgets/platform.js\" charset=\"UTF-8\"></script></p></blockquote>"},{"url":"/posts/2020-04-21-sd_basics1/","relativePath":"posts/2020-04-21-sd_basics1.markdown","relativeDir":"posts","base":"2020-04-21-sd_basics1.markdown","name":"2020-04-21-sd_basics1","frontmatter":{"title":"Some Thoughs on Systems Design","template":"post","date":"2020-04-21 19:31:03 -0400","permalink":"sd_basics1"},"html":"<blockquote>\n<p>The Big Picture: Systems Design Basics - Part 1</p>\n</blockquote>\n<p>While taking an online course on <a href=\"https://www.educative.io/courses/grokking-the-system-design-interview\"><strong>systems design</strong></a>, I learned some cool ideas worth sharing.</p>\n<h2>Systems Design is About Thinking in Scale</h2>\n<p>When developing <a href=\"https://catoro.now.sh/\">Catoro</a>, I focused a lot on the actual functionality of the application. However, it actually never came to my head thinking questions such as <em>what if I had 100 million total users and 2 million daily users?</em>. How will the design of my backend and deployment be affected by growth?</p>\n<p>Systems design focus on <strong>distributed systems</strong> meaning a a system whose components are located on different networked computers. Some characteristic of such systems include Scalability, Reliability, Availability, Efficiency, and Serviceability/Manageability. There are also strategies of how to assess and design your system for scale.</p>\n<h2>Capacity Estimation</h2>\n<p>Lets take our example of <strong>Catoro, a coffee cupping app</strong>. Coffee cupping must be read heavy, we can assume a 1:50 ratio between read and write.</p>\n<p><strong>Traffic, Storage, Bandwidth Estimates</strong>\nIf we assume there are 2M new cuppings per month this actually means about 50M readings same month:</p>\n<p><code>2 * 50 => 50M</code></p>\n<p>What about <em>queries per second (QPS)</em>? Roughly ~0.77. So about one new cupping <strong>per second</strong>!</p>\n<p><code>2M / (3600(secs in hour)* 24hours * 30days) =~ 1</code></p>\n<p>What about reading? Well with our <em>1:50 ratio it means 50 readings per second</em>.</p>\n<p>How about <em>storage</em>? </p>\n<p>Let's assume we'll store everything for five years. Since we have 2M every month we should expect to store roughly 120M!</p>\n<p><code>2M * 12months * 5years = 120M</code></p>\n<p>What about each particular cupping? Each cupping lets assume is 1KB of information since there are a lot of parameters to track per cupping as well as total score.</p>\n<p>Since hour total storage is 120M we should expect roughly 120GB of storage just of cuppings.</p>\n<p><code>120M * 1KB =~ 120GB</code></p>\n<p><em>Tip</em>: Try <a href=\"https://whatsabyte.com/P1/byteconverter.htm\"><strong>this</strong></a> resource for a good byte/kb/gb etc. conversion tool.</p>\n<p>Regarding bandwidth of <em>incoming</em> data we should expect roughly 1KB per second as our QPS is 1/s. Read requests about 50KB with our 1:50 ratio.</p>\n<h2>Road Ahead for SD Explorations</h2>\n<p>In the next blog post we'll talk about the Database / Component Design. Tips for DB schema, REST API, Data Partitioning, Load Balancers, Telemetry and Cache.</p>\n<p><em>Stay tuned</em>!</p>"},{"url":"/posts/2020-04-05-planning_for_a_pandemic_year/","relativePath":"posts/2020-04-05-planning_for_a_pandemic_year.markdown","relativeDir":"posts","base":"2020-04-05-planning_for_a_pandemic_year.markdown","name":"2020-04-05-planning_for_a_pandemic_year","frontmatter":{"title":"Planning for a Pandemic Year","template":"post","date":"2020-04-05 19:31:03 -0400","permalink":"planning_for_a_pandemic_year"},"html":"<blockquote>\n<p>Since it does seem like very different times are coming, let's take a deep breath and do some planning for the pandemic times that lie ahead of us.</p>\n</blockquote>\n<p>I probably would never guessed a year ago how these days I was going to be writing about social distancing and promoting <a href=\"https://medium.com/@fbohorqu/stuck-at-home-join-these-tech-business-conferences-events-online-and-free-9e5a5843d80b\">online and virtual networking</a>.</p>\n<p>Since it does seem like very different times are coming, let's take a deep breath and do some planning for the pandemic times that lie ahead.</p>\n<h2>Planning for a pandemic year: What's next?</h2>\n<ol>\n<li>\n<p><strong>Continue Learning Algorithms and Data Structures</strong></p>\n<ul>\n<li>Terms like <strong>Big O</strong>, <strong>Recursion</strong>, or <strong>Dynamic Programming</strong> pop-in in coding interview questions all the time. </li>\n<li>This will also prepare me to deal with issues in terms of scale, patterns and methodically apply them to day-to-day coding problems.</li>\n</ul>\n</li>\n<li>\n<p><strong>Advanced JavaScript and Improving on TypeScript</strong></p>\n<ul>\n<li>I'll want to expand on advanced concepts to lay on top of my JS foundation. I'll also want to improve my skills with TypeScript which seems to be growing in popularity.</li>\n<li>Here I'm thinking digging deeper into <strong>closures</strong>, <strong>OOP</strong>, <strong>FP</strong>, <strong>error handling</strong> and ES6+ features. </li>\n<li>Learning about the inner workings of JavaScript also seems appealing. </li>\n</ul>\n</li>\n<li>\n<p><strong>Advanced React</strong></p>\n<ul>\n<li>Building <a href=\"https://catoro.now.sh/\"><strong>Catoro</strong></a> was an amazing experience that brought a deep interest in React.</li>\n<li>I'm thinking about implementing a React app without Create React App to practice using Webpack.</li>\n<li>Gain knowledge and implement React Hooks as well as testing.</li>\n<li>Dig into other server implementations, Firebase and GraphQL. Probably for this I'll re-iterate on <a href=\"https://yijingballz.herokuapp.com/\"><strong>Yijing Ball Z</strong></a> to see how it plays with a different backend. Let's see how many Yijing Ball Z's can live on Github at the same time. </li>\n</ul>\n</li>\n<li>\n<p><strong>Other</strong></p>\n<ul>\n<li>React Native, Node.js, Angular, Smart Contracts and Blockchain development (in no particular order).</li>\n</ul>\n</li>\n</ol>\n<h3>What <em>could be</em> next?</h3>\n<p>I'm curious to see whether (or not) I will follow this path a year from now. If there are unexpected coding experiences in the road ahead, well that could be even better. After all, I'm a big fan of surprises ;)</p>"},{"url":"/posts/2020-05-04-serverless/","relativePath":"posts/2020-05-04-serverless.markdown","relativeDir":"posts","base":"2020-05-04-serverless.markdown","name":"2020-05-04-serverless","frontmatter":{"title":"What is Serverless?","template":"post","date":"2020-05-04 19:31:03 -0400","permalink":"serverless_intro"},"html":"<blockquote>\n<p>Serverless allows you to run and deploy apps without having to worry about managing server infrastructure</p>\n</blockquote>\n<p>Probably most of us have heard about serverless computing, and probably you've asked yourself (like me) if its a good technology to learn. Here I'm sharing some high level points I learned after seeing a <a href=\"https://www.youtube.com/watch?v=MEeZLM1XVLI&#x26;feature=youtu.be\">presentation</a> about it at Byteconf React. </p>\n<h1>So, What is Serverless?</h1>\n<p><strong>Serverless allows you to run and deploy apps without having to worry about managing server infrastructure</strong>. Examples include AWS Lambda, MongoDB Stitch and Microsoft Azure. Developers then worry about building the business logic only.</p>\n<p>So the name <em>serverless can be misleading</em> because there are actually servers, its just serverless for us, the developers.</p>\n<p>Why serverless is popular right now:</p>\n<ul>\n<li>No managing infrastructure, nor provisioning.</li>\n<li>No capacity planning.</li>\n<li>No patching.</li>\n<li>Not worrying about scaling.</li>\n<li><em>Can be cheaper</em>. Not running 24/7 only when running serverless functions.</li>\n</ul>\n<p>But what's the <em>catch</em> with serverless?</p>\n<ul>\n<li>\n<p>Servers need to warm up</p>\n<ul>\n<li>If you scale up pretty quickly you need to configure this with cloud provider to mitigate this.</li>\n</ul>\n</li>\n<li>Deployment pipeline (DevOps) still needs to happen.</li>\n<li>Serverless functions means state is managed externally.</li>\n</ul>\n<h2>When to use serverless</h2>\n<ul>\n<li>If you had a static site that needs occasionally server updates. No need for 24/7 servers.</li>\n<li>Variable traffic level, and augment existing systems to handle additional load.</li>\n</ul>\n<h2>When to avoid serverless</h2>\n<ul>\n<li>If you don't want to rely on third party vendor.</li>\n<li>As app grows it might get more complicated your serverless management, so there's an additional learning curve.</li>\n</ul>\n<h2>Some considerations when using serverless</h2>\n<ul>\n<li>Avoid lock-in with a single vendor.</li>\n<li>Ensure that it remains easy to build.</li>\n</ul>\n<h2>Quick Example Connecting React App to Serverless Provider</h2>\n<p>Depending on the provider, you might have access to an SDK that you can easily include on your React app. </p>\n<p>In the example below with MongoDB Stitch you pass <code>MongoDB Stitch ID</code> on where is in the cloud and kind of works like Redux where you pass as props to get data from server components.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80838027-a5810f80-8bbd-11ea-8064-5743d907638a.png\" alt=\"demo1\"></p>\n<p>Then you can use MongoDB Queries (MQL) to get data and update state from it. </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80838438-a5cdda80-8bbe-11ea-8268-9a57ba4fccb5.png\" alt=\"demo2\"></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80838542-e594c200-8bbe-11ea-9e23-b4e50e7f76ba.png\" alt=\"demo3\"></p>\n<h2>Future of serverless</h2>\n<ul>\n<li>Infrastructure will continue to be abstracted by cloud providers.</li>\n<li>More serverless options will pop up, so many more to chose form.</li>\n<li>Serverless will get cheaper and faster in the future.</li>\n</ul>"},{"url":"/posts/2020-04-27-sd_basics2/","relativePath":"posts/2020-04-27-sd_basics2.markdown","relativeDir":"posts","base":"2020-04-27-sd_basics2.markdown","name":"2020-04-27-sd_basics2","frontmatter":{"title":"Systems Design Part 2: Digging Deeper","template":"post","date":"2020-04-27 19:31:03 -0400","permalink":"sd_basics2"},"html":"<blockquote>\n<p>Digging Deeper into SD </p>\n</blockquote>\n<p><strong>Note</strong>: This article is somewhat of a continuation of the <a href=\"http://fbohz.com/sd_basics1\"><strong>last blog</strong></a> the basics of Systems Design (SD). The main difference is that on this article I'll use <strong>examples of other SDs</strong> to explain the concepts better.</p>\n<h2>Digging Deeper: High Level System Design and REST API</h2>\n<p>After we got some capacity estimates, now it is worth coming up with a basic high level design of the system and a Entity Relationship Diagram (ERD).</p>\n<p>While I won't go into detail, here you can find an ERD and high level SD design examples: </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80003020-073ace80-8486-11ea-8223-b1a4f67ce7ce.png\" alt=\"ERD\"> </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80003150-34877c80-8486-11ea-9d3f-6b5b37041589.png\" alt=\"high level SD design\"> </p>\n<p>After this is done you can come up with your systems <strong>API endpoints</strong>. It is recommended using a REST API. Here's an example of a twitter API:</p>\n<p><code>tweet(api_dev_key, tweet_data, tweet_location, user_location)</code></p>\n<p><em>Sample API Parameters</em>:</p>\n<ul>\n<li>api<em>dev</em>key (string)</li>\n<li>tweet_data (string)</li>\n<li>tweet_location (string)</li>\n<li>user_location (string)</li>\n</ul>\n<p><em>Sample API Returns</em>: (string)</p>\n<p>Here think about any <strong>appropriate HTTP error(s)</strong> returned when accessing the API. Maybe a NotFound 404 or 403 (forbidden) if <code>api_dev_key</code> is invalid?</p>\n<h2>Component Design</h2>\n<p>The component design part can be the most complex part and is the one that talks about the scalability of our system.</p>\n<p>There's a concept called <strong>CAP Theorem</strong> that states that you cannot balance all this these characteristics (<em>Consistency, Availability, and Partition</em>) and you'll have to include tradeoffs in your design. </p>\n<p>Example: Shortening URL. Long URL hard to remember and short URL chances of collision.</p>\n<p>So in what part would you focus your design? Consistency, availability, portioning, and/or performance? What part(s) are important, why? </p>\n<p>Lets now drill down into our <strong>component design</strong>:</p>\n<ul>\n<li>Come up with a <em>workflow</em> of the system. Think about <strong>services</strong> in charge of making workflow efficient.</li>\n<li>\n<p>Database schema:</p>\n<ul>\n<li>Atomicity, Consistency, Isolation and Durability (ACID) if Relational Database Systems (RDBS).</li>\n<li>Think object / file system storage for images (e.g. Hadoop HDFS, AWS S3 ) and RDBS (MySQL) for metadata / info.</li>\n</ul>\n</li>\n<li>\n<p>Expand your SD and include Algorithms / Services:</p>\n<ul>\n<li>\n<p><em>Horizontal vs. Vertical Scaling</em>: Horizontal scaling means that you scale by adding more servers into your pool of resources whereas vertical scaling means that you scale by adding more power (CPU, RAM, Storage, etc.) to an existing server. Vertical scaling might imply downtime and comes with limit.</p>\n<ul>\n<li>Good examples of horizontal scaling are Cassandra and MongoDB. Vertical is MySQL.</li>\n</ul>\n</li>\n<li>Talk about how the application layer (logic) communicates storage layer (store / retrieve data).</li>\n<li>Assess data size per DB table.</li>\n<li>\n<p><em>Data Partitioning/Distribution</em> (e.g data sharding) and replication. Think about horizontal vs vertical partitioning</p>\n<ul>\n<li>Horizontal: put different rows in different tables. E.g. zip codes less than 10000 stored in x.</li>\n<li>Vertical: store features/resources with each other. Can be good if resource (e.g. photos) heavy.</li>\n</ul>\n</li>\n<li>Think about Reliability vs Redundancy.</li>\n<li>\n<p>Answer this: <strong>How your system handles success and failure cases?</strong></p>\n<ul>\n<li>E.g. have standby DB as replica avoid single point of failure. So have secondary backup servers. On read traffic? write, both?</li>\n</ul>\n</li>\n<li>Divide read and write storage in different servers?</li>\n</ul>\n</li>\n</ul>\n<h3>Load Balancers (LB), Cache and Telemetry</h3>\n<p><strong>Load Balancers</strong></p>\n<p>With Load balancers you can effectively distribute incoming network traffic across a group of  servers. When a new server is added to the group, the load balancer automatically starts to send requests to it.</p>\n<p>LB reduces individual server load and <strong>prevents single point of failure</strong>, thus improves application availability and responsiveness. If failure LB can redirect to next available healthy server.</p>\n<p><em>E.g. messaging app</em>: LB in front of chat servers. The LB can map each userId to a server that holds the connection for each user and then direct such request to that server.</p>\n<p>Some LB strategies:</p>\n<ul>\n<li><em>Round Robin</em>: distribute evenly across all servers, but this won't take server load.</li>\n<li><em>More intelligent LB</em>: can query servers about their load and adjust traffic based upon how they are doing.</li>\n<li>You can also have <strong>passive and active</strong> LBs to prevent single point of failure in LB as well. </li>\n</ul>\n<p><strong>Cache</strong></p>\n<p>Cache is short term for memory. Takes advantage that recently requested data might be asked again so stored locally. Cache is good for quick access to data. CDNs use cache since as they serve content if locally available.</p>\n<p>Some cache strategies: </p>\n<ul>\n<li><em>80/20 rule</em>: E.g try caching 20% of daily read volume of photos and metadata.</li>\n<li><em>Least recently used method LRU</em>: Or latest data. So it discards the least viewed first. This is a cache eviction policy.</li>\n<li>Read up on <em>Memcaching</em> and <em>Redis</em> as strategies for managing your caching system.</li>\n</ul>\n<p> <em>Note:</em> If the data is modified in the database, then it should be <strong>invalidated</strong> in the cache as this could cause inconsistent app behavior.</p>\n<p><strong>Telemetry</strong></p>\n<p>How will you monitor for <em>peaks</em>, <em>Daily Active Users (DAU)</em> and <em>average latency</em>. Thinking about this will further prepare your app to scale even further and reduce failure chances.</p>\n<h2>Conclusion</h2>\n<p>Designing distributed systems it indeed includes a lot of factors and there are many tradeoffs to consider. However it could also be a fun and creative exercise to do.</p>\n<p>Hopefully you found this SD exploration useful!</p>"},{"url":"/posts/2020-06-01-js_back_to_basics2/","relativePath":"posts/2020-06-01-js_back_to_basics2.markdown","relativeDir":"posts","base":"2020-06-01-js_back_to_basics2.markdown","name":"2020-06-01-js_back_to_basics2","frontmatter":{"title":"JS Back-to-Basics: Part II","template":"post","date":"2020-06-01 19:31:03 -0400","permalink":"js_back_to_basics2"},"html":"<blockquote>\n<p>We'll expand on last week's concepts and talk about other exciting JS foundational concepts!</p>\n</blockquote>\n<p><em>Note:</em> This is a follow up is a continuation to <a href=\"http://fbohz.com/js_back_to_basics1\">last week's article</a>.</p>\n<h2>JS Back-to-basics Part II</h2>\n<p>This week, we'll expand on last week's concepts and talk about other exciting JS foundational concepts!</p>\n<p><em>Quick Reminder</em>\nIn JS we basically</p>\n<ul>\n<li>Assign variables</li>\n<li>Write functions</li>\n</ul>\n<p>That's all we really do, all the time!</p>\n<p>As soon as JS engine sees <code>()</code> it creates an <strong>Execution Context (EC)</strong>:</p>\n<ul>\n<li>Items get pushed to our call stack each with its own execution context</li>\n<li>\n<p>It starts with the <code>global()</code> execution context (first item in the stack), then narrows down to the function being called.</p>\n<ul>\n<li>This global() has the <code>globalObject</code> and <code>this</code>.</li>\n<li>In browser the globalObject is the <code>window</code>.</li>\n<li>Depending on the function context <code>this</code> might refer to one thing or the other.</li>\n<li>You can add functions, variables to this globalObject</li>\n</ul>\n</li>\n<li><em>Execution base</em> is where you run your code.</li>\n</ul>\n<p><strong>Lexical Environment / Scope</strong></p>\n<ul>\n<li>It means <strong>where</strong> you write something.</li>\n<li>They are like little universes each time there's a new execution context.</li>\n<li>Functions within functions are in the lexical environment of another functions (closures).</li>\n<li>Knowing where it was written, the compiler can make decisions what to do.</li>\n<li>Remember every time we add a new function we create a \"new planet\".</li>\n</ul>\n<p>Execution context tells which lexical environment (\"planet\") is currently running.</p>\n<p><strong>Our lexical scope (available data + variables where functions were defined) determines our available variables NOT where the function is called (dynamic scope)</strong>. It doesn't matter where we call our functions.</p>\n<p><em>The very first lexical environment is the global environment</em>.</p>\n<p><strong>Hoisting</strong></p>\n<p>In the creation phase (when set globalObject and 'this') before execution of code we have hosting:</p>\n<ul>\n<li>Hoisting is the behavior of moving variables and fn declarations to their context.</li>\n<li>\n<p>During creation phase (first go through) it allocates memory. As soon as they see variables or function it allocates them, the first run they will be as <code>undefined</code>.</p>\n<ul>\n<li>Variables with <code>var</code> are then <strong>partially hoisted</strong>. Var is as undefined.</li>\n<li><code>let</code> and <code>const</code> are NOT hoisted.</li>\n<li>Function declarations are <strong>fully hoisted</strong>.</li>\n<li>Function expressions (defined with var) are partially and <code>undefined</code>.</li>\n</ul>\n</li>\n<li>Compiler is not moving lines but in the first pass is just <strong>allocating memory</strong></li>\n</ul>\n<p><strong>Function Invocation</strong></p>\n<p>Remember JS <strong>programs assign in memory variables and then write functions to do something with those variables</strong>.</p>\n<p>So what are functions?</p>\n<ul>\n<li>Function <em>declaration</em> start with <code>function</code> keyword. They get hoisted. Define at run-time.</li>\n<li>Function <em>expression</em> are saved to a variable. Expressions don't get hoisted. Defined at parse-time, first run because hoisted.  . </li>\n<li>\n<p>Functions have invocation/call/execution</p>\n<ul>\n<li>We invoke by running in parenthesis like <code>myFunction()</code>.</li>\n</ul>\n</li>\n<li>\n<p>With function invocation we get the <code>arguments</code> keyword.</p>\n<ul>\n<li>This arguments keyword gives us an object with the arguments.</li>\n<li><code>arguments</code> is only available when we create new execution context with a function.</li>\n<li>Remember <strong>do not use arguments keyword</strong>. They are not an array, so cannot use array methods but if you use <code>Array.from</code> you could convert into array object it.</li>\n</ul>\n</li>\n<li>You can also use spread operator in our arguments such as. <code>function marry(...args) {console.log(args[0])}</code></li>\n</ul>\n<p><strong>Variable Environment</strong></p>\n<p>What about variables created inside of execution contexts of functions? They are called Variable Environment.</p>\n<p>Some functions have access to certain variables, while others not. Remember functions have their own execution content in which variables reside and the first execution context is the global() one. </p>\n<p>Variables default to their outermost execution context. Execution context have their own variable environment.</p>\n<p><strong>Scope Chain</strong></p>\n<p>Each EC has a link to the outer world. When the code runs it goes down the scope chain in parent environment if it doesn't find variable.</p>\n<pre><code class=\"language-js\">var x = 'x'\n\nfunction printX() {\n  console.log(x)\n}\n</code></pre>\n<p>Lexical or <strong>static</strong> scope, only by looking at code determines  which environment a certain variable lives in. Scope chain starts inner and goes all the way to global context.</p>\n<p><strong>Function lexical environment</strong>, creates closures on environment.  This closures are defined internally so you cannot access outside for a variable that is defined internally. </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81589013-b0d2f880-937e-11ea-9b06-0e95b6118953.png\" alt=\"scopeclosure\"></p>\n<p><strong>Reminder</strong>\nRemember <code>undefined</code> means, <strong>yes</strong> we have 'x' variable but it doesn't have any value while something like <code>Reference Error</code> is like 'x' is completely undeclared not found anywhere in the scope chain.</p>\n<p>Lexical environment === [[scope]]. So each environment has a field, and each field with its own scope and the link to next scope. Also named [[scope]]. <code>Scopes</code> will give you all the scopes you can test in console.</p>\n<p><strong>Function vs Block Scope</strong>\nScope means what variables we have access to.</p>\n<p>Other coding languages have <em>block scope</em>. Any time you do code in curly brackets <code>{}</code> you create block scope. In JS this is done with <code>let</code> and <code>const</code> create block scope!</p>\n<p>So let and const <strong>create block scope</strong> just like in {}</p>\n<p><strong>Caution with Global Variables</strong></p>\n<p>You can pollute global namespace. Remember <strong>we have limited space and our memory heap is limited</strong>. You can pollute global scope by keeping adding global variables.</p>\n<p>You can also <strong>overwrite</strong> global variables. So avoid them.</p>\n<h2>Concluding Thoughts</h2>\n<p>This seems to be a robust discussion on JS foundational concepts. There are still other concepts worth exploring including IIFE, <code>this</code> keyword and more. Please be sure to read on them. An article I previously wrote about <code>this</code> can be found <a href=\"https://medium.com/swlh/javascript-this-a-quick-example-regular-arrow-functions-and-methods-95fdfae01c98\">here</a>.</p>"},{"url":"/posts/2020-05-18-component_library_storybook/","relativePath":"posts/2020-05-18-component_library_storybook.markdown","relativeDir":"posts","base":"2020-05-18-component_library_storybook.markdown","name":"2020-05-18-component_library_storybook","frontmatter":{"title":"React Component Library","template":"post","date":"2020-05-18 19:31:03 -0400","permalink":"component_library_storybook"},"html":"<blockquote>\n<p>React component libraries ensure that your application is well designed, accessible and easy to use. </p>\n</blockquote>\n<p><em>Note:</em> This short article is a continuation of what I learned while participating at <a href=\"https://www.bytesized.xyz/react-2020\">Byteconf React</a>. </p>\n<p><strong>React component libraries</strong> ensure that your application is well designed, accessible and easy to use. </p>\n<p>As applications grow and evolve they could face these challenges:</p>\n<ul>\n<li><strong>Lack of consistency</strong>: like different colors, fonts, so UI styles changes. UI elements could be different depending of component.</li>\n<li><strong>UX challenges</strong>: E.g. if confirm button is blue on one page but then the cancel is blue on the next it can cause confusion.</li>\n</ul>\n<p>Here's where component libraries can really help! 🙌🏼</p>\n<h2>Storybook to the Rescue!</h2>\n<p>First things first. The truth is that it <strong>takes time</strong> to build component libraries 😑. So often no one wants to build these. <strong>However, it is worth investing the upfront time</strong>.</p>\n<p><strong>React Storybook</strong></p>\n<p>Storybook is a React tool for developing UI components. An example of using Storybook tool to build component libraries can be found <a href=\"https://myelin.herrmannsolutions.net/\">here</a>.</p>\n<p>By using Storybook you can have a centralized a place for quick reference and create faster prototyping.  It offers example of common components along with specific styling and documentation.</p>\n<p>Some examples:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80983926-cb432a00-8df2-11ea-9c9e-4c0022e0e0d3.png\" alt=\"example1a\"></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80983923-ca11fd00-8df2-11ea-8b7d-48ae1ca4b86b.png\" alt=\"example1b\"></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80983919-c8e0d000-8df2-11ea-8f40-c1dac9bc69a1.png\" alt=\"example2a\"></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80983890-bd8da480-8df2-11ea-94ca-16b5065001f6.png\" alt=\"example2b\"></p>\n<h2>How to Build Your Own Library</h2>\n<p>Building the components is the easiest part of building the library. Storybook has many add-ons you can use. You can start with vanilla Storybook and expand.</p>\n<p>For animated components you can use <strong>GreenSock</strong> or <strong>Animate.CSS</strong>. For icons you can use FontAwesome. You can also try Rollup.js as an alternative to Webpack. </p>\n<p><em>Building Your Library</em></p>\n<p>Go through your app screen by screen and create an <strong>interface inventory</strong> in a document. </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80984904-1873cb80-8df4-11ea-8ab1-6a97a5030795.png\" alt=\"uiinventory\"></p>\n<p>Then choose the <em>most used</em> components (8 max at the beginning). At the beginning you'll copy the code of it into Storybook.</p>\n<p>As you have your <strong>library small</strong> of 5-8 components, you can have users start getting used to the library without having a lot of <em>unused components</em>.</p>\n<p>Think about different situations in which each component will be used and build library on it. E.g. buttons:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80985340-b5366900-8df4-11ea-9141-aca06586b0a1.png\" alt=\"buttons\"></p>\n<p>Not only colors here but also <em>state</em> (e.g. disabled, active states).</p>\n<p><em>Consistent Components and Documentation</em></p>\n<p>Documentation is key so your users of the library will know how and when to use each component.</p>\n<p>Check out this component <a href=\"https://twitter.com/EmmaBostian/status/1177248937763311617\">checklist</a> you can use as you build your library.</p>\n<p><em>Testing your Library</em></p>\n<p>As you have users testing your library you might have to do edits. You can prevent this by being thorough and trying to go on all use cases of components.</p>\n<p>Ask users for specific feedback. E.g. What parts are useful/not useful? Do they hit snags in implementation?</p>\n<p><em>Expanding and Maintaining Your Library</em></p>\n<p>Keep <strong>backlog of components</strong> that you want to build in the future. This is important as you start to include other team members to contribute in your library. </p>\n<p>You might also see that some components are not being used. Try to reduce this clutter in library. Check with other developers and designers why a component is not being used. <strong>Tag components</strong> to denote status. E.g. retiring, active component etc. This labeling will keep users up-to-date on whats going on with your library.</p>\n<p>You can also have an external version of library (such as the link shared above). The internal version can have internal tags as well, IP information, etc.</p>\n<p><em>Maintenance</em> is also key. Think where you can tie component library creation. Sprint planning can be useful to tie it with the component backlog. Make sure you're active in maintaining your library so it doesn't become outdated.</p>\n<p><em>Final tips</em></p>\n<ul>\n<li><strong>Keep it simple</strong>. Sometimes being limiting/restricting on props, might mean you have to add a lot of conditionals to keep up with all the use cases. So being open at the beginning can save you a lot of upfront time. Start with less opinionated component and build from there if really need it. Make your components more flexible. See my <a href=\"http://fbohz.com/react_pattern_apropcalypse\"><strong>last blog</strong></a> for more info on flexible components.</li>\n<li>Unfinished components are ok. Build from the feedback of your users.</li>\n<li>Have accesibility in mind.</li>\n<li><a href=\"https://atomicdesign.bradfrost.com/table-of-contents/\"><strong>Read Atomic Design Book</strong></a> to increase your knowledge and build a solid library with advanced components families. </li>\n<li>Don't forget the <a href=\"https://twitter.com/EmmaBostian/status/1177248937763311617\"><strong>component checklist</strong></a> you can use as you build your library.</li>\n<li>Check out the presentation video <a href=\"https://youtu.be/MEeZLM1XVLI?t=10258\"><strong>here</strong></a>.</li>\n</ul>\n<p>That's all folks. Happy component library building! 📗</p>"},{"url":"/posts/2020-06-08-react_basics_refresher/","relativePath":"posts/2020-06-08-react_basics_refresher.markdown","relativeDir":"posts","base":"2020-06-08-react_basics_refresher.markdown","name":"2020-06-08-react_basics_refresher","frontmatter":{"title":"React ⏱ \"5 Minute\" Refresher","template":"post","date":"2020-06-08 19:31:03 -0400","permalink":"react_basics_refresher"},"html":"<blockquote>\n<p>This is a React refresher on the basics...If you're new to React this should get you started on a conceptual realm. </p>\n</blockquote>\n<h1>React ⏱ \"5 Minute\" Refresher</h1>\n<p>This is a React refresher on the basics, <strong>recommended to those with experience in React</strong>. If you're new to React this should get you started on a conceptual realm. </p>\n<h2>React Brief History</h2>\n<ul>\n<li>Back in the day, websites had synchronous tasks from the backend, and refreshed the page every time new data was needed.</li>\n<li>jQuery took care of complexities and also worked in all browsers.</li>\n<li>Backbone.js allowed to organize these .js files.</li>\n<li>\n<p>Single Page Applications (SPA) were born out of working more and more with the DOM.</p>\n<ul>\n<li>AJAX downloading all files at once. JS updating as needed.</li>\n</ul>\n</li>\n<li>\n<p>Angular.js was born out of this. It had containers that wrap the project. It also had an MVC pattern.</p>\n<ul>\n<li>Angular in the beginning was very complex. Data flowing everywhere and app maintenance was harder.</li>\n</ul>\n</li>\n<li>In 2013 React was released by Facebook. In 2014 Angular was also rewritten as a response.</li>\n</ul>\n<h2>React Core Principles</h2>\n<ul>\n<li>\n<p>React virtual DOM (don't touch the DOM). React will do it. </p>\n<ul>\n<li><em>Imperative Programming</em>: Changing directly the DOM through JS (e.g. <code>getElementById</code>). This approach has that it becomes difficult to point and identify relationships between events.</li>\n<li><em>Declarative Programming</em>: Declares to React what the state or data should look like. React will make the decision of how to implement it. This <code>state</code> is one big JavaScript object. Resulting in less complexity, and faster developer times. </li>\n</ul>\n</li>\n<li>\n<p><em>Components</em> </p>\n<ul>\n<li>Put them together and they form bigger components and the whole app. You can copy these components and reuse them. </li>\n<li>Components are built with JSX. JSX stands for JavaScript XML. JSX allows us to write HTML with JavaScript.</li>\n<li>Reusable components and we can use many component NPM packages. E.g React.Bootstrap, Blueprint etc.</li>\n</ul>\n</li>\n<li>\n<p><em>Unidirectional</em> Data Flow.</p>\n<ul>\n<li>Anytime we want something to change <code>state</code> has to change.</li>\n<li>Data flows one way. State changes and trickle down. Data can't move up.</li>\n<li>This could allow for easier debugging.</li>\n<li>Angular is often thought as the opposite.</li>\n</ul>\n</li>\n<li>\n<p>React is not a framework</p>\n<ul>\n<li>Angular is a framework and gives you everything. </li>\n<li><em>React is a library</em> and lets you use any tools you want from outside.</li>\n</ul>\n</li>\n<li>\n<p>React Everywhere</p>\n<ul>\n<li>React Native</li>\n<li>React Desktop and React 360 (VR)</li>\n</ul>\n</li>\n</ul>\n<h2>Create-React-App</h2>\n<ul>\n<li>Run as <code>npx create-react-app &#x3C;app-name></code></li>\n<li>Create-React-App is CLI created so we can build fast apps.</li>\n<li><code>npx</code> allows you to build using Create-React-App without globally installing it first.</li>\n<li>When we do <code>build</code> on React project, it will take all code inside src folder and bring it to public folder.</li>\n<li>Babel will make sure that the JS files will work on all browsers.</li>\n<li>Webpack is a module bundler that allows to write modular code. It takes all our Javascript and optimizes it for us.</li>\n<li><code>react-scripts</code> does things for us so we don't worry about Webpack nor Babel. </li>\n<li>React library allows us to write JSX. ReactDOM like the virtual DOM which interacts with the actual DOM, and makes DOM decisions for us.</li>\n</ul>\n<p><strong>Warning:</strong> Ejecting Create-React-App</p>\n<ul>\n<li>You have all scripts for Webpack to build, start and test your app.</li>\n<li>It's a lot of code, so not recommended to eject. </li>\n<li>It is a lot like competing with a team of developers that work full time on this. They keep up-to-date with industry trends.</li>\n</ul>\n<h2>Expanding React Key Concepts</h2>\n<p><strong>React and JSX</strong></p>\n<p>JSX has different keywords such as <code>className</code> instead of regular HTML 'class'. Also anything in between <code>{}</code> is JavaScript injected through JSX.</p>\n<p>React always intercepts all events and then we use setState to trigger a <em>re-render</em>. React re-renders anytime state is updated. </p>\n<p>So JSX creates that virtual DOM with state and then React re-renders the DOM as state changes.</p>\n<p><strong>React Components</strong></p>\n<p>Our React components act like custom elements that we can mix with common HTML elements but with special powers! </p>\n<p>You can have React components as classes or as functions. React class components have a <code>render()</code> method. We use classes to get access to <code>state</code> and <code>setState</code> to change state. We build these with ES6 <code>class</code> syntax.</p>\n<p>To be able to do special things we get to use the special attribute <code>props</code> that carry data, functions and anything in between to make our application work effectively.</p>\n<p>We can also have components that <em>do not</em> extend from <code>React.Component</code>. We can also get access to state via <em>hooks</em>. We build this with ES6 arrow functions. In the past these functional components only received props and returned HTML from JSX. With hooks, this has changed.</p>\n<p>You might notice how Class Components could have methods and arrow function declarations inside. </p>\n<p><strong>Good Rule of Thumb</strong>: </p>\n<p>Use <em>arrow functions</em> on any methods you define that aren't part of React (i.e. render or componentDidMount).</p>\n<p><strong>React Lifecycle Methods (Class Components)</strong></p>\n<p>They are methods that get called automatically by React in particular instances of its component life.</p>\n<ol>\n<li><code>constructor()</code>: Called first. Allows the class to have access to lifecycle components. Here is where you declare your state.</li>\n<li><code>render()</code>: Render is called next to display HTML.</li>\n<li><code>componentDidMount()</code>: This lifecycle method is called when component is mounted and good for calling API requests. This will also cause a re-render so <code>render()</code> gets called again. It runs every time you refresh the page.</li>\n<li><code>componentDidUpdate</code>: Any state updates brings your component to this updating phase. React here selectively changes parts of the DOM and it <em>doesn't remount the component</em>. <code>componentDidUpdate</code> is called after update. Here you can do additional fetch calls as you compare previous and new props. <a href=\"https://reactjs.org/docs/react-component.html#componentdidupdate\"><strong>Read more</strong></a>.</li>\n</ol>\n<p>Other lifecycle methods:</p>\n<ul>\n<li><code>shouldComponentUpdate()</code>: It checks the props and can decide whether or not update. This is done for optimization. Read <a href=\"https://reactjs.org/docs/react-component.html#shouldcomponentupdate\"><strong>here</strong></a> to learn more. You can also consider using React Pure Components, read <a href=\"https://reactjs.org/docs/react-api.html#reactpurecomponent\"><strong>here</strong></a>.</li>\n<li><code>componentWillUnmount()</code>: Called when a component is being removed from the DOM. This is where cleanup can be done, including memory leaks that JS garbage collection has not picked up. Read <a href=\"https://reactjs.org/docs/react-component.html#componentwillunmount\"><strong>docs</strong></a> to learn more.</li>\n</ul>\n<p>Check out this useful <a href=\"https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/\">diagram</a> on React lifecycle methods.</p>\n<p><strong>Dawn of SPAs</strong></p>\n<p>Before you used to make requests to the backend and you'll visit one or more pages. Now with SPAs (although the Javascript file is bigger) we don't have to keep coming back to request a new page to the server. Today we just <em>request for data</em> and refresh any part of the page we need. </p>\n<p>So with SPAs you'll start talking with APIs to get the data you need. We build pages dynamically depending on user input/interaction.</p>\n<p><strong>How do we decide to break a part of our app into a component?</strong></p>\n<p>This is key for you to practice and know as a React developer. You should decide this for yourself. The idea is that you can reuse this components on other applications and make things more flexible. So you start building your component library. </p>\n<p>Learn more about component libraries <a href=\"http://fbohz.com/component_library_storybook\">here</a>. </p>\n<p><strong>State and Props</strong></p>\n<p>When we pass down state, this is usually received as prop by children. This is related to <em>one way data flow</em> of React. </p>\n<p>Remember you can also put state wherever you want. You'll have to practice how to implement that. Every time state changes there might be implications on re-render and could affect performance. You'll start seeing how there is a <em>tree of state</em> that any changes might have trickle down effects.</p>\n<p>When you work on your tree of state you might want to <em>lift state</em> to parent components so that it can be shared by children. </p>\n<p>Managing state can become tedious and complicated at best, we recommend using <a href=\"https://redux.js.org/\">Redux</a> state management add-on as your state gets more complicated. </p>\n<p><strong>Synchronous vs Asynchronous</strong></p>\n<p>Remember this distinction. Synchronous happens literally immediately. Async takes time that JavaScript nor React knows. JS runs the code after it, and then returns when the promise is resolved. React <code>setState()</code> is async, because React decides for itself when is the best time to run it. </p>\n<p>Tip: In order to see changes after using setState you must use its second argument. <a href=\"https://medium.com/@yelstin.fernandes/using-setstates-optional-second-parameter-in-react-js-1ecd5de6f1ea\">Read more</a>. There has been state management improvements specially with Hooks. However Redux has been well tested for scale. Do stick to Redux to manage more complex state.</p>\n<p><strong>Virtual DOM</strong></p>\n<p>Remember we don't directly (imperatively) change the DOM. React takes care of the DOM through the virtual DOM. React has what is called <code>synthetic event</code>, which it means that React will interfere on all events and decide what to do. React only deals with the real DOM when it sees fit and with its own patterns, that is why React feels so fast. </p>\n<p>So React takes all the hard work on showing and hiding elements from the DOM for us. But we have to learn its re-render mechanism and how to manage state. This will make us a pro React developer.</p>\n<h2>How Can I be a Top React Developer? 🚀</h2>\n<ol>\n<li><strong>Decide on Components</strong>: What is a component and how will you divide the app.</li>\n<li>Decide on <strong>state and where it lives</strong>. Decide how you'll manage state (e.g. Redux, hooks, or props).</li>\n<li>Know <strong>what changes when state changes</strong>.</li>\n</ol>\n<h2>Resources</h2>\n<ul>\n<li><a href=\"https://jsonplaceholder.typicode.com/\"><strong>JSON Placeholders</strong></a></li>\n<li>Styling with<a href=\"https://www.youtube.com/watch?v=feYJ5D7VknE&#x26;feature=emb_title\"> <strong>Styled Components</strong></a>.</li>\n<li><a href=\"https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/\"><strong>React lifecycle methods</strong></a>.</li>\n<li><a href=\"https://www.udemy.com/course/complete-react-developer-zero-to-mastery/\"><strong>React course</strong></a>.</li>\n<li><a href=\"https://reacttraining.com/react-router/web/guides/quick-start\"><strong>React Router</strong></a>. For Navigation in React. How is navigation possible in SPAs? React Router takes advantage of the history API brought by modern browsers to mimic routing.</li>\n</ul>\n<p>😅 You know this wasn't literally a \"5 minute\" refresher. But hopefully it was useful. Happy React studying 🙌🏼</p>"},{"url":"/posts/2020-05-25-js_back_to_basics1/","relativePath":"posts/2020-05-25-js_back_to_basics1.markdown","relativeDir":"posts","base":"2020-05-25-js_back_to_basics1.markdown","name":"2020-05-25-js_back_to_basics1","frontmatter":{"title":"JS Back-to-Basics: Part I","template":"post","date":"2020-05-25 19:31:03 -0400","permalink":"js_back_to_basics1"},"html":"<blockquote>\n<p> We'll go back to the basics in JavaScript and discuss about the JS Engine and JS Runtime</p>\n</blockquote>\n<p>On this article, we'll go back to the basics in JavaScript and discuss about the JS Engine and JS Runtime.</p>\n<h2>JavaScript Engine</h2>\n<p>JS Engine allows to have the machine to understand code. So it acts as a <em>translator</em>. There are a ton of JS Engines written by programmers. They can be written in other languages such as C++. An example of this is V8. These engine allows JS to run faster and faster.</p>\n<p>Engines looks for lexical analysis formed into a <strong>tree like structure call AST</strong>:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81210695-db483e80-8f97-11ea-820d-3006718796e1.png\" alt=\"1\"></p>\n<p>It then goes to the interpreter and moves forward so it can be understood by computer.</p>\n<p>ECMAScript was created as governing body of JS. It tells engine creators parameters of creating engines. There are many engines b/c they can be implemented in many ways.</p>\n<p><strong>Interpreters and Compilers</strong></p>\n<p>Interpreter translates and reads file line-by-line. Compiler doesn't translate on the fly. Compiler does one run and then writes a new program in a program that the computer can understand like machine code. You can still run JS using one or the other.</p>\n<p><strong>Babel and Typescript</strong> </p>\n<p>They are heavily used in the Javascript ecosystem and you should now have a good idea of what they are.</p>\n<p>Babel is a Javascript compiler that takes your modern JS code and returns  browser compatible JS (older JS code). Typescript is a superset of Javascript that compiles down to Javascript.</p>\n<p>Both of these do exactly what compilers do: Take one language and convert into a different one!</p>\n<p><strong>V8 Engine</strong></p>\n<p>Interpreter is good for JS. Interpreters can get very slow with things like loops and often doesn't do optimization. Compiler can be a bit better in some instances.</p>\n<p><em>JIT Compiler:</em> Just In Time Compilers. V8 engine does this to get best of both worlds. Here the profiler and compiler work as the code is running.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81311026-7c8fcd00-904a-11ea-88c4-3ec3d28c19f0.png\" alt=\"2\"></p>\n<p><strong>Compared with other languages</strong></p>\n<p>.exe is usually a C++ file that is compiled to a executable machine code file. Java uses the JVM to compile code.</p>\n<p>Javascript initially was an interpreted language with time evolving JS has compilers as part of V8 engine, so depends. Python can also be run through a compiler or interpreted.</p>\n<p><strong>Writing Efficient / Optimized Code</strong></p>\n<p>Be mindful with some keywords and JS patterns that can make code not optimized.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81311646-4868dc00-904b-11ea-9d81-4430dc05d9da.png\" alt=\"3\"></p>\n<p>Thinks like inline caching and hidden classes. For hidden class you want to assign properties of the object in the constructor or add things in the same order. </p>\n<p>Some of these optimizations help the compiler.</p>\n<p>Some Resources:</p>\n<ul>\n<li>Read article <a href=\"https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments\"><strong>here</strong></a></li>\n<li>Check <a href=\"https://richardartoul.github.io/jekyll/update/2015/04/26/hidden-classes.html\"><strong>this other article</strong></a></li>\n</ul>\n<p><em>So why don't write machine code from the beginning?</em></p>\n<p>WebAssembly - could make things better and avoid some JIT Compiler and make things more standarized.</p>\n<h2>JS Engine Key Concepts</h2>\n<p><strong>Call Stack and Memory Heap</strong></p>\n<p>JS engine needs to store and keep track of everything. Memory heap uses, allocates memory. Call stack keeps track of where we are in the code in the execution.</p>\n<p>Memory heap is like a free store, with no order. Allows to store variables.</p>\n<p>Call stack is like a region in memory acts like a FIFO method. You add things like functions to the call stack starting with the global execution context (sometimes as anonymous)</p>\n<p>You can check the call stack in google chrome:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81314979-59b3e780-904f-11ea-97ff-0b65c0ad2022.png\" alt=\"4\"></p>\n<p>So call stack stores functions in memory. And <strong>the first one in is the last one getting popped out the call stack</strong>.</p>\n<p>Where variables are allocated it depends, sometimes they are stored in the stack and more complex are in memory heaps. More on this soon.</p>\n<p><strong>Stack Overflow</strong></p>\n<p>Happens when we keep calling functions nested over and over. This happens a lot with recursion functions (functions that call themselves). Example:</p>\n<pre><code class=\"language-js\">function inception() {\n    inception()\n}\n</code></pre>\n<p><strong>Gargage Collection</strong></p>\n<p>When JS allocates memory automatically with JS when we finish calling the function it is going to clean it. So it automatically frees up the memory we no longer use. </p>\n<p>In that case it makes sure we don't use all memory. It gives a false sense of security. <em>JS developers sometimes have false impression that they don't need to care about memory</em>.</p>\n<p>In JS garbage collection uses a <em>mark and sweep</em> algorithm. So it basically 'marks' what it needs and 'seeps' what it doesn't.</p>\n<p><strong>Memory Leaks</strong></p>\n<p>Memory can happen on <em>infinite loops</em> when we fill our memory heap and app crashes.</p>\n<p>Common memory leaks:</p>\n<ul>\n<li>Global Variables.</li>\n<li>\n<p>Event listeners</p>\n<ul>\n<li>So add event listeners and you never remove them when you don't need them.</li>\n</ul>\n</li>\n<li>\n<p>Using <code>setInterval</code></p>\n<ul>\n<li>unless we clear it and stop it it will run and run.</li>\n</ul>\n</li>\n</ul>\n<p>An example happened with SoundCloud plug-in the background <a href=\"https://developers.soundcloud.com/blog/garbage-collection-in-redux-applications\">here</a></p>\n<p><strong>JS is Single Threaded</strong></p>\n<p>JS is a single threaded programming language so only one set of instructions at the time. It only has <em>one call stack</em>.</p>\n<p>Because of this JS is synchronous, doing one thing at a time.</p>\n<ul>\n<li>This could make difficult with long running tasks. An example is <code>alert</code> that when it is executed only alert runs.</li>\n</ul>\n<p>However most of the time we <em>don't use JS Engine</em> but use the <em>JS Runtime</em> to make things asynchronous.</p>\n<h2>JavaScript Runtime</h2>\n<p>So how do we make asynchronous calls? with the JS Runtime.</p>\n<p><em>Web API</em> </p>\n<p>The Web API communicates with JS engine and comes with browser. These web API can do variety of things. The web API is usually the <code>window</code> and you can check what it has available such as <code>fetch</code>, <code>setTimeout</code>. </p>\n<p>Browser provides help so that users don't keep waiting for things to finish. So browser uses low level languages such as C++ to do other stuff.</p>\n<p><em>Event Loop</em>\nItems come to call stack, lets say <code>fetch</code> comes, the call stack identifies it and gives it to the Web API and it doesn't it in the background. Web API returns data received to the appropiate part.</p>\n<pre><code class=\"language-js\">console.log('1')\n\nsetTimeout(() => {console.log('2')}, 0)\n\nconsole.log('3')\n</code></pre>\n<p>This runs 1, 3, 2 because it has timeout. No matter the length. Then moved away from call stack gives back to web API for setTimeout. </p>\n<p>No matter how fast setTimeout is, it still gets sent to the Web API.</p>\n<p><a href=\"http://latentflip.com/loupe/?code=ZnVuY3Rpb24gcHJpbnRIZWxsbygpIHsNCiAgICBjb25zb2xlLmxvZygnSGVsbG8gZnJvbSBiYXonKTsNCn0NCg0KZnVuY3Rpb24gYmF6KCkgew0KICAgIHNldFRpbWVvdXQocHJpbnRIZWxsbywgMzAwMCk7DQp9DQoNCmZ1bmN0aW9uIGJhcigpIHsNCiAgICBiYXooKTsNCn0NCg0KZnVuY3Rpb24gZm9vKCkgew0KICAgIGJhcigpOw0KfQ0KDQpmb28oKTs%3D!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D\"><strong>Great tool to visualize Call Stack and Web APIs</strong></a></p>\n<p>This makes it possible to not rely on just one call stack and memory heap and achieve asynchronous code, with <strong>multiple threads</strong>.</p>\n<h2>Final Thoughts</h2>\n<p>There are many Runtimes, so what is <em>Node.js</em>? </p>\n<p><strong>Node.js</strong> is a <em>runtime</em>. So it runs outside the browser. It is a C++ program, like a Node.exe. With Node you can access the file system and other things. There are differences such as in Node there's not window but it is replaced with <code>global</code>. It creates a runtime outside of the browser. It also uses the asynchronous runtime.</p>\n<p><strong>Stay tuned for next week's article</strong>, as we'll talk about more basic JavaScript concepts. 'Till then!</p>"},{"url":"/posts/2020-06-15-firebase_in_react/","relativePath":"posts/2020-06-15-firebase_in_react.markdown","relativeDir":"posts","base":"2020-06-15-firebase_in_react.markdown","name":"2020-06-15-firebase_in_react","frontmatter":{"title":"Implementing Firebase in a React Project","template":"post","date":"2020-06-15 19:31:03 -0400","permalink":"firebase_in_react","filename":"2020-06-15-firebase_in_react"},"html":"<blockquote>\n<p>In Building <a href=\"https://studio-ghibli-fanhub.herokuapp.com/\">Studio Ghibli's Fan Hub</a>, a project made with React, I decided to implement Firebase for its backend.</p>\n</blockquote>\n<h1>Implementing Firebase in a React Project ✨</h1>\n<p>In Building <a href=\"https://studio-ghibli-fanhub.herokuapp.com/\">Studio Ghibli's Fan Hub</a>, a project made with React, I decided to implement Firebase for its backend.</p>\n<p>Note: Firebase library is always expanding and evolving. You can read about what we went over <a href=\"https://firebase.google.com/docs/auth/web/google-signin\">here</a>.</p>\n<p><strong>What is Firebase?</strong></p>\n<p>Firebase as being a backend deals with everything related to:</p>\n<ul>\n<li><em>Database</em>: any data important to application. The frontend will pull the data that it needs.</li>\n<li><em>Server</em>: Server determines the most efficient way to get the data out of the database.</li>\n<li><em>Authentication</em>: It is the way in which we confirm the users and authenticate them so they can access their data. So they confirm whether or not the user is who they say they are (through passwords, SSO login).</li>\n</ul>\n<p>Firebase is pretty efficient and is maintained by Google. It gives a lot of features to developers without having to do a lot of backend development.</p>\n<h2>Getting Started with Firebase</h2>\n<p>Once you access the Firebase website make sure you login with your Google account then click on 'Create/Add Project'. Add the project name usually as <code>projectName-db</code> or <code>projectName-backend</code> . Then leave all the defaults and let your project finish up spinning up and completing setting up.</p>\n<p>Now make sure you are in the <em>Spark - Free Plan</em>. You'll wanna upgrade as you feel more comfortable with Firebase. At the beginning is very rare you exceed the limits.</p>\n<p>As you look at your project focus on the Develop tab and get acquinted with it specially the three first sections:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83354289-38c47680-a31d-11ea-91fe-71f7f59142c3.png\" alt=\"1\"></p>\n<p>Here it is worth mentioning that Storage is more for assets like images and videos and database is more your other types of data.</p>\n<p>Other sections such as Hosting involve Firebase hosting your website, ML Kit is for machine learning and Functions you'll learn when you're more advanced.</p>\n<h2>Setting up our Firebase Backend for React App</h2>\n<ol>\n<li>Click on 'Project Overview' on top.</li>\n<li>Click on Web Icon (the last)</li>\n<li>Register firebase by adding a name (internal name) like the convention above. I named mine also as <code>studio-ghibli-fan-hub-db</code>. </li>\n<li>You'll get a code snippet. Make sure you <em>copy</em> the <code>var firebaseConfig</code> contents which includes your API configuration.</li>\n<li>Go back to terminal and do <code>yarn add firebase</code> or <code>npm i firebase</code>.</li>\n</ol>\n<p>Now we're ready for the next step ✨</p>\n<h2>Adding Firebase to our React App</h2>\n<ul>\n<li>Create a folder named 'Firebase' inside your 'src' folder. Then make a new file called <code>firebase.utils.js</code>. Make sure you have that config object info ready.</li>\n<li>Then do the following to import your firebase utilities.</li>\n</ul>\n<pre><code class=\"language-js\">import firebase from 'firebase/app'\nimport 'firebase/firestore'\nimport 'firebase/auth'\n\nconst config = {\n    // your config info here\n}\n\nfirebase.initializeApp(config)\n\nexport const auth = firebase.auth();\nexport const firestore = firebase.firestore();\n\nconst provider = new firebase.auth.GoogleAuthProvider();\nprovider.setCustomParameters({ prompt: 'select_account' });\nexport const signInWithGoogle = () => auth.signInWithPopup(provider);\n\nexport default firebase;\n</code></pre>\n<p>Here we are only importing what we need then the second imports are attached to the firebase keyword. After we initialize our app there's some setup code that is in the documentation. We export auth() and firestore().</p>\n<p>Then the rest of the code is to setup Google Login. The <code>prompt: 'select_account'</code> is the popup that will show up and then we can Login users.</p>\n<p>Note: You might be worried to expose your key publicly. But it is generally save to expose Firebase apiKey. Read more <a href=\"https://twitter.com/search?q=firebase%20api%20key%20gitguardian&#x26;src=typd\">here</a>.</p>\n<p><strong>Allow Google Sign in on Firebase</strong></p>\n<ol>\n<li>Click on Authentication then on 'Set up sign in method' and select Google.</li>\n<li>Click on edit icon, enable it, add project support email.</li>\n<li>Click Save.</li>\n</ol>\n<p><strong>Adding Google Sign in to your Login Component</strong></p>\n<ul>\n<li>Import as <code>import { signInWithGoogle } from '../../firebase/firebase.utils'</code> in your Login/Sign in Component. </li>\n<li>Add another button and do the onClick to take the imported function. My button looks like this.</li>\n</ul>\n<pre><code class=\"language-js\">&#x3C;button type=\"submit\" onClick={signInWithGoogle} isGoogleSignIn>Login with Google&#x3C;/button>\n</code></pre>\n<ul>\n<li>Go ahead and test your app and make sure the pop up works and don't get weird errors on console.</li>\n</ul>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83354981-079a7500-a322-11ea-982f-eb6db4d2dadb.png\" alt=\"Screen Shot 2020-05-31 at 9 34 59 AM\"></p>\n<ul>\n<li>Go back to Firebase and click on Authentication there you'll see the user that just signed in!</li>\n</ul>\n<h2>Using Firebase Auth Data on Your React App</h2>\n<p>In order to add Firebase data into our application we do the following.</p>\n<ul>\n<li>Import into our <code>App.js</code> our firebase utils file. As <code>import { auth } from './firebase/firebase.utils'</code>.</li>\n<li>First lets add <code>currentUser</code> to state and add a componentDidMount() function that will call our imported auth as this.</li>\n</ul>\n<pre><code class=\"language-js\">this.state = {\n  currentUser: null,\n}\n\ncomponentDidMount() {\nauth.onAuthStateChanged(user => {\n  this.setState({ currentUser: user })\n})\n}\n</code></pre>\n<ul>\n<li>Note that the <code>onAuthStateChanged()</code> connection is always open as long as App.js is mounted so you don't have to re-call it again.</li>\n<li>One of the key things of Firebase is that it has user auth persistance. So if you do a console.log on 'user' you'll see that your previous user persisted on your React app. So we don't need to have the user re-sign when the page refreshes. Even on Dev mode. </li>\n<li>Because <code>onAuthStateChanged</code> we need to unsuscribe so we modify our code as:</li>\n</ul>\n<pre><code class=\"language-js\">unsubscribeFromAuth = null\n\ncomponentDidMount() {\n  this.unsubscribeFromAuth = auth.onAuthStateChanged\n  (user => {\n    this.setState({ currentUser: user })\n  })\n}\n\ncomponentWillMount() {\n  this.unsubscribeFromAuth()\n}\n</code></pre>\n<ul>\n<li>Now we'll pass out the state of our users to the components that need it. </li>\n</ul>\n<p><strong>Logout Users</strong></p>\n<p>This depends on your component implementation but usually implemented on a Header or Nav component pass out the user state.</p>\n<p>First you import the auth library as you did in App.js. Then pass the 'user' props to your Nav/Header component. Then you might want to render another header item that will conditionally render either Login or Logout and if clicked you'll pass the <code>signOut()</code> function from our auth that we imported to firebase. This is how I did it on Studio Ghibli's app:</p>\n<pre><code class=\"language-js\">// props.currentUser was passed from App.js. Link is a react-router-dom element.\n\n{\n props.currentUser ? \n &#x3C;div className=\"option\" onClick={() => \n auth.signOut()}>LOGOUT&#x3C;/div> \n : \n &#x3C;Link className=\"option\" \n  to=\"/signin\">LOGIN&#x3C;/Link>\n}\n</code></pre>\n<h2>Implementing Firebase Firestore to Save and Get User Data</h2>\n<p>Firestore is a <em>noSQL</em> database, kind of pretty much a database made up of a big JSON object. With that in mind let's create our database</p>\n<p>On Firebase console, click on Database then create database. You'll have two options to start in production (locked) or test mode. Select <code>test-mode</code>, you'll wanna write some access rules as you go. Now you can follow up the prompts and click Done.</p>\n<p><strong>Types of Firestore Data</strong></p>\n<p>In your new db you can have two types of data. One of them is called 'collection' and you can add a collection if you access your new db, lets name our collection 'users'.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83357924-38d07080-a335-11ea-82b4-1a84bfbb893b.png\" alt=\"Screen Shot 2020-05-31 at 11 52 25 AM\"></p>\n<p>You saw a new path was created named '/users'. Here we can add a new 'document' or new user with its own ID. You can play with it to see how to add items. </p>\n<p>You can also nest collections so a collection can have its own collection as objects such as. Here we have an example of a cart-items collection on an user having two documents (or items):</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83357976-99f84400-a335-11ea-81e2-0cfc116632ec.png\" alt=\"Screen Shot 2020-05-31 at 11 55 08 AM\"></p>\n<p>So in firebase we can have either <em>documents</em> or <em>collections</em> types of data. Now in a nutshell you can access such documents in React like this:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83358048-49351b00-a336-11ea-8f85-5aa0620c1c48.png\" alt=\"Screen Shot 2020-05-31 at 11 59 41 AM\"></p>\n<p><strong>Storing to our database - First Steps</strong></p>\n<p>The following function will take that user we get from Authentication and then store the information we need in our database. To do so we'll head to the <code>firebase.utils.js</code> and <code>App.js</code>.</p>\n<pre><code class=\"language-js\">// firebase.utils.js\nexport const createUser = async (userAuth, addData) => {\n  if (!userAuth) return;\n\n  const userRef = firestore.doc(`users/${userAuth.uid}`);\n\n  const snapShot = await userRef.get();\n\n  if (!snapShot.exists) {\n    const { displayName, email } = userAuth;\n    const createdAt = new Date();\n    try {\n      await userRef.set({\n        displayName,\n        email,\n        createdAt,\n        ...addData\n      });\n    } catch (error) {\n      console.log('error creating user', \n      error.message);\n    }\n  }\n\n  return userRef;\n};\n</code></pre>\n<pre><code class=\"language-js\">//App.js\n\ncomponentDidMount() {\nthis.unsubscribeFromAuth = auth.onAuthStateChanged(\n  async user => {\n  createUser(user)\n})\n}\n</code></pre>\n<p>In this function which is an async request, we query first if it exists. Continue reading to learn more about what this functions does. Do not test the app, just yet.</p>\n<p><em>QueryReference vs QuerySnapshot</em>\nQuery is a request to Firestore to get something from the db. Firestore returns either references or snapshots. Of these objects it can be either a Document or Collection. Firestore will always give us the object. Using the object we can determine or not if there's any data.</p>\n<p><em>QueryReference</em> is that object that represents the current place in the db we are querying. This one doesn't have the actual data. Just properties that tell us details about it and the method to get the <em>QuerySnapshot</em> with the actual data. We could call them as:</p>\n<p><code>frestore.doc('/users/userId')</code>\n<code>frestore.collections('/users')</code></p>\n<p>Regarding QueryReference, there are <em>DocumentReference</em> vs <em>CollectionReference</em>. There are some differences as follows:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83358405-dd07e680-a338-11ea-95a7-3dc6e399594d.png\" alt=\"Screen Shot 2020-05-31 at 12 18 31 PM\"></p>\n<p>If you console.log the snapShot you get something like this:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83358454-50a9f380-a339-11ea-9070-29740f351a90.png\" alt=\"Screen Shot 2020-05-31 at 12 21 45 PM\"></p>\n<p>Here the 'exists' property tells if there's any data. Here in our code we are checking if the user already exists. If snapShot doesn't exists then we use CRUD on documentRef (not snapShot ). We get the data we need (in this case displayName and email) and make the request to the firebase to create with the Firebase method of <code>.set()</code></p>\n<p>The function above will always return the userRef if we need to use that userRef object. So now head to your Firebase console and login and check on your Database to see if the user is created. Refresh the user persisted and still one user. Great right!</p>\n<p><strong>Storing User Data in our App</strong></p>\n<p>Did you notice your app Login button is not being changed to Logout. This is because we are not setting state. We need to modify our App.js to use that userRef object.  We need use the <code>onSnapshot()</code> method we get from this object to get a <em>DocumentSnapshot</em>. </p>\n<p>A documentSnapshot allows us to check if a document exists using the <code>.exists</code> property which returns a boolean and we can actually get the actual data using the <code>data()</code> method which returns a JSON of the document. If you do on the code a console.log of snapShot.data() inside onSnapshot() call you can see the same data you saw on the Firebase console. The id we just get by snapShot.id</p>\n<pre><code class=\"language-js\">  componentDidMount() {\n    this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {\n      if (userAuth) {\n        const userRef = await createUser(userAuth);\n\n        userRef.onSnapshot(snapShot => {\n          this.setState({\n            currentUser: {\n              id: snapShot.id,\n              ...snapShot.data()\n            }\n          });\n        });\n      }\n    // if userAuth is null do this:\n      this.setState({ currentUser: userAuth });\n    });\n  }\n</code></pre>\n<p>Now try again and see if all is back to normal! </p>\n<p><strong>Moving other data into Firebase Firestore</strong></p>\n<p>Studio Ghibli's fan app has shop data related to the films and products it offers. In the beginning this data was stored as a separate js and in an object data type. Now what if this data grows? What if we have 10 million shop items? Here is where an object might not be the right choice. </p>\n<p>So how do we move this shop collection data into Firebase? Remember when we make query requests we either get both of these two objects (even if nothing exists in the response):</p>\n<ul>\n<li><em>QueryReference</em>: It represents the current place in the database we are querying. It doesn't have the actual data.</li>\n<li>\n<p><em>Snapshot Object</em>: Also either as document type or collection type. Note a collection snapshot object is called specifically a \"QuerySnapshot\". </p>\n<ul>\n<li>DocumentReference we can use CRUD methods.  Remember we can check if the snapshot document object exists in db with the <code>.exists</code> property. If you need the data you call <code>.data()</code> on object.</li>\n<li>QuerySnapshot. With the collectionRef we can add documents to collections. The important methods here are <code>docs()</code>, <code>empty()</code> and <code>size</code>.</li>\n</ul>\n</li>\n</ul>\n<p><strong>Populating Our Firebase With Additional Data</strong></p>\n<p>We need to get back to our Firestore console and add another collection. Before we do that lets take at how our shop.data basic structure looks:</p>\n<pre><code class=\"language-js\">// shop.data.js\n\nexport const SHOP_DATA =  {\nmemorabilia: {\nid: 1,\ntitle: 'Memorabilia',\nrouteName: 'memorabilia',\nitems: [\n  {\n    id: 1,\n    name: 'Calcifer Toy (Handsewn)',\n    imageUrl: 'imageUrlHere',\n    price: 10\n  },\n  ]\n},\n\nfilms: {\n  id: 2,\n  title: 'Selected Films',\n  routeName: 'films',\n  items: [\n    {\n    id: 10,\n    name: 'Nausicaä of the Valley of the Wind',\n    imageUrl: 'imageUrlHere',\n    price: 25,\n    description: \"Warrior and pacifist Princess Nausicaä\",\n    director: \"Hayao Miyazaki\",\n    producer: \"Hayao Miyazaki\",\n    release_date: \"1984\",\n    },  \n  ]\n}\n}\n</code></pre>\n<p>As you check your Firebase is almost the same, it has keys that point to names that hold values. This is because Firebase is NoSQL so it can have as many properties as possible (properties can be different among documents of same collections) as it is not stored as tables like SQL.</p>\n<p>Firestore supports many types of data. So we need to think about what data we will store as. With that in mind, lets export our <code>shop.data.js</code> by adding this on our Firebase <code>firebase.utils.js</code> file.</p>\n<pre><code class=\"language-js\">// firebase.utils.js\nexport const addCollectionAndDocuments = \n  async (collectionKey, objectsToAdd) => {\n  const collectionRef = firestore.collection(collectionKey)\n\n  const batch = firestore.batch()\n  objectsToAdd.forEach(obj => {\n    const newDocRef = collectionRef.doc()\n    batch.set(newDocRef, obj)\n  })\n\n  return await batch.commit()\n}\n</code></pre>\n<p>Here we can see it implements a batch write that if any document fails then everything fails so ensure all collection is saved. Now that this is setup, then we can modify our <code>App.js</code>, please refer to <a href=\"https://github.com/fbohz/studio-ghibli-fan-app-demo/commit/f16ab99ffb42448ed44352c0424c9c7c7988914e\">source code</a> to see what we added.</p>\n<p>Now that we have dynamically populated our db. We need to <em>remove the code we wrote on the App.js</em> because this only runs once so we did it to avoid the manual write of it! We'll keep the firebase.utils <code>addCollectionAndDocuments</code> code for future reference if we need it.</p>\n<p>Now in order to access our Firebase shop data in the frontend, there are a couple roads we could take. We need to access the most up level component and create and subscribe to listen to firebase changes then unsubscribe when component unmount. While I won't go into a lot of detail, feel free to take a look at the <a href=\"https://github.com/fbohz/studio-ghibli-fan-app-demo\">repo</a> to see how I implemented on the app.</p>\n<p>Now that we moved this data out of the frontend it can be shared along other implementations such as React Native and there's a single source of truth with Firebase.</p>\n<h2>Final Thoughts</h2>\n<p>Firebase is a pretty robust platform that can take a while to learn. But the more you practice the better you become. The concepts covered are the core of Firebase so once you have them settled you'll know how to use it. Learning Firebase is important because at the end is easier than spinning up our own backend, database and authentication.</p>\n<p>Also you saw there are some Firebase commands, as a React Developer, you do not need to memorize these things and most of the time you can always refer to the <a href=\"https://firebase.google.com/docs/firestore/quickstart\">documentation</a>.</p>"},{"url":"/posts/2020-06-22-graph_ql_debrief/","relativePath":"posts/2020-06-22-graph_ql_debrief.markdown","relativeDir":"posts","base":"2020-06-22-graph_ql_debrief.markdown","name":"2020-06-22-graph_ql_debrief","frontmatter":{"title":"GraphQL + Apollo - Flash Debrief","template":"post","date":"2020-06-22 19:31:03 -0400","permalink":"graph_ql_debrief","filename":"2020-06-22-graph_ql_debrief"},"html":"<blockquote>\n<p>What is GraphQL? It is a query language that wraps around an existing database to make requests to APIs differently. I implemented GraphQL on the latest iteration of the <a href=\"https://yijingballz.herokuapp.com/\">Yijing-Ball-Z</a> app. </p>\n</blockquote>\n<h1>GraphQL + Apollo - Flash Debrief</h1>\n<p>What is GraphQL? It is a query language that wraps around an existing database to make requests to APIs differently. I implemented GraphQL on the latest iteration of the <a href=\"https://yijingballz.herokuapp.com/\">Yijing-Ball-Z</a> app. </p>\n<p>Look at the traditional backend diagram:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84446658-9c974b00-ac0b-11ea-904c-4d98969eee84.png\" alt=\"Screen Shot 2020-06-11 at 5 46 58 PM\"></p>\n<p>We make requests to specific endpoints to get some data. Above you can see the REST paradigm, with either POST, GET, PUT etc requests. With deeply nested endpoints e.g. users/userId/posts we could make at least multiple requests just to get user posts.</p>\n<p>Now GraphQL tries to solve this differently from REST APIs. So first we need to make our server into a <em>GraphQL backend server</em>.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84519685-0fe69e80-ac98-11ea-9a30-6c084793c264.png\" alt=\"Screen Shot 2020-06-12 at 10 32 21 AM\"></p>\n<p>So you can see first that there's only one endpoint exposed instead of multiple endpoints. Then from here we make all requests to either a <em>query</em> (ask/read data) or <em>mutation</em> (create/update/delete data). These requests look pretty much like JSON objects. So we don't need multiple endpoints to just access data.</p>\n<p><strong>Playing with GraphQL</strong></p>\n<p>Take a look at the <a href=\"https://crwn-clothing.com/\">GraphQL Playground</a>. Here we can start playing with GraphQL queries for a sample project. Please refer to GraphQL <a href=\"https://graphql.org/graphql-js/basic-types/\">documentation</a> for queries help. You can implement this playground when you build your own GraphQL server. </p>\n<p>Here's an example of a query you can do on this playground:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84521206-4a513b00-ac9a-11ea-9b49-a1a2f0fb0b02.png\" alt=\"Screen Shot 2020-06-12 at 10 48 35 AM\"></p>\n<p>Inside our query we can only make certain requests as defined on the db as things we can take. If you look at the schema you can see what is available. We can define our schema in many ways for example a Person schema:</p>\n<pre><code class=\"language-js\">type Person {\n  id: ID!\n  name: String!\n  age: Int!\n}\n</code></pre>\n<p>The exclamation mark means mandatory. Items is an array, then inside items there's an item. Then if you click on docs you can see the type of queries you can make. </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84521635-ee3ae680-ac9a-11ea-8324-d1b7662fd4b9.png\" alt=\"Screen Shot 2020-06-12 at 10 52 55 AM\"></p>\n<p>If we pass then ID of collection we can get a collection, we can also get a collection by a title. So whatever we see we have access it means it was built by the backend server and made available to us. Here's an example of a query we can make:</p>\n<pre><code class=\"language-js\">query {\n  collections {\n    id\n    title\n  }\n}\n</code></pre>\n<p>If you click run with this query then you get an object containing all the collections. You can also pass in items to get the items as specified on the schema. As this:</p>\n<pre><code class=\"language-js\">query {\n  collections {\n    id\n    title\n    items {\n      id\n      name\n      price\n    }\n  }\n}\n</code></pre>\n<p>Now what if you wanted to query by ID:</p>\n<pre><code class=\"language-js\">query {\n  collection(id: \"cjwuuj5bz000i0719rrtw5gqk\") {\n    title\n  }\n}\n</code></pre>\n<p>For mutations we'll start with the <code>mutation</code> keyword. Back to our Person example consider this:</p>\n<pre><code class=\"language-js\">mutation {\n  createPerson(name: \"Bob\", age: 36) {\n    name\n    age\n  }\n}\n</code></pre>\n<p>Now in your schema you might define it as such:</p>\n<pre><code class=\"language-js\">type Mutation {\n  createPerson(name: String!, age: Int!): Person!\n}\n</code></pre>\n<p>Pretty easy right?</p>\n<p><em>Note</em>: as React developers, we will usually only concern ourselves with the frontend implementation of GraphQL. If you're curious as to how to  build a GraphQL server, below are some resources, as well as a list of some popular options out there for building such a server:</p>\n<ul>\n<li>Backend Implementation <a href=\"https://github.com/ZhangMYihua/crwn-clothing-prisma\">Example</a>. Uses <a href=\"https://www.prisma.io/\">Prisma</a></li>\n<li><a href=\"https://hasura.io/\">Hasura</a></li>\n<li><a href=\"https://www.apollographql.com/docs/apollo-server/\">Apollo Server</a></li>\n<li>Quick way to build a GraphQL server: <a href=\"https://github.com/prisma/graphql-yoga\">graphql-yoga</a></li>\n<li>A quick <a href=\"https://blog.apollographql.com/tutorial-building-a-graphql-server-cddaa023c035\">step by step guide</a> on how to set up your own GraphQL server</li>\n<li>Here's my backend <a href=\"https://github.com/fbohz/yijing-ball-z_backend\"><strong>Rails API + GraphQL Implementation</strong></a>.</li>\n</ul>\n<p><strong>Introduction to Apollo</strong></p>\n<p>Ensure you install it as well as GraphQL:</p>\n<p><code>yarn add apollo-boost react-apollo graphql</code></p>\n<p>Apollo client lets us use the GraphQL API toolkit. Apollo also caches the data so we don't double request it.</p>\n<p>Take a look at the <code>index.js</code> on the following <a href=\"https://github.com/fbohz/graphql-practice-example\">GraphQL example repository</a>. We could test making a query using <code>gql</code> function as this:</p>\n<pre><code class=\"language-html\">client.query({\n  query: gql`\n  {\n    getCollectionsByTitle(title: \"hats\") \n    {\n    id\n    title\n    items {\n      id\n      name\n    }\n   }\n  }\n  `\n}).then(res => console.log(res))\n</code></pre>\n<p>Note how here the <code>client.query</code> returns a promise.</p>\n<p><strong>Apollo Container</strong></p>\n<p>On the example repo take a look at the Collections-Ov-GraphQL component. This container does the fetching and includes loading attribute we can use. You might see how Apollo extrapolates a lot of the verbose promise code, resolving etc. So it feels like synchronous even though we're fetching the database.</p>\n<p><strong>GraphQL vs Redux</strong></p>\n<p>There are benefits in both. Redux has very fleshed out architecture. You can actually use <em>both</em> in the same app, however you might actually be having to handle two pieces of state management. So usually Apollo replaces Redux but this is up to you, but if you keep both then it could affect the single source of truth concept.</p>\n<p>Here's how Redux works:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84534360-627f8500-acaf-11ea-9eb6-f5afb178394a.png\" alt=\"Screen Shot 2020-06-12 at 1 19 23 PM\"></p>\n<p>Here's how Apollo works:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84534678-fa7d6e80-acaf-11ea-8c80-663aca370fff.png\" alt=\"Screen Shot 2020-06-12 at 1 23 38 PM\"></p>\n<p><em>Local cache</em> replaces our reducer. We access/modify our data through a query or mutation. These resolver functions can get or modify data and they can get it from local cache as internal state. </p>\n<p><strong>Mutations on the Client (Frontend)</strong></p>\n<p>Mutations are a bit different and you can check the example Repo and specifically the <a href=\"https://github.com/fbohz/graphql-practice-example/tree/master/src/graphql\">graphql folder</a>. Basically you create a resolvers.js file that handles the mutations inside a graphql folder in src.</p>\n<p><code>extend</code> keyword in GraphQL behaves a little bit different than JS, read more <a href=\"https://www.apollographql.com/docs/react/development-testing/client-schema-mocking/#1-extend-your-server-schema-with-a-client-only-field\">here</a>. Another key concept are resolvers methods, the <a href=\"https://www.apollographql.com/docs/react/data/local-state/#local-resolvers\">GraphQL documentation</a> can explain them in detail. Here the cache object you can <a href=\"https://www.apollographql.com/docs/react/caching/cache-configuration/\">read more</a> about it.</p>\n<p>Notice also how we import and pass to our client in index.js the resolvers and typeDefs defined on resolver.js. Here for example the <code>toggleCartHidden</code> mutation is used on header-container that is in charge of dealing with the graphql querying using the Query element and then renders the header-component. </p>\n<p>You might also notice in resolvers.js the <code>@client</code> this tells Apollo to look on the local cache not the server. Finally on the cart-icon container you might see that it uses <code>compose</code> and <code>graphql</code> functions, that look kind of like Redux, you can access the <a href=\"https://www.apollographql.com/docs/react/api/react-apollo/#graphqlquery-configcomponent\">documentation</a> to see how to implement in detail.</p>\n<p>Mutations can be a complex topic, so read on the resources and make your own tests. Complete Apollo documentation in the link <a href=\"https://www.apollographql.com/docs/react/essentials/mutations/\">here</a>. However do have in mind that if you would like to implement it consider having a container that deals with the graphql logic then the actual presentational component so the latter can be reused as it is not solely related to graphql.</p>\n<p><strong>What's Next</strong></p>\n<ul>\n<li>Build your own <em>GraphQL server</em> from scratch <a href=\"https://www.howtographql.com/choose/\"><strong>here</strong></a>. </li>\n<li>Checkout my GraphQL implementation using Vanilla JS + Rails API (<a href=\"https://github.com/fbohz/yijing-ball-z_frontend\"><strong>frontend</strong></a>/<a href=\"https://github.com/fbohz/yijing-ball-z_backend\"><strong>backend</strong></a>).</li>\n</ul>\n<p><strong>Conclusion: Should You Use GraphQL?</strong></p>\n<p>GraphQL can be very challenging since there's so much to learn at the beginning. I tried to touch on some interesting concepts, with demo projects both in React and Vanilla JS. The rest is for you to keep digging and motivate yourself to start implementing it in your own project.</p>\n<p>Do note that the issues with REST that GraphQL tries to solve, are important propositions. The problem with implementations such as Apollo is that it needs both backend and frontend adoption. Setting up backend with can be hard so taking this risk might be difficult. Also this tech is new, not like Redux which there are so many resources out there. Apollo client and GraphQL are relatively new and the paradigm might change. So for now learning GraphQL is great, but do keep your strong skills on Redux, since on scaling it performs really well, and has been industry tested. </p>"},{"url":"/posts/2020-07-20-stripe_api_implementation/","relativePath":"posts/2020-07-20-stripe_api_implementation.markdown","relativeDir":"posts","base":"2020-07-20-stripe_api_implementation.markdown","name":"2020-07-20-stripe_api_implementation","frontmatter":{"title":"Implementing Stripe API in React","template":"post","date":"2020-07-20 19:31:03 -0400","permalink":"stripe_api_implementation","filename":"2020-07-20-stripe_api_implementation"},"html":"<blockquote>\n<p>Handling payments is very complex, not talking the security risks one can take if handling payment information. Stripe API, make things easier, secure and faster to deploy</p>\n</blockquote>\n<h1>Implementing Stripe API in React</h1>\n<p>In my latest React project, <a href=\"https://studio-ghibli-fanhub.herokuapp.com/\">Studio Ghibli's Fan Hub</a> I implemented Stripe API to test and handle payments on the Shop component of the app. </p>\n<p>Handling payments is very complex, not talking the security risks one can take if handling payment information. Stripe API, make things easier, secure and faster to deploy.</p>\n<p><strong>Intro to Stripe</strong></p>\n<p>Stripe is well known in the payments sphere. You can read the <a href=\"https://stripe.com/docs\">docs</a> to learn more how easy it can be implemented. But basically Stripe renders itself the handling of payments and you implement some configuration to get the payment information and handle it backend. For this post we will focus on the frontend with React.</p>\n<p><strong>Setting Up Stripe</strong></p>\n<p>Again we will implement the <em>frontend of Stripe</em>. We might implement the backend handling of the data received in a future blog.</p>\n<p>First things first lets <a href=\"https://dashboard.stripe.com/register\">sign up for Stripe account</a>.</p>\n<p><strong>Integrating Stripe</strong></p>\n<p>Lets add it to our package.json</p>\n<p><code>yarn add react-stripe-checkout</code></p>\n<p>With this installed we can now add our Stripe element to render it frontend. Lets begin by creating a boilerplate element such as this one.</p>\n<pre><code class=\"language-js\">import React from \"react\";\nimport StripeCheckout from 'react-stripe-checkout'\n\nconst StripeBtn = ({ price }) => {\n    const priceForStripe = price * 100\n    const publishableKey = \"your_key\"\n    \n    const onToken = token => {\n        console.log(token)\n        alert('Payment Successful')\n    }\n\nreturn (\n&#x3C;StripeCheckout\n    label=\"Pay Now\"\n    name=\"Studio Ghibli's Fan Hub (Demo Purposes)\"\n    billingAddress\n    shippingAddress\n    image=\"https://svgshare.com/i/Lko.svg\"\n    description={`Your (demo) total is ${price}`}\n    amount={priceForStripe}\n    panelLabel=\"Pay Now\"\n    token={onToken}\n    stripeKey={publishableKey}\n>\n\n&#x3C;/StripeCheckout>\n)\n}\n\nexport default StripeBtn\n</code></pre>\n<p>Not here it is worth mentioning that stripe handles values as cents, that is why we create the const. The <code>publishableKey</code> is your own API key. To get the key, just access your new account and click on developer tab then API keys. </p>\n<p><img src=\"https://i.udemycdn.com/redactor/raw/2019-07-01_06-21-56-2d4f24984f3ec9b4c75abae102479511.png\" alt=\"img\"></p>\n<p>Now, the imported <code>stripeCheckout</code> has a bunch of features and you can read more <a href=\"https://github.com/azmenak/react-stripe-checkout\">here</a>.</p>\n<p><code>token</code> is where you process your payment on your backend. For now we will just log it to the console and have the fake alert.</p>\n<p>With this you can go ahead and test adding this button to your appropriate component and see the button has been added accordingly. Here's how it shows on mine:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83676511-6b31d600-a5a0-11ea-80d7-66ec5295fa64.png\" alt=\"Screen Shot 2020-06-03 at 1 42 14 PM\"></p>\n<p><em>You might see some console errors they are usual Stripe's end and had to do with style them, if it doesn't affect functionality ignore them for now.</em></p>\n<p>Go ahead and test by using any of the test credit cards found a <a href=\"https://stripe.com/docs/testing\">Stripe's docs</a>. Everything should test correctly. And done you have implemented Stripe! Here's the token object format.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83676736-c49a0500-a5a0-11ea-9a90-f9606edff021.png\" alt=\"Screen Shot 2020-06-03 at 1 46 45 PM\"></p>\n<p>Now although these are just the first steps. You can continue building and show how as a React developer you can implement Stripe!</p>"},{"url":"/posts/2020-07-07-going_beyond_usestate_react/","relativePath":"posts/2020-07-07-going_beyond_usestate_react.markdown","relativeDir":"posts","base":"2020-07-07-going_beyond_usestate_react.markdown","name":"2020-07-07-going_beyond_usestate_react","frontmatter":{"title":"React Hooks: Going Beyond useState","template":"post","date":"2020-07-07 19:31:03 -0400","permalink":"going_beyond_usestate_react","filename":"2020-07-07-going_beyond_usestate_react"},"html":"<blockquote>\n<p>Hooks are fairly new, and there's still a lot of hype around them. However, a lot of companies have built scalable apps without hooks. So for some companies, it'll take time to migrate to Hooks.</p>\n</blockquote>\n<h1>React Hooks: Going Beyond <code>useState</code></h1>\n<p>Hooks were implemented in 2019. They have very interesting features and bring some changes to building components. Hooks can only be used in React 16 or higher and on functional components. Read about the motivation to add React Hooks <a href=\"https://reactjs.org/docs/hooks-intro.html#motivation\">here</a>.</p>\n<p>Now probably by know, everyone with some React knowledge should know about the <code>useState</code> Hook. It lets us use state in functional components. You can use as many as use state hooks as needed. This is an alternative to setting state with deeply nested objects. On this article we'll go beyond useState and explore other hooks.</p>\n<p><strong>useEffect</strong></p>\n<p><code>useEffect</code> lets us employ lifecycle kind of methods to functional components. This has to do with dealing with side-effects including API calls. </p>\n<pre><code class=\"language-js\">// mimics as a render lifecycle method\n\nuseEffect(() => {\n    console.log('hello')\n})\n\n// ...assume this code on an input\nonChange={e => setQuery(e.target.value)}\n\n// useEffect gets called whenever onChange changes value\n</code></pre>\n<p>useEffect does not get a value, but gets a function that gets called whenever the component changes/updates and re-renders. It works as componentDidMount and also as the render method when the component gets updated.</p>\n<p>If we want to use useEffect as componentDidMount we add an array as second argument.</p>\n<pre><code class=\"language-js\">useEffect(() => {\n    console.log('hello')\n},[])\n</code></pre>\n<p>The array takes an array of properties we want to watch and it will render if those properties change. If the array is empty is like componentDidMount. Now how could we implement an API call using useEffect?</p>\n<pre><code class=\"language-js\">useEffect(() => {\n    if (query.length > 0) {\n        const fetchUser = async () => {\n            const res = await fetch('baseURL')\n            const resJson = await res.json()\n            //useState call\n            setUser(resJson)\n        }\n    \n        fetchUser()\n    }\n},[query])\n</code></pre>\n<p>Make sure you add the <em>empty array</em>, or with special properties if you plan it to run it once. In this case it will update if the search query updates on the example above. The conditional then ensures we are calling useEffect if queries are valid. You can read more about <a href=\"https://reactjs.org/docs/hooks-rules.html\">Hook rules</a>.</p>\n<p><em>Note</em>: You might get a warning when using useEffect that says something like 'React Hook useEffect has a missing dependency...etc'. To add a safeguard if calling an API pass in the api in the array list as such:</p>\n<pre><code class=\"language-js\">    // behaves like componentDidMount avoids missing dependency warning\n    useEffect(() => {\n      checkUserSession()\n    }, [checkUserSession])\n</code></pre>\n<p><strong>useEffect as componentWillUnmount</strong></p>\n<p>We can also pass a cleanup function, so return a function from a function. This is useful when implementing subscriptions, so on the cleanup function it will be for unsubscribing.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84339775-cb0e1b00-ab64-11ea-8100-21328333460d.png\" alt=\"Screen Shot 2020-06-10 at 9 52 11 PM\"></p>\n<p><strong>useEffect Boilerplate Code</strong></p>\n<pre><code class=\"language-js\">//ComponentDidMount\n//Class\ncomponentDidMount() {\n    console.log('I just mounted!');\n}\n \n//Hooks\nuseEffect(() => {\n    console.log('I just mounted!');\n}, [])\n\n\n//ComponentWillUnmount\n//Class\ncomponentWillUnmount() {\n    console.log('I am unmounting');\n}\n \n//Hooks\nuseEffect(() => {\n    return () => console.log('I am unmounting');\n}, [])\n\n\n// ComponentWillReceiveProps\n//Class\ncomponentWillReceiveProps(nextProps) {\n    if (nextProps.count !== this.props.count) {\n        console.log('count changed', nextProps.count);\n    }\n}\n \n//Hooks\nuseEffect(() => {\n    console.log('count changed', props.count);\n}, [props.count])\n</code></pre>\n<p><strong>Reusable Custom Hooks</strong></p>\n<p>Sometimes you might have similar situations in which you're using the same hooks, with very small differences.  Lets say you're fetching with useEffect then setting state depending on the return of the fetch. Here's where reusable Hook components work. </p>\n<p>Here's how we can implement custom hooks:</p>\n<ol>\n<li>Create new folder called 'effects' then a file with the name of your custom hook with the 'use' keyword. E.g. 'useFetch'.</li>\n<li>Create your custom hook. E.g.</li>\n</ol>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84421224-db63db80-abe0-11ea-9fe5-fe6addc1779f.png\" alt=\"Screen Shot 2020-06-11 at 12 26 38 PM\"></p>\n<ol start=\"3\">\n<li>Import it and use it</li>\n</ol>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/84421372-16fea580-abe1-11ea-9bb1-9cbc68fb35b7.png\" alt=\"Screen Shot 2020-06-11 at 12 42 25 PM\"></p>\n<p>It is like writing utility functions. Then you can make those custom hooks to share functionality. </p>\n<p>Note also the example there's no second argument with the <code>[]</code> passed so it gets called whenever the <code>useFetch</code> custom hook gets called. We could also pass the 'url' as the second argument. Since our user might change and there are no dependencies here we don't pass the second argument in this use case. So in this case the component that use it, will fire the useFetch whenever it re-renders. </p>\n<p><strong>useReducer</strong></p>\n<p>The useReducer hook can be similar as to what you use with Redux. useReducer is for cases where you need more complex state management than useState. You can read the documentation <a href=\"https://reactjs.org/docs/hooks-reference.html#usereducer\">here</a>. </p>\n<p>Consider the following <a href=\"https://gist.github.com/fbohz/6440ad94a264336fe6c2b00c2ce2131f\">useReducer example</a>.</p>\n<script src=\"https://gist.github.com/fbohz/6440ad94a264336fe6c2b00c2ce2131f.js\"></script>\n<p>As you can see is similar to Redux. We also destruct different values. In the useReducer, we pass the reducer and the initial state value.</p>\n<p>The initial state we created accordingly and the reducer is just like in Redux. Then you can see the action creators setUser and setQuery with types and payload, again like Redux. Now how we pull the values we destruct them from our state variable and we dispatch them with our dispatch, e.g. <code>dispatch(setUser(resJson[0]))</code>. So React seems to be moving in which we might or not want to use Redux in our case or the other. </p>\n<p><strong>Implementing Context API with <code>createContext</code> and <code>useContext</code></strong></p>\n<p>Context API was recently updated by the React team. Context API is also used by Redux but now is more powerful. Context API tries to solve props drilling, and is a way to store different states in separate components and add them as Hooks. This is done like Redux.</p>\n<p>In order to implement context Hook:</p>\n<ul>\n<li>Create the context using createContext</li>\n<li>Import the context you created and also the useContext library. Pass in the context created to useContext as your context. E.g. <code>const myContext = useContext(sampleContext)</code>.</li>\n</ul>\n<p>In Studio Ghibli Fan App we implemented this in the <a href=\"https://github.com/fbohz/studio-ghibli-fan-app-demo/blob/1.4.0.5_ContextAPI/src/pages/collection/Collection.js\">Collection page</a>. The context created can be found <a href=\"https://github.com/fbohz/studio-ghibli-fan-app-demo/tree/1.4.0.5_ContextAPI/src/contexts/collections\">here</a>.</p>\n<p><strong>Dynamically Set Values with Context API</strong></p>\n<p>Here we take advantage of Context.Provider. We implemented it on <a href=\"https://github.com/fbohz/studio-ghibli-fan-app-demo/blob/1.4.0.5_ContextAPI/src/App.js\">App.js</a> wrapping the header to pass the currentUser context. We use the <code>value</code> attribute to pass the state we need on on to the Context Consumer in this case Header. So if currentUser changes then Header, as the consumer re-renders. Take a look at how Header consumes the context created <a href=\"https://github.com/fbohz/studio-ghibli-fan-app-demo/blob/1.4.0.5_ContextAPI/src/components/Header.js\">here</a>.</p>\n<p>We can even create whole providers with Context API that we pass into our own index.js just like Redux.</p>\n<p>Here you might see a <em>caveat</em> that we have to re-leverage component state to use this created context. But it can be easier to pass state into nested components. Remember we are solving prop drilling.</p>\n<p><strong>Context API vs Redux</strong></p>\n<p>It is rare that you have an app that uses both. But you'll have to decide. Things like Redux-persist, Redux-logger still are pretty robust and difficult to implement fast with Context API. Redux is more opinionated but with Context API we loose sagas, thunk, etc. Context API might make our component less reusable as we tight the components to their specific contexts they live. Also as app grows with Context API you might be having a lot of providers in index.js while redux there's the root provider. So Redux for larger scale apps might be a better go. Context API would be good for a portfolio project or small landing page with not that much reusability. </p>\n<p><strong>Should we adopt Hooks?</strong></p>\n<p>Hooks are fairly new, and there's still a lot of hype around them. However, a lot of companies have built scalable apps without hooks. So for some companies, it'll take time to migrate to hooks. Below are some resources you can use in your learning of these exciting Hooks.</p>\n<ul>\n<li><a href=\"https://react-redux.js.org/next/api/hooks\">React Redux Hooks</a>. Look into the useSelector.</li>\n<li><a href=\"https://overreacted.io/a-complete-guide-to-useeffect/\">Complete guide of useEffect</a>.</li>\n</ul>"},{"url":"/posts/2020-06-29-styled_components_intro/","relativePath":"posts/2020-06-29-styled_components_intro.markdown","relativeDir":"posts","base":"2020-06-29-styled_components_intro.markdown","name":"2020-06-29-styled_components_intro","frontmatter":{"title":"CSS In JS? Yes! Styled Components 💅🏽","template":"post","date":"2020-06-29 09:31:03 -0400","permalink":"styled_components_intro","filename":"2020-06-29-styled_components_intro"},"html":"<blockquote>\n<p>Styled Components can be an advanced topic, and it comes with tradeoffs with pros and cons. As you move into becoming an advanced React developer know when to use this tool is efficient and when you should not add this overhead. Each project and each situation is different and you should make the right call before you jump into the latest trend. </p>\n</blockquote>\n<h1>CSS In JS? Yes! Styled Components 💅🏽</h1>\n<p>This is a hot topic. The usual way was separating your CSS files and add your styles as needed. Then import them to the appropriate component. With React we scope the CSS to the specific component that we want to style.</p>\n<p>Back then styling was very simple, nowadays with large scales app styling can get very complicated and organizing CSS as difficult. </p>\n<p>Problem can be with CSS that shares same namespace so if another developer adds their own styling to <code>.name</code> then it could cause conflicts. To overcome this different implementations such as <a href=\"http://getbem.com/\">BEM</a> have risen. However with BEM class names can become very nested with lots of mental overhead. </p>\n<p>With React we could leverage this even further by creating style constants then apply it to the specific component. E.g.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/83706504-43ad2e80-a5dd-11ea-8564-d654dc5aa643.png\" alt=\"Screen Shot 2020-06-03 at 9 00 14 PM\"></p>\n<p>With this way there are some limitation with limited functionality (not all CSS selectors are available here) but the most popular enhancement to CSS in JS right now is Styled Components (SC).</p>\n<p>To purists they believe CSS should be done in CSS but performance might be enhanced along with the readability of your app.</p>\n<p><strong>What is Styled Components?</strong></p>\n<p>SC will make our code into components, so then we can <em>encapsulate</em> our CSS to avoid the usual problems of styles leaking across components.</p>\n<p><em>Note</em>: If you're on VS Code we recommend installing the <code>vscode-styled-components</code> extension, it will highlight your syntax so you get used to and it will help you get a head start with this great library.</p>\n<p>After you <a href=\"https://styled-components.com/\">read</a> and install SC (<code>yarn add styled-components</code>) you should import it on the specific component you want to implement it. The documentation has a simple example:</p>\n<pre><code class=\"language-html\">import React from 'react'\nimport styled from 'styled-components'\n\nconst Title = styled.h1`\n  font-size: 1.5em;\n  text-align: center;\n  color: palevioletred;\n`;\n\nconst Wrapper = styled.section`\n  padding: 4em;\n  background: papayawhip;\n`;\n\nrender(\n  &#x3C;Wrapper>\n    &#x3C;Title>\n      Hello World!\n    &#x3C;/Title>\n  &#x3C;/Wrapper>\n);\n</code></pre>\n<p>Here you can see that the attribute after <code>style</code> it is just the element, so it could be an h2, div, img etc. Then we use string interpolation just like we usually do in React. However here we add our own styling. The styles we create are just elements that we can then use but with styles. These elements themselves can have additional styling, class names etc. So we use Title and Wrapper like any other React component – except they're styled!</p>\n<p>Now if you do a console.log you will see that SC gives each component their own unique class name. Because of this styles will never bleed. So you can share names with different components, and they will never be collisions. </p>\n<p>SC also supports all selectors and it will even support <code>props</code>! Learn more about it in <a href=\"https://styled-components.com/docs/basics#passed-props\">docs</a>.</p>\n<p><strong>Implementing SC in our React App</strong></p>\n<p>Now for small apps you could definitely implements SC in the components themselves. However you can also separate SC into their own JS files for better access by other developers. Here's the naming structure of folders and files.</p>\n<p>So let's say you have a Homepage component with a className of \"homepage\" you'll then create a new JS file that will hold the specific SC code. Then you will just take a look at the CSS file code and convert it as SC code as this:</p>\n<pre><code class=\"language-css\">/* old css file */\n.homepage {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n}\n</code></pre>\n<p>homepage.styles.js:</p>\n<pre><code class=\"language-html\">import styled from 'styled-components';\n\nexport const HomePageContainer = styled.div`\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n`;\n</code></pre>\n<p>And our Homepage changes:</p>\n<pre><code class=\"language-js\">//old Homepage.js\nconst HomePage = () => (\n  &#x3C;div className='homepage'>\n  &#x3C;/div>\n);\n\n\n//Homepage.js with SC\nimport { HomePageContainer } from './homepage.styles';\n\nconst HomePage = () => (\n  &#x3C;HomePageContainer>\n  &#x3C;/HomePageContainer>\n);\n</code></pre>\n<p>Quiet easy right? With more complicated components you might need to go through the documentation, but all-in-all usually is pretty straightforward. You add styles as different const and for example if you need to style an imported element such as Link from React Router you'll just do:</p>\n<pre><code class=\"language-html\">import {Link} from 'react-router-dom'\n\nexport const OptionLink = styled(Link)`\n    height: 100%;\n`\n\n&#x3C;OptionLink to=\"/shop\"> SHOP &#x3C;OptionLink/>\n</code></pre>\n<p>You saw how we use it in our component as pass the props as usual.</p>\n<p>If you need to leverage CSS to reuse and share with other styles you can write it with style components such as in this example:</p>\n<pre><code class=\"language-html\">import styled, { css } from 'styled-components';\n\nconst ReusableStyles = css`\n    display: flex;\n    cursor: pointer;\n`\n\nexport const OptionLink = styled(Link)`\n    ${ReusableStyles}\n`\n\nexport const OptionDiv = styled.div`\n    ${ReusableStyles}\n`\n</code></pre>\n<p>If you want to make even more easier you can just use the <code>as</code> keyword and it will do the same as the reusable css code above without importing the css module. With the 'as' keyword you can also include <code>{}</code> to import other components etc. </p>\n<pre><code class=\"language-js\">&#x3C;OptionLink as='div' onClick{() => handleChange()} />\n</code></pre>\n<p>With SC css you can also conditionally render CSS blocks.</p>\n<pre><code class=\"language-html\">const buttonStyles = css`\n  background-color: black;\n  color: white;\n  border: none;\n\n  &#x26;:hover {\n    background-color: white;\n    color: black;\n    border: 1px solid black;\n  }\n`;\n\nconst invertedButtonStyles = css`\n  background-color: white;\n  color: black;\n  border: 1px solid black;\n\n  &#x26;:hover {\n    background-color: black;\n    color: white;\n    border: none;\n  }\n`;\n\nconst googleSignInStyles = css`\n  background-color: #4285f4;\n  color: white;\n\n  &#x26;:hover {\n    background-color: #357ae8;\n    border: none;\n  }\n`;\n\nconst getButtonStyles = props => {\n  if (props.isGoogleSignIn) {\n    return googleSignInStyles;\n  }\n\n  return props.inverted ? \n    invertedButtonStyles : \n    buttonStyles;\n};\n</code></pre>\n<p>You might notice that you can also implement SCSS patterns with SC.</p>\n<p><strong>Styled Components Tradeoffs</strong></p>\n<p>Styled Components can be an advanced topic, and it comes with tradeoffs with pros and cons. As you move into becoming an advanced React developer know when to use this tool is efficient and when you should not add this overhead. Each project and each situation is different and you should make the right call before you jump into the latest trend. </p>"},{"url":"/posts/2020-05-11-react_pattern_apropcalypse/","relativePath":"posts/2020-05-11-react_pattern_apropcalypse.markdown","relativeDir":"posts","base":"2020-05-11-react_pattern_apropcalypse.markdown","name":"2020-05-11-react_pattern_apropcalypse","frontmatter":{"title":"A React Pattern to Avoid Apropcalypse","template":"post","date":"2020-05-11 19:31:03 -0400","permalink":"react_pattern_apropcalypse"},"html":"<blockquote>\n<p>React patterns are useful to promote code reuse while maintaining component simplicity and flexibility.</p>\n</blockquote>\n<p>Today we'll go over some React patterns I learned while participating at <a href=\"https://www.bytesized.xyz/react-2020\">Byteconf React</a>. React patterns are useful to promote code reuse while maintaining component simplicity and flexibility. This article is a bit on the <strong>advanced React</strong> side. </p>\n<h2>Typical Component Development</h2>\n<p>Lets imagine a custom component that has an accordion UI. So we'll build this <code>Accordion</code> component.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80917534-37eff300-8d25-11ea-95a5-cc4853fafd34.png\" alt=\"accordion1\"></p>\n<p>Imagine another developer wants you to allow more flexibility to your accordion so that the order of the accordion items can be customized. Here you might think passing out a <code>props</code> like <code>top</code> so if true then the accordion item becomes the first.</p>\n<p>Now, another developer wants you to have the text on the side rather than at the bottom. Then after working on it you change the CSS so it can have it on the side with <code>props</code> as <code>right</code>, then if true it moves to the right.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80917657-25c28480-8d26-11ea-804f-993e9ecc2401.png\" alt=\"accordion2\"></p>\n<p>Then things can start becoming complicated when now another use case tell you  to implement text on the left. So use cases start to pop up one after the other. Your accordion component starts having a lot of props, that can become hard to control and deal with.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80917860-34f60200-8d27-11ea-9d11-89786a2ee2cd.png\" alt=\"accordion3\"></p>\n<p>Easily you can jump into having a component with record level props (<strong>apropcalypse</strong>)!</p>\n<p>Some problems with a component with lots of props and many use cases to deal with:</p>\n<ul>\n<li>Hard to maintain</li>\n<li>Re-renders and JSX that doesn't even apply to your use case</li>\n<li>Implementation complexity - breeding ground for bugs</li>\n<li>API complexity. Harder for other people to use your project. Your documentation can become complex.</li>\n</ul>\n<p><em>So how can we support these use cases without keep adding new props?</em></p>\n<h2>Making it Simpler / Flexible</h2>\n<p>The following implementation might look a bit confusing at the beginning. Note it uses <strong>React Hooks</strong>, so you might wanna brush up on it before digging into it (you can read my <a href=\"https://medium.com/swlh/learning-about-react-hooks-a-coffee-lover-perspective-c699f699fb3d\">article</a> on Hooks).</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80918025-61f6e480-8d28-11ea-9816-3efd1896dd19.png\" alt=\"patt1\"></p>\n<p>This implementation uses the <strong>inversion of control</strong> pattern. It has a default reducer, although anyone can use their own version of the reducer. </p>\n<p>So with this, we can build our own accordion component that might look like this:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80918255-9fa83d00-8d29-11ea-8dd4-4e4c12394d71.png\" alt=\"patt2\"></p>\n<p>And then we can pass items to render the accordion in the default way like <code>&#x3C;Accordion items={accordionItems}></code></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80917534-37eff300-8d25-11ea-95a5-cc4853fafd34.png\" alt=\"accordion1\"></p>\n<p>Because component is built on top of a hook then you can modify to make things your way. E.g. lets say we want the accordion to point up now. Then with just a few lines of code differences, the change now becomes the responsibility of who is implementing the code:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/80918517-0d089d80-8d2b-11ea-9f19-bf77ce144750.png\" alt=\"patt3\"></p>\n<p><strong>What is important</strong> is that this pattern doesn't add any complexity to the logic behind the component. You can add features to it and have total control of render and no you're no longer responsible of use cases you don't want to support.</p>\n<p>As all the logic is stored in <code>useAccordion</code> custom hook, it gives flexibility and control as to how a particular user of the component wants the UI to be rendered.</p>\n<p>Remember we are <strong>inverting control</strong>, as it can receive its own custom reducer, props so it can adapt to it. This is a <strong>benefit of React Hooks</strong>.</p>\n<p>Here we are using the systems design principle of <strong>composability</strong> so that users can use this component and assemble as depending on their needs.</p>\n<p>Feel free to <a href=\"https://youtu.be/MEeZLM1XVLI?t=1884\">watch</a> the Byteconf React presentation Video. The presenter has different examples with reducers to take care of other use cases. Also check the code repo <a href=\"https://github.com/kentcdodds/simply-react\">here</a> to play with it yourself!</p>\n<p>👋🏼👋🏼🚀</p>"},{"url":"/posts/2019-08-20-begin_building_your_own_cms_in_just_minutes_code-along/","relativePath":"posts/2019-08-20-begin_building_your_own_cms_in_just_minutes_code-along.markdown","relativeDir":"posts","base":"2019-08-20-begin_building_your_own_cms_in_just_minutes_code-along.markdown","name":"2019-08-20-begin_building_your_own_cms_in_just_minutes_code-along","frontmatter":{"title":"Begin building your own CMS in just minutes! (code-along)","template":"post","date":"2019-08-20 17:58:20 -0400","permalink":"begin_building_your_own_cms_in_just_minutes_code-along"},"html":"<p>Article on <a href=\"https://medium.com/@fbohorqu/begin-building-your-own-cms-in-just-minutes-code-along-5d4eb5f2072e\">Medium</a></p>\n<blockquote class=\"embedly-card\"><h4><a href=\"https://medium.com/@fbohorqu/begin-building-your-own-cms-in-just-minutes-code-along-5d4eb5f2072e\">As I was building [LuckyTube](https://lucky-tube.herokuapp.com/), I learned how in general it can be very straight forward to build a simple CMS using Sinatra. So you too can can start creating a Content Management System (CMS) with users managing a single resource in less than an hour!</p></blockquote>\n<script async src=\"//cdn.embedly.com/widgets/platform.js\" charset=\"UTF-8\"></script>"},{"url":"/posts/2020-07-06-node_express_baby_steps/","relativePath":"posts/2020-07-06-node_express_baby_steps.markdown","relativeDir":"posts","base":"2020-07-06-node_express_baby_steps.markdown","name":"2020-07-06-node_express_baby_steps","frontmatter":{"title":"Node.js + Express - Baby Steps 🍼","template":"post","date":"2020-07-06 09:31:03 -0400","permalink":"node_express_baby_steps","filename":"2020-07-06-node_express_baby_steps"},"html":"<blockquote>\n<p>With Express we can easily build an stateless API...and follow patterns such as REST to build routes with GET, POST, PUT, you name it!</p>\n</blockquote>\n<h1>Node.js + Express - Baby Steps 🍼</h1>\n<p>Today we'll be taking some baby steps into the Node.js world 👶🏽. You can check the latest incarnation of the <a href=\"https://github.com/fbohz/ybz-backend-node-express\">Yijing Ball-Z with Node/Express</a> as you follow along.</p>\n<p>Node.js: Pros vs Cons</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/86070758-140a0e80-ba43-11ea-8d52-74dbefbf529b.png\" alt=\"Screen Shot 2020-06-29 at 7 57 33 PM\"></p>\n<p>In Node we have synchronous code, which can be called also <em>blocking code</em>. Async code is non-blocking that can run the background. So by running code in the background it seems faster and the app can do many things at the same time. Node usually has its sync vs async versions of methods e.g. readFile vs readFileSync. Unless it is top level code do not run sync methods. More on this to follow.</p>\n<p><strong>Asynchronous Nature of Node.js</strong></p>\n<p>Node is single threaded, so all users access the same single thread. If a user access the line with synchronous code it can be a problem (e.g. read very large file), with async code then multiple users can run queries at same time (e.g. login, read file, logout etc). So time-consuming data can run in background and once completed will finish the request.</p>\n<p>Example of blocking vs non-blocking code:</p>\n<pre><code class=\"language-js\">// playing with fs module - SYNCHRONOUS / BLOCKING\n\nconst t1 = fs.readFileSync(\"./large-txt\", \"utf-8\");\nconst t2 = `${t1} \\n Done ${Date.now()}`;\n\nfs.writeFileSync(\"./txt/output.txt\", t2);\n\n//  NON BLOCK - ASYNC EXAMPLE\n\nfs.readFile(\n  \"./txt/start.txt\",\n  \"utf-8\",\n  // be wary of callback hell nesting here\n  (err, data) => {\n    console.log(data);\n  }\n);\n</code></pre>\n<p>Node.js is built on callbacks. But be wary of <em>callback hell</em>, e.g.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/86073609-b927e580-ba49-11ea-98fb-810268dba659.png\" alt=\"Screen Shot 2020-06-29 at 8 46 45 PM\"></p>\n<p>Node is well known for callbacks to start nesting many levels down. We can escape this callback hell with async await or promises (I'll discuss this in a future article).</p>\n<h2>Creating a Simple Web Server</h2>\n<p>We can create a simple node server as this:</p>\n<pre><code class=\"language-js\">const http = require(\"http\");\n\nconst server = http.createServer((req, res) => {\n  res.end(\"Hellooo\");\n});\n\n// saved variable then listen port\n// localhost default is '127.0.0.1'\nserver.listen(8000, \"127.0.0.1\", () => {\n  console.log(\"listening on port 8000\");\n});\n</code></pre>\n<p>By using <code>createServer()</code> we then pass the callback function executed each time the server is requested. Then we listen on port 8000. So if you go to <a href=\"http://localhost:8000\">http://localhost:8000</a> on your browser you'll see: 'Hellooo'. Can it get more easy?</p>\n<p>Now if you console.log the <code>req</code> object you'll see a bunch of stuff, so we get access to a bunch of stuff to handle requests.</p>\n<p><strong>Routing with Pure Node.js</strong></p>\n<p>Routing can get complicated in a big app so Express is recommended but we'll talk about  it next. For now we can modify our server as this:</p>\n<pre><code class=\"language-js\">const server = http.createServer((req, res) => {\nconst pathName = req.url\n\nif (pathName === '/') {\n    res.end('Hellooo Root')\n} else if (pathName === '/product') {\n    res.end('Hellooo Product')\n} else  {\n    res.writeHead(404, {\n        'Content-type': 'text/html',\n        'my-own-header': 'hello-world'\n        });\n    res.end('&#x3C;h1>Page not found!&#x3C;/h1>');\n}}\n</code></pre>\n<p>On the 404 response we send back a header, which is a piece of info about the response sent back. <code>my-own-header</code> is like custom metadata we can see on the console then Network tab on Chrome.</p>\n<h2>Sneak-peak of Express</h2>\n<p>Express is a Node.js framework with useful abstractions. It is the most popular framework. It has some characteristics.</p>\n<ul>\n<li>Allows for easy organization into MVC structure</li>\n<li>Rapid development of Node.js by implementing some robust features including server-side rendering, middleware, complex routing, better handling of response/request cycle.</li>\n</ul>\n<p>So we can write apps so much faster, looks simpler as well.</p>\n<p><strong>Express Setup and Basic Routing</strong></p>\n<p>Note Express is fully written on Node but it abstracts away all the complexities.</p>\n<p>To start make sure you <code>npm init</code> and <code>npm i express</code>. Then create your <code>App.js</code> file that will contain your express server. Example</p>\n<pre><code class=\"language-js\">const express = require(\"express\");\nconst app = express();\n\n// routing with GET\n\napp.get(\"/\", (req, res) => {\n  res.status(200).json({\n    message: \"Hi from Express world!\",\n    app: \"Museo API\",\n  });\n});\n\nconst port = 4000;\napp.listen(port, () => {\n  console.log(`Listening on port ${port}`);\n});\n</code></pre>\n<p>Here <code>.get()</code> similar to Node, which has access to the request and response objects, but in Express there are even more methods. Now if you navigate to localhost:4000 you get \"Hello from Express World!\" as JSON and thus we have an Express API!.</p>\n<p>Another thing you can see is that Express automatically sends app headers for you. With Express we can easily build an stateless API (in which the client will ask for specific info) and follow patterns such as REST to build routes with GET, POST, PUT, you name it!</p>\n<p>Wanna checkout a quick demo of simple API implementation? Check <a href=\"https://github.com/fbohz/museo-node/blob/1.basicExpress/app.js\">this repo</a>.</p>\n<p><strong>Express Request / Response Cycle</strong></p>\n<p>When Express receives a request, it creates a request and response object. Data will be used to process the data. To do this you can use some middleware, which intercepts and does something with the data on different stages. So here middleware is between request and response. There's the saying that everything is middleware, so router, setting headers, logging, parsing body.</p>\n<p>All middleware used in Express is called <em>middleware stack</em>. The req/res objects go into these middlewares and they call the <code>next()</code> function to move to the next middleware. This is called the pipeline until it reaches the final middleware that usually uses the <code>res.send()</code> method or similar (like <code>res.json()</code>). You can define your own middlewares:</p>\n<pre><code class=\"language-js\">app.use((req, res, next) => {\n  // current time of request e.g.\n  req.requestTime = new Date().toISOString;\n  next();\n});\n</code></pre>\n<p>Now you can use <code>req.requestTime</code> in any body of any request! There are many middlewares out there you don't have to manually create them yourself. It will make your life and development much easier.</p>\n<p>So as you grow your application, you wanna separate concerns. App.js then focuses mostly on middleware declarations using <code>.use()</code>. Also there should be a server.js file that deals with just starting the server and server configurations. Checkout such file in the <a href=\"https://github.com/fbohz/ybz-backend-node-express\">YBZ repo</a>.</p>\n<p><strong>The Importance of Middlewares in Express</strong></p>\n<p>So the importance of express middlewares is that you can implement validations as middleware then it will apply every time it applies. For example here's a function that will use the <code>params</code> middleware to check for 'id' and whether it exists. This will only fire if 'id' is on the params of the request.</p>\n<pre><code class=\"language-js\">// tour controller\nexports.checkId = (req, res, next, value) => {\n  console.log(\"id is \", value);\n  if (req.params.id * 1 > tours.length)\n    return res.status(404).json({\n      status: \"fail\",\n      message: \"Invalid ID\",\n    });\n  // remember to call next() on middlewares\n  next();\n};\n\n// tour routes\nconst { checkId } = require(\"./tourController\");\n\nrouter.param(\"id\", checkId);\n</code></pre>\n<p>With this simple check we no longer have to include such validations on each route, it will hit anytime the id matches the middleware. This is the magic of Node.js enhanced by Express!</p>\n<h2>BONUS - Node Environment Variables</h2>\n<p>Node can run on development and production environments among others. You can run in a particular environment by doing for example on the terminal and starting your server as: <code>NODE_ENV=development node server.js</code>. This could be helpful if you use different db for development/production. You can also check environment variables with <code>process.env</code>.</p>\n<p>Now the easiest way to define these variables and environments is to add them to a <code>config.env</code> file. To do this use a dotenv NPM package you can install as <code>npm i dotenv</code>. After you define your variables you can use them on server.js as this:</p>\n<pre><code class=\"language-js\">// top level code server.js\nconst dotenv = require(\"dotenv\");\n// read config.env and save as env variables\ndotenv.config({ path: \"./config.env\" });\n</code></pre>\n<h2>BONUS 2 - ESLint and Prettier Cheatsheet</h2>\n<p>Install this to use ESLint and prettier with cool config to make your Node life easier.</p>\n<pre><code class=\"language-sql\">npm i eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-plugin-jsx-a11y eslint-plugin-react-hooks eslint-plugin-node eslint-plugin-import  eslint-plugin-react eslint-config-airbnb --save-dev\n</code></pre>\n<p>In the repo you can check the <code>.eslintrc.json</code> and <code>.prettierrc</code> file configurations used.</p>\n<p>So although we took some baby steps on this exploration, I think they were enough to prepare us to fly with express in no time 🧙🏾‍♂️💫.</p>\n<h2>Continue Your Journey</h2>\n<ul>\n<li><a href=\"https://nodejs.org/en/docs/\"><strong>Node Docs</strong></a>. </li>\n<li><a href=\"https://expressjs.com/\"><strong>Express Docs</strong></a>.</li>\n<li><a href=\"https://expressjs.com/en/resources/middleware.html\"><strong>Express Middleware list</strong></a>.</li>\n<li><a href=\"https://prettier.io/\"><strong>Prettier</strong></a>.</li>\n<li><a href=\"https://eslint.org/docs/rules\"><strong>ESLint</strong></a>.</li>\n<li><a href=\"https://graphql.org/graphql-js/running-an-express-graphql-server/\"><strong>GraphQL on top of express server</strong></a>.</li>\n<li><a href=\"https://medium.com/@utkarshprakash/setting-up-graphql-server-with-nodejs-express-and-mongodb-d72fba13216\"><strong>GraphQL + Express + MongoDB Tutorial</strong></a>.</li>\n</ul>"},{"url":"/posts/2020-07-13-async_await_node/","relativePath":"posts/2020-07-13-async_await_node.markdown","relativeDir":"posts","base":"2020-07-13-async_await_node.markdown","name":"2020-07-13-async_await_node","frontmatter":{"title":"Solving Callback Hell😈 - JS Promises and Async-Await in Node.js","template":"post","date":"2020-07-13 09:31:03 -0400","permalink":"async_await_node","filename":"2020-07-13-async_await_node"},"html":"<blockquote>\n<p>Async/Await was introduced recently. In order to use async/await we need to use mark functions as <code>async</code> functions. Async functions return a promise and we can use one or more await functions. </p>\n</blockquote>\n<h1>Solving Callback Hell😈 - JS Promises and Async-Await in Node.js</h1>\n<p>Last week we went through the baby steps involved in Node.js and setting up a Express server. Now we left a question unanswered, remember <em>callback hell</em> in Node.js?</p>\n<pre><code class=\"language-js\">const fs = require(\"fs\");\nconst superagent = require('superagent');\n\nfs.readFile(`${__dirname}/dog.txt`, (err,data) => {\n   superagent\n  .get(`https://dog.ceo/api/breed/${data}/images/random`)\n  .end((err, res) => {\n      if (err) return console.log(err.message)\n\n      console.log(res.body.message);\n\n      fs.writeFile('dog-img.txt', res.body.message,err => {\n          console.log(\"Dog Image Saved to File\")\n      });\n  })\n}) \n \n</code></pre>\n<p>Note superagent is a NPM package we use to use APIs such as the Dog CEO API above. </p>\n<p>But note how here we ended up with callbacks inside of callbacks. This makes code messy and difficult to understand!</p>\n<p><strong>Saving Callback Hell with Promises</strong></p>\n<p>We can implement and consume promises easily. It implements a future value we are expected to receive in the future. Above <code>.get()</code> returns a promise so we can use it. To do that we use the <code>.then()</code> method:</p>\n<pre><code class=\"language-js\">fs.readFile(`${__dirname}/dog.txt`)\n  .then(data => {\n    console.log(`Breed: ${data}`);\n    return superagent\n    .get(`https://dog.ceo/api/breed/${data}/images/random`);\n  })\n  .then(res => {\n    console.log(res.body.message);\n    fs.writeFile('dog-img.txt', res.body.message);\n  })\n  .then(() => {\n    console.log('Dog image saved to file!');\n  })\n  .catch(err => {\n    console.log(err);\n  });\n</code></pre>\n<p><code>.then</code> only handles fulfilled promises, <code>.catch</code> handles when error. Here we can see it looks much better and we're not nesting callbacks! However we still have callbacks function so we can make it event better 😏.</p>\n<pre><code class=\"language-js\">const readFilePromise = file => {\n  return new Promise((resolve, reject) => {\n    fs.readFile(file, (err, data) => {\n      if (err) reject('File not found 😢');\n      resolve(data);\n    });\n  });\n};\n\nconst writeFilePromise = (file, data) => {\n  return new Promise((resolve, reject) => {\n    fs.writeFile(file, data, err => {\n      if (err) reject('File not found 😢');\n      resolve('success');\n    });\n  });\n};\n</code></pre>\n<p>The Promise constructor takes an executer function with resolve and reject as arguments. Then here just modify the <code>fs.readFile</code>, <code>fs.writeFile</code> to be <code>readFilePromise()</code>, <code>writeFilePromise()</code> with the file name and looks much better. So with that we solve and have less callbacks inside of callbacks. </p>\n<p>Remember in order to use <code>.then()</code> we need to make sure code returns a promise!</p>\n<p><strong>Using Promises with Async / Await</strong></p>\n<p>Async/Await was introduced recently. In order to use async/await we need to use mark functions as <code>async</code> functions. Async functions return a promise and we can use one or more await functions. </p>\n<pre><code class=\"language-js\">const getDogPic = async () => {\n  try {\n    const data = await readFilePromise(`${__dirname}/dog.txt`);\n    const res = await superagent.get(\n      `https://dog.ceo/api/breed/${data}/images/random`\n    );\n    console.log(res.body.message)\n\n    await writeFilePromise('dog-img.txt', imgs.join('\\n'));\n    console.log('Random dog image saved to file!');\n\n\n  } catch (err) {\n    console.log(err);\n    throw err;\n  }\n};\n\ngetDogPic()\n</code></pre>\n<p>The await will make sure it waits for code to finish, once finished it will store it to variable. In in order to catch the error, we just wrap it in an try/catch block. So hope you can see how this looks sync even though is async code!</p>\n<p>So this is called synthetic sugar for promises, it is still the same on the back but looks better on the front 😊.</p>\n<p><strong>Bonus - <code>Promise.all</code></strong></p>\n<p>We can wait for multiple promises using <code>Promise.all</code> by passing as an array of some saved promises. Example:</p>\n<pre><code class=\"language-js\">  const res1Pro = superagent.get(\n    `https://dog.ceo/api/breed/${data}/images/random`\n  );\n  const res2Pro = superagent.get(\n    `https://dog.ceo/api/breed/${data}/images/random`\n  );\n  const res3Pro = superagent.get(\n    `https://dog.ceo/api/breed/${data}/images/random`\n  );\n  const all = await Promise.all([res1Pro, res2Pro, res3Pro]);\n  const imgs = all.map(el => el.body.message);\n  console.log(imgs);\n</code></pre>\n<h2>Further Reading</h2>\n<ul>\n<li><a href=\"https://nodejs.org/en/docs/\"><strong>Node Docs</strong></a></li>\n<li><a href=\"http://callbackhell.com/\"><strong>Callback Hell</strong></a></li>\n<li><a href=\"https://blog.risingstack.com/node-js-async-best-practices-avoiding-callback-hell-node-js-at-scale/\"><strong>Node.js Async Best Practices &#x26; Avoiding the Callback Hell</strong></a></li>\n</ul>"},{"url":"/posts/2020-07-27-html_js_games_canvas/","relativePath":"posts/2020-07-27-html_js_games_canvas.markdown","relativeDir":"posts","base":"2020-07-27-html_js_games_canvas.markdown","name":"2020-07-27-html_js_games_canvas","frontmatter":{"title":"HTML5 + JS Games - An Intro to the Canvas Element 👾","template":"post","date":"2020-07-27 09:31:03 -0400","permalink":"html_js_games_canvas","filename":"2020-07-27-html_js_games_canvas"},"html":"<blockquote>\n<p>HTML Games are fun way to practice your HTML <code>canvas</code> tag skills as well as Javascript concepts.</p>\n</blockquote>\n<h1>HTML5 + JS Games - An Intro to the Canvas Element 👾</h1>\n<p>Couple of weeks ago I built a clone of the arcade classic snake, <a href=\"http://fbohz.com/html5_games/retro_snake.html\">Retro Snake</a>. Today we'll talk about some basic concepts involved in building HTML5 and JS games.</p>\n<p><strong>HTML Canvas</strong></p>\n<p>HTML Games are fun way to practice your HTML <code>canvas</code> tag skills as well as Javascript concepts.</p>\n<p><code>&#x3C;canvas></code> is an element that has height/width and you can draw anything inside.</p>\n<ul>\n<li>Canvas is like a box with a border. Inside of the box you can make another box, circle, line and text. You cannot do anything outside of the canvas. </li>\n<li>Canvas is defined inside the body.</li>\n</ul>\n<pre><code class=\"language-html\">&#x3C;body>\n    &#x3C;canvas height=\"500\" width=\"500\" \n    style=\"border: 2px solid #000;\" \n    id=\"ctx\">&#x3C;/canvas>\n&#x3C;/body>\n</code></pre>\n<p><strong>Adding Text with JS to Canvas</strong></p>\n<p><code>getContext()</code> is used in JS and '2d' to specify as two-dimension.</p>\n<p>With <code>fillText()</code> you can add text, in specific x and y coordinates, and get something like this:</p>\n<pre><code class=\"language-js\">var ctx = document.getElementById(\"ctx\")\n    .getContext('2d');\n\nctx.fillText(\"HOLA BRAVE NEW WORLD!\", 150, 250);\n</code></pre>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81889102-61502080-9568-11ea-952c-96daee4d9c55.png\" alt=\"1\"></p>\n<p>To make font larger you can do like <code>ctx.font = \"30px Calibri\"</code>.</p>\n<p><strong>Draw a Line in Canvas</strong></p>\n<p><code>strokeText()</code>: gives embossed look to font.</p>\n<p><code>moveTo()</code>: takes two params. First cursor will move to specific position. You use it to draw lines with <code>lineTo()</code>. You can then create line with <code>stroke()</code>. </p>\n<pre><code class=\"language-js\">ctx.moveTo(100,300)\nctx.lineTo(200,300)\nctx.stroke();\n</code></pre>\n<p>So first two methods define line, third draws the line.</p>\n<p><code>fillStyle()</code>. You can add color such as <code>ctx.fillStyle = '#efa556'</code> into a rectangle with <code>fillRect()</code>.</p>\n<p><code>fillRect()</code> takes four arguments. The first two position then next two width and height of rectangle as <code>ctx.fillRect(250, 300, 200, 300);</code>.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/81889930-57c7b800-956a-11ea-9b2a-66d24fb86c55.png\" alt=\"2\"></p>\n<p><strong>Canvas State</strong></p>\n<p>The canvas object we identified as <code>ctx</code> has many properties like we've been describing. Sometimes if we <code>fillStyle()</code> ctx then everything after could be red as well! </p>\n<p>To manage this we have <em>canvas state</em>. </p>\n<ul>\n<li><code>save()</code>: whatever was the state we want to save at that point like a <em>checkpoint</em></li>\n<li>we can then call <code>restore()</code> to restore to previous state.</li>\n</ul>\n<p>So when we do modification on canvas and then save the checkpoint and then restore as we need it.</p>\n<p><strong>Drawing JS Objects in the Canvas</strong></p>\n<p>Lets try to draw this object:</p>\n<pre><code class=\"language-js\">const square = {\n    width: 300,\n    height: 200,\n    x: 100,\n    y: 200,\n    color: 'red'\n}\n</code></pre>\n<p>We can easily draw our square by accessing the square attributes:</p>\n<pre><code class=\"language-js\">ctx.fillStyle = square.color\nctx.fillRect(\n    square.x, square.y, \n    square.width, square.height\n    )\n</code></pre>\n<p><strong>Using JS Functions</strong></p>\n<p>Games like video are just a <em>series of frames</em>. The main difference is that you <em>can interact with the game</em> and not the video.</p>\n<p>We use the <code>setInterval()</code> to accomplish this. This will call the function every specified time. If we have <code>setInterval(myFunction(),1000)</code> then it will be like <em>1fps</em>, as every 1 second there will be new frame. It will be very slow game so we can decrease when <code>setInterval()</code> can be called to have more frames.</p>\n<p><strong>User Inputs &#x26; Event Handling</strong></p>\n<p>You can control events with keyboard and mouse such as:</p>\n<ul>\n<li><code>onmousedown</code></li>\n<li><code>onmouseup</code></li>\n<li><code>onkeydown</code></li>\n</ul>\n<p>Here are some examples:</p>\n<pre><code class=\"language-js\">document.getElementById(\"ctx\").onmousedown = function() {\n    ctx.fillStyle = 'blue';\n    ctx.fillRect(100,100,50,50);\n\n}\n\n\ndocument.getElementById(\"ctx\").onmouseup = function() {\n    ctx.fillStyle = 'red';\n    ctx.fillRect(100,100,50,50);\n\n}\n\ndocument.onkeydown = function(e) {\n    //a = 65 code\n    if (e.keyCode == 65) {\n        ctx.fillText('A has been pressed', 100,100);\n    }\n\n}\n</code></pre>\n<p><strong>Recap</strong></p>\n<p>When building HTML5 + JS games make sure you:</p>\n<ol>\n<li>Declare the <code>canvas</code> element.</li>\n<li>Build objects of the game. For example: Snake and Food (for Snake game). </li>\n<li>Draw objects in the canvas.</li>\n<li>Move objects as required.</li>\n<li>Use functions to meet game requirements. Make sure you have the game requirements clear.</li>\n<li>Add common features such as scores, game over, initial screen etc.</li>\n<li>Add other features. E.g difficulty.</li>\n</ol>\n<p><strong>Resources</strong></p>\n<ul>\n<li>Here's my implementation of snake, <a href=\"http://fbohz.com/html5_games/retro_snake.html\"><b>Retro Snake</b></a>. Note I used Express/MongoDB as a backend to track high scores.</li>\n<li>Read <a href=\"https://www.w3schools.com/graphics/canvas_drawing.asp\"><b>W3 Schools HTML Canvas Drawing</b></a>.</li>\n<li>Checkout <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes\"><b>MDN Drawing Shapes with Canvas</b></a>.</li>\n</ul>"},{"url":"/posts/2020-08-05-getting_started_react_native/","relativePath":"posts/2020-08-05-getting_started_react_native.markdown","relativeDir":"posts","base":"2020-08-05-getting_started_react_native.markdown","name":"2020-08-05-getting_started_react_native","frontmatter":{"title":"Getting Started with React Native","template":"post","date":"2020-08-05 19:31:03 -0400","permalink":"getting_started_react_native","filename":"2020-08-05-getting_started_react_native"},"html":"<blockquote>\n<p>This article on React Native assumes previous knowledge on React so there will be concepts that come from React.</p>\n</blockquote>\n<h1>Getting Started with React Native</h1>\n<p><strong>Before you get started:</strong> This article on React Native assumes previous knowledge on React so there will be concepts that come from React. While reading please refer to the <a href=\"https://github.com/fbohz/react-native-blogs-practice/tree/master/1.Demo\">Demo repository</a> I made previously. Also, read my previous blog on <a href=\"http://fbohz.com/react_basics_refresher\">React basics</a> if you need a refresher.</p>\n<p>React Native (RN) is:</p>\n<ul>\n<li>Cross-platform, native iOS and Android apps without web views</li>\n<li>Mainly focused on the front-end. Uses React JavaScript</li>\n<li>100% access to native APIs via JavaScript and reuse of packages from NPM</li>\n<li>Backed by Facebook</li>\n</ul>\n<p><strong>React Native Approach</strong></p>\n<p>There are React native specific components such as <code>&#x3C;View></code> and <code>&#x3C;Text></code>. RN is a real mobile app. It also uses hot reloading.</p>\n<p>It also gives you the options to go native and inject out Swift/Java should you need. Although most of the time you shouldn't do it.</p>\n<p><strong>How RN works</strong></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82259138-b43b2680-9920-11ea-86be-545e6896e3fd.png\" alt=\"rn1\"></p>\n<p>Android has (V8 JS) and iOS (JS core), RN has the bridge that then implements its framework with JS. RN then spits out native code when we are ready to build with the <code>export SDK</code>.</p>\n<p><strong>Getting Started: Using Expo (Preferred)</strong></p>\n<p>First <a href=\"https://reactnative.dev/docs/getting-started\">read React Native docs</a>.</p>\n<p>Then, to get everything running you should install Expo at <a href=\"https://expo.io/learn\">expo.io</a>. Expo will ensure you can test app on mobile straight.</p>\n<p>After installation. To start directly with a new expo app use <code>expo init projectName</code> then do <code>expo start</code>. You can also clone the <a href=\"https://github.com/fbohz/react-native-blogs-practice/tree/master/1.Demo\"><strong>source code repository</strong></a>. Then just do <code>npm install</code> and <code>expo start</code>.</p>\n<p>From here, you'll need to download the mobile app version (either in AppStore or GooglePlay) of Expo and create an account. Once in the Expo app just scan the generated QR code and you're up and running!.</p>\n<p><strong>RN Project Structure</strong></p>\n<p>Similar convention with React but no <code>index.js</code>. <code>App.js</code> also is your entry point.</p>\n<p>Also note the inline based styling different from React. <code>StyleSheet</code> is imported from RN like JS to apply styles that you can reuse. RN uses <em>flexbox</em> CSS.</p>\n<h2>React Native Components</h2>\n<p>These are just like React components!</p>\n<ul>\n<li>All the features of React components: state, props, JSX, etc.</li>\n<li>It uses native components instead of web components in building the view</li>\n<li>We also use an all-in-one <em>UI kit</em> for creating apps in react native!</li>\n<li>It provides several useful UI components</li>\n<li>Useful in designing the UI for your app</li>\n</ul>\n<p>There are some <em>primitive RN elements</em> such as the following:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82503725-73c5df00-9abf-11ea-93dc-2a5ae3287c92.png\" alt=\"Screen Shot 2020-05-20 at 5 29 00 PM\"></p>\n<p>As you follow along don't forget to download and run the following repo <a href=\"https://github.com/fbohz/react-native-blogs-practice/tree/master/1.Demo\">here</a>. Again, if you navigate to <code>App.js</code>, you'll notice <code>StyleSheet.create</code>, this is optional and you can also pass styles <strong>inline</strong> just like in React.</p>\n<p>You might also notice how when you need to return more than one element you need to wrap it in a single element in this case we can do it in a <code>&#x3C;View></code>.</p>\n<p><strong>Implementing React Native Elements</strong></p>\n<p>The following example uses <code>FlatList</code> from 'react-native' and <code>ListItem</code> from 'react-native-elements'.</p>\n<p>If you check on the <a href=\"https://github.com/fbohz/react-native-blogs-practice/tree/master/1.Demo\">repo</a>, you'll see the <code>&#x3C;ListScreen></code> component. There you'll identify the React Native's <em>FlatList Element</em>:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82512733-8bf52880-9ad6-11ea-9a40-03fd346f35d6.png\" alt=\"Screen Shot 2020-05-20 at 8 14 30 PM\"></p>\n<p>So FlatList does optimizations for you for the mobile world when lists become big. Here the FlatList reminds us just like React that <code>key</code> is important. 'Keys' are important when this list is changed, RN will have to rebuild the entire list if we don't specify the key. Keys optimize and RN will re-render only what it needs.</p>\n<p>FlatList properties:</p>\n<ul>\n<li><code>horizontal</code> will make list horizontal. Only need to add keyword <code>horizontal</code> as Flatlist element prop.</li>\n<li>To hide horizontal bar below just have <code>showsHorizontalScrollIndicator={false}</code></li>\n</ul>\n<h2>RN Navigation</h2>\n<p>Extensible and easy-to-use navigation solution. React Native Navigation supports navigational features. We can have common views of a navigational menu, with <em>stack based</em> pages we commonly see on mobile apps.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82474695-0a2edc00-9a91-11ea-9dcb-ebd4ccb89357.png\" alt=\"Screen Shot 11 56 01 AM\"></p>\n<p>To install read documentation <a href=\"https://reactnavigation.org/docs/getting-started/\">here</a>.</p>\n<p><em>Note:</em> You might notice the newer version of RN Navigation has different implementation.</p>\n<p>Features:</p>\n<ul>\n<li>It automatically adds back bottom.</li>\n<li>Provides support for transition between screens</li>\n<li>\n<p>Manages navigation history</p>\n<ul>\n<li>Similar to web browser</li>\n</ul>\n</li>\n<li>\n<p>Provides the gestures and animations when navigating between routes in the stack</p>\n<ul>\n<li>Enables you to go back, tied to Android back button</li>\n</ul>\n</li>\n</ul>\n<p><strong>Two Types of Buttons for Navigation</strong></p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82516115-99fb7700-9adf-11ea-80b6-00c9ef98ec47.png\" alt=\"Screen Shot 2020-05-20 at 9 19 19 PM\"></p>\n<p>We add the text as string and use the <code>onPress</code> attribute. Remember Button element is self-closed. Out of both for navigation we recommend TouchableOpacity element if you need more customization.</p>\n<p><strong>Implementing Navigation</strong></p>\n<p>We implement navigation on RN with React Navigator. In <code>App.js</code> we see how it uses the <code>createStackNavigator()</code> method. Depending on the version of React Navigator the way you implement it might change.</p>\n<p>With props passed by the stackNavigator() we can tell what to show or not on the screen. To access the navigation object you access it by <code>props.navigation</code>. On the included <code>props.navigation.navigate()</code> method we can pass in the screen we defined on App.js and it will render the component we want! It is easy as:</p>\n<p><code>onPress={() => props.navigation.navigate('ComponentName')}</code></p>\n<p>And voilà! This takes us to the basic navigation and UI display with React Native!</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82520784-a33e1100-9aea-11ea-97de-cf99b4713692.gif\" alt=\"May-20-2020 22-38-00\"></p>\n<h2>React Native - Further Reading</h2>\n<ul>\n<li><a href=\"https://blog.nerdjfpb.com/project-ideas-for-react-native-beginners-to-expert/\" target=\"_blank\" rel=\"noopener nofollow\">15 React Native App IDEAS: BEGINNER TO EXPERT</a></li>\n<li><a href=\"https://www.logicroom.co/react-native-architecture-explained/\" target=\"_blank\" rel=\"noopener nofollow\">React Native Architecture : Explained!</a></li><li><a href=\"https://medium.com/kuralabs-engineering/reactive-core-architecture-for-react-native-and-react-applications-d590daf4ef8a\" target=\"_blank\" rel=\"noopener nofollow\">Reactive Core architecture for React Native and React applications</a></li><li><a href=\"http://www.discoversdk.com/blog/how-react-native-works\" target=\"_blank\" rel=\"noopener nofollow\">How Does React Native Work?</a></li><li><a href=\"https://www.youtube.com/watch?v=7rDsRXj9-cU\" target=\"_blank\" rel=\"noopener nofollow\">React.js Conf 2015 Keynote 2 - A Deep Dive into React Native</a></li>\n<li><a href=\"http://www.smashingmagazine.com/2014/10/providing-a-native-experience-with-web-technologies/\" target=\"_blank\" rel=\"noopener nofollow\">Hybrid Mobile Apps: Providing A Native Experience With Web Technologies</a></li><li><a href=\"https://developer.salesforce.com/page/Native,_HTML5,_or_Hybrid:_Understanding_Your_Mobile_Application_Development_Options\" target=\"_blank\" rel=\"noopener nofollow\">Native, HTML5, or Hybrid: Understanding Your Mobile Application Development Options</a></li><li><a href=\"http://mobile-frameworks-comparison-chart.com/\" target=\"_blank\" rel=\"noopener nofollow\">Mobile Frameworks Comparison Chart</a></li><li><a href=\"http://www.riaxe.com/blog/top-cross-platform-mobile-development-tools/\" target=\"_blank\" rel=\"noopener nofollow\">40+ CROSS PLATFORM DEVELOPMENT TOOLS FOR MOBILE APP AND GAMES</a></li>\n<li><a href=\"https://facebook.github.io/react-native/docs/components-and-apis.html\" target=\"_blank\" rel=\"noopener nofollow\">Components and APIs</a></li><li><a href=\"https://facebook.github.io/react-native/docs/view.html\" target=\"_blank\" rel=\"noopener nofollow\">View</a></li><li><a href=\"https://facebook.github.io/react-native/docs/text.html\" target=\"_blank\" rel=\"noopener nofollow\">Text</a></li><li><a href=\"https://facebook.github.io/react-native/docs/flatlist.html\" target=\"_blank\" rel=\"noopener nofollow\">Flatlist</a></li><li><a href=\"https://facebook.github.io/react-native/docs/stylesheet.html\" target=\"_blank\" rel=\"noopener nofollow\">Stylesheet</a></li><li><a href=\"https://react-native-training.github.io/react-native-elements/docs/getting_started.html\" target=\"_blank\" rel=\"noopener nofollow\">React Native Elements</a></li><li><a href=\"https://react-native-training.github.io/react-native-elements/docs/overview.html\" target=\"_blank\" rel=\"noopener nofollow\">React Native Elements 1.0.0-beta5 Documentation</a></li><li><a href=\"https://react-native-training.github.io/react-native-elements/docs/listitem.html\" target=\"_blank\" rel=\"noopener nofollow\">RNE List Item</a></li><li><a href=\"https://react-native-training.github.io/react-native-elements/docs/card.html\" target=\"_blank\" rel=\"noopener nofollow\">RNE Card</a></li>\n</ul>"},{"url":"/posts/2020-07-21-mongo_db/","relativePath":"posts/2020-07-21-mongo_db.markdown","relativeDir":"posts","base":"2020-07-21-mongo_db.markdown","name":"2020-07-21-mongo_db","frontmatter":{"title":"MongoDB - A Sweet Database 🥭","template":"post","date":"2020-07-21 09:31:03 -0400","permalink":"mongo_db","filename":"2020-07-21-mongo_db"},"html":"<blockquote>\n<p>MongoDB is a NoSQL database...Each database can have one or more <em>collection</em>. What in RDBS are tables. Each collection can have one or more data structures or single entity called <em>document</em>, like table rows in RDBS.</p>\n</blockquote>\n<h1>MongoDB - A Sweet Database 🥭</h1>\n<p>MongoDB is a NoSQL database, compared to relational databases such as MySQL. In the latest reincarnation of our Yijing Ball-Z (YBZ) and <a href=\"http://fbohz.com/html5_games/retro_snake.html\">Snake HTML5 Game</a>, we implemented Mongo.DB/Mongoose on top of Express. So feel free to refer to the <a href=\"https://github.com/fbohz/ybz-backend-node-express\">Mongo.DB YBZ Repository</a> and <a href=\"https://github.com/fbohz/snake-game-node-backend\">Snake Node Backend</a> as you read along.</p>\n<p>In MongoDB:</p>\n<ul>\n<li>Each database can have one or more <em>collection</em>. What in RDBS are tables.</li>\n<li>Each collection can have one or more data structures or single entity called <em>document</em>, like table rows in RDBS.</li>\n</ul>\n<p>MongoDB is defined more specifically as:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/86502577-4c268f80-bd6a-11ea-82e9-b4149a3bb40f.png\" alt=\"Screen Shot 2020-07-03 at 8 17 39 PM\"></p>\n<p>MongoDB uses as data structure like JSON called <em>BSON</em>. BSON is typed so documents are typed. Meaning all values <em>have a data type</em>, like string, boolean, number. All MongoDB documents are typed as well. With MongoDB you can have multiple values in one field, unlike RDBS. You can also have embedded documents. BSON documents have a limit on size as well.</p>\n<p><em>Embedding/Denormalizing</em>: Including related data into a single document. It allows for quicker access and easier data models (better performance). But it's not always the best solution. Opposite is normalization in RDBS, which involves creating new tables, joining them.</p>\n<p><strong>Installing Using MongoDB</strong></p>\n<p>You can install locally MongoDB community server or use Atlas version in the cloud. After installing lets say locally you can create a new db, just run the shell by doing <code>mongod</code>, starting mongo shell on a new tab with just <code>mongo</code> and then doing <code>use dbName</code>. You can create a collection by doing this:</p>\n<p><code>db.tours.insertOne({name: \"Test Tour\", price: 297})</code></p>\n<p>Note you refer to your current database as <code>db</code> even though you named your database differently. You can refer to newly created document as such:</p>\n<p><code>db.tours.find()</code></p>\n<p>MongoDB automatically creates unique ids for documents created. You can show databases available and collections by doing either <code>show dbs</code> or <code>show collection</code>.</p>\n<p>You can also insert many documents just by doing for example <code>db.tours.insertMany([{},{}])</code>. You can also have different fields in different documents. So no limitation on fields as could be with RDBS.</p>\n<p>If for some reasons you have issues with the running mongod process you can force stop it by doing <code>sudo killall mongod</code>.</p>\n<h2>CRUD with MongoDB</h2>\n<p><strong>Reading</strong></p>\n<p>We already completed the C of CRUD by creating documents. Below are some reading/querying operators.<code>find()</code>: You can also pass a filter object. E.g. <code>db.tours.find({difficulty: \"easy\"})</code></p>\n<p>You can make even more complex searches with <em>query operators</em>. Query operators start with an <code>$</code>, for example less than or equal is <code>$lte</code>. E.g. <code>db.tours.find({price {$lte: 500}})</code>.</p>\n<p>You can also have two search criteria. E.g <code>db.tours.find({price {$lt: 500}, rating: {$gte: 4.8}})</code>. Here <code>gte</code> is greater than or equal and <code>lt</code> is simply less than.</p>\n<p>Or queries can be performed as with <code>$or</code>. E.g <code>db.tours.find($or: [{price {$lt: 500}, rating: {$gte: 4.8}}])</code>. If you want to show only one field, e.g. name only you can do <code>db.tours.find({difficulty: \"easy\"}, {name: 1})</code>.</p>\n<p>You're starting to see how in MongoDB everything works with objects!</p>\n<p><strong>Updating</strong></p>\n<p>Similar to insertOne, insertMany we can do to update for example <code>db.tours.updateOne({name: \"Test Name\"}, {$set: {price: 499}})</code>. As you can see first you're like querying for the document then you update it. We use the <code>$set</code> operator and because we use insertOne if many matches only the first match is updated.</p>\n<p>To update more than one document if we expect multiple matches we can do <code>db.tours.UpdateMany({price {$lt: 500}, rating: {$gte: 4.8}}, {$set {premium: true}})</code>.</p>\n<p><strong>Delete</strong></p>\n<p>Delete is straightforward and we have <code>deleteOne</code> and <code>deleteMany</code>. For example: <code>db.tours.deleteMany({rating: {$lt: 4.8}})</code>. To delete <em>all</em> documents in a collection you just pass an empty object as this <code>db.tours.deleteMany({})</code>.</p>\n<h2>Bonus: Using the Mongoose Library</h2>\n<p>You can install with <code>npm i mongoose</code>. The relationship between MongoDB and Mongoose is similar as to that of Node.js and Express, so it a level up abstraction higher. The Object Data Modeling (ODM) it uses it is just a way to talk to the database. Mongoose allows for for rapid development. It also allows for schemas to model data, relationships, easy validation, query API and other middleware.</p>\n<p>In Mongoose we have the schema and the model. The <em>schema</em> is where the data is modeled, data structure is described, with default values and validation. The Mongoose <em>model</em> is a wrapper for the schema, which provides an interface to make CRUD operations on the database.</p>\n<p><strong>Creating a Schema and Model in Mongoose</strong></p>\n<p>Mongoose is about models. We create these models as blueprints for our db, in order to creates objects. In order to create a model we need a schema. In the most basic sense we can define our schema as such:</p>\n<pre><code class=\"language-js\">const tourSchema = new mongoose.Schema({\n  name: String,\n  rating: Number,\n  price: Number,\n});\n</code></pre>\n<p>We can refine it by adding some validations.</p>\n<pre><code class=\"language-js\">const tourSchema = new mongoose.Schema({\n  name: {\n    type: String,\n    required: [true, \"must have name\"],\n    unique: true,\n  },\n  rating: {\n    type: Number,\n    default: 4.5,\n  },\n  price: {\n    type: Number,\n    required: [true, \"must have price\"],\n  },\n});\n</code></pre>\n<p>Now we can create our model. Always remember models are capitalized in mongoose.</p>\n<pre><code class=\"language-js\">const Tour = mongoose.model(\"Tour\", tourSchema);\n</code></pre>\n<p><strong>Testing Our Model: Creating Documents</strong></p>\n<p>We can create new documents based upon the model we created.</p>\n<pre><code class=\"language-js\">const testTour = new Tour({\n  name: \"Magic Monquira\",\n  rating: 4.7,\n  price: 49,\n});\n</code></pre>\n<p>We can now save using <code>.save()</code> which produces a promise we can consume as well. The result value of the promise is a document.</p>\n<pre><code class=\"language-js\">testTour\n  .save()\n  .then((doc) => {\n    console.log(doc);\n  })\n  .catch((err) => console.log(\"ERROR: \", err));\n</code></pre>\n<p>Now you can check your db using the MongoDB Atlas or Compass interface and there you go you just used Mongoose to save to our MongoDB database, pretty easy right from our code!</p>\n<h2>Level Up 🍄 Readings</h2>\n<ul>\n<li><a href=\"https://www.mongodb.com/try/download/community\"><strong>Mongo DB Community Server</strong></a></li>\n<li>You can install <a href=\"https://www.mongodb.com/products/compass\"><strong>Compass App</strong></a> to make easy CRUD Operators and with a nice Graphical interface.</li>\n<li><a href=\"https://mongoosejs.com/docs/api.html\"><strong>Mongoose Docs</strong></a>.</li>\n<li><a href=\"https://mongoosejs.com/docs/queries.html\"><strong>Mongoose Queries</strong></a>.</li>\n</ul>"},{"url":"/posts/2020-08-04-mobile_development_roads/","relativePath":"posts/2020-08-04-mobile_development_roads.markdown","relativeDir":"posts","base":"2020-08-04-mobile_development_roads.markdown","name":"2020-08-04-mobile_development_roads","frontmatter":{"title":"Mobile Development - Which Road To Take?📱","template":"post","date":"2020-08-04 19:31:03 -0400","permalink":"mobile_development_roads","filename":"2020-08-04-mobile_development_roads"},"html":"<blockquote>\n<p>You will be surprised that many of the mobile applications that you use are actually hybrid mobile applications (using frameworks like React Native)...</p>\n</blockquote>\n<h1>Mobile Development - Which Road To Take?📱</h1>\n<p>There are few options available when it comes to mobile development.</p>\n<p><em>Native Apps</em> (using Swift for iOS or Java for Android):</p>\n<ul>\n<li>Platform specific skills</li>\n<li>Highest performance</li>\n<li>Full access to device capabilities</li>\n</ul>\n<p>Basically when you hear 'native' it doesn't mean that you are writing in machine code. There's still some level of abstraction, so although called native, it is not to the strictest sense.</p>\n<p>You'll also need <em>two separate code bases</em>. So could we do a mobile app and use a single code base? </p>\n<p><em>Option 1: Mobile Web Apps</em></p>\n<ul>\n<li>Fully hosted in the mobile browser</li>\n<li>Slowest</li>\n<li>No access to device capabilities. However it is improving but still lots of limitations</li>\n</ul>\n<p><em>Option 2: Hybrid with WebView</em></p>\n<ul>\n<li>Embedded web view based with partial implementation in native code </li>\n<li>Slow, but comparable to native apps based on functionality. Still some limitations.</li>\n<li>Some access to device capabilities</li>\n<li>Example: Ionic framework.</li>\n</ul>\n<p><em>Option 3: Compiled/Interpreted/VM Hybrid</em></p>\n<ul>\n<li>Makes use of Native UIs with the native platform’s rendering engine, not WebViews\n– Near-native performance\n– Access to most device capabilities </li>\n<li>Built in JS engine that both Android/iOS use</li>\n<li>Example: React Native</li>\n</ul>\n<h2>Digging Deeper</h2>\n<p><em>WebView App</em></p>\n<ul>\n<li>The HTML, CSS and JavaScript code base runs in an internal browser (called WebView) that is wrapped in a native app. Some native APIs are exposed to JavaScript through this wrapper</li>\n<li>This mobile app feels native.\n– Examples: Ionic Framework + Cordova/Phonegap, Trigger.io</li>\n</ul>\n<p><em>Compiled/Interpreted/VM hybrid app</em></p>\n<ul>\n<li>The code is written in one language (such as C# or JavaScript) and gets\ncompiled/interpreted to native code or run on a Virtual Machine (VM) for each supported platform. The result is a native app for each platform, but less freedom during development</li>\n<li>Examples: React Native, NativeScript, Appcelerator Titanium, Xamarin, Embarcadero, FireMonkey</li>\n</ul>\n<p><em>Different types of frameworks aimed to build hybrid apps</em></p>\n<ul>\n<li>Frameworks targeting HTML5 content like Ionic + Cordova/Phonegap (both\nvia JS byte code)</li>\n<li>Frameworks like React Native, NativeScript and Appcelerator Titanium that render the UI using the platform’s native controls but still work via JS</li>\n<li>Free (or partially free) Frameworks aiming to produce real native code like Unity (C# or JS based, Games oriented), Kivy (Python Based) or libgdx (Java based, Game Oriented)</li>\n<li>Commercial Frameworks aiming to produce real native code like Xamarin\n(using C#) or Embarcadero</li>\n</ul>\n<h2>Good vs Bad of Hybrid Development</h2>\n<p><strong>Advantages of Hybrid Approach</strong></p>\n<ul>\n<li>Developer can use existing skills</li>\n<li>One code base for multiple platforms</li>\n<li>Reduced development time and cost</li>\n<li>Easily design for various form factors (including tablets) using responsive web design</li>\n<li>Access to (some) device and operating system features</li>\n<li>Advanced offline capabilities. You get access to the native storage capabilities on the mobile devices. </li>\n<li>Increased visibility because the app can be distributed natively (via app stores) and to mobile browsers (via search engines)</li>\n</ul>\n<p><strong>Drawbacks of Hybrid Approach</strong></p>\n<ul>\n<li>Performance issues for certain types of apps (ones relying\non complex native functionality or heavy transitions, such\nas 3D games)</li>\n<li>Increased time and effort required to mimic a native UI and\nfeel</li>\n<li>Not all device and native features (fully) supported</li>\n<li>Risk of being rejected by Apple if app does not feel 'native'\nenough (for example, a simple website)</li>\n</ul>\n<p><strong>Where Hybrid Apps Work Best</strong></p>\n<ul>\n<li>Hybrid approach does not suit all kinds of apps</li>\n<li>Need to carefully evaluate your target users, their\nplatforms of choice and the app’s requirements.</li>\n<li>\n<p>Mainly suitable for content-driven apps</p>\n<ul>\n<li>Business and Productivity</li>\n<li>Enterprise</li>\n<li>Media</li>\n</ul>\n</li>\n</ul>\n<p>You will be surprised that many of the mobile applications that you use are actually hybrid mobile applications (using frameworks like React Native). Take Facebook app as an example.</p>\n<p>So now that you know the options available <em>which road will you take?</em></p>\n<h2>References</h2>\n<ul>\n<li><a href=\"https://www.coursera.org/learn/react-native\"><strong>Multiplatform Mobile App Development with React Native</strong></a></li>\n</ul>"},{"url":"/posts/2020-08-19-css_cheatsheet.css_cheatsheet/","relativePath":"posts/2020-08-19-css_cheatsheet.css_cheatsheet.markdown","relativeDir":"posts","base":"2020-08-19-css_cheatsheet.css_cheatsheet.markdown","name":"2020-08-19-css_cheatsheet.css_cheatsheet","frontmatter":{"title":"CSS Cool Tricks Cheatsheet 😎","template":"post","date":"2020-08-19 09:31:03 -0400","permalink":"css_cheatsheet","filename":"2020-08-19-css_cheatsheet"},"html":"<blockquote>\n<p>If you always feel you have to look up CSS terms, checkout this cheatsheet! It will make your CSS life easier.</p>\n</blockquote>\n<h1>CSS Cool Tricks Cheatsheet 😎</h1>\n<p>If you always feel you have to look up CSS terms, checkout this cheatsheet! It will make your CSS life easier. I applied some if this tricks while I was building Museo, a <a href=\"http://fbohz.com/css-learning/museo-demo/index.html\">Vanilla CSS/SCSS Landing Page</a>.</p>\n<p><strong>Know About the Three Pillars to Write Good CSS</strong></p>\n<ol>\n<li><em>Responsive Design</em>: Building a website that works well on all devices. You'll have to know about fluid layouts, media queries, responsive images, correct units (for e.g. font sizes) and desktop-first vs mobile-first.</li>\n<li><em>Writing maintainable/scalable code</em>: Write code that is clean and reusable. Think about CSS folder architecture, and class naming.</li>\n<li><em>Web Performance</em>: Make it faster and smaller in size. Less HTTP requests, compress code, and use a CSS preprocessor. Also less images and if images, compress them.</li>\n</ol>\n<p><strong>Reset Styles Globally</strong></p>\n<p>Sometimes you want to reset styles from those that might be imposed by the browser by default. Here's an example</p>\n<pre><code class=\"language-css\">* {\n  margin: 0;\n  padding: 0;\n  box-sizing: border-box;\n}\n</code></pre>\n<p><strong>Attribute Selectors</strong></p>\n<p>We can select attributes by wrapping them in <code>[]</code></p>\n<pre><code class=\"language-css\">/* ^ means starts with */\n\n[class^=\"col-\"] {\n    float: left;\n    background-color: orange;\n}\n</code></pre>\n<p><strong>Converting <code>px</code> units to <code>rem</code></strong></p>\n<p>The <code>rem</code>  unit is related to root font size. So by setting the root font size, then use rem so you can easily make changes to root without changing all lines of codes. You can specify root font size. Instead of having root font as as px we could use percentages. </p>\n<pre><code class=\"language-css\">html {\n    font-size: 62.5%;\n}\n</code></pre>\n<p>Since usually default font size is 16px here we are saying 62.5% which is roughly 10px. This will mean that 1rem is 10px, 2rem is 20px and so forth. </p>\n<p>You can then use rem as this:</p>\n<pre><code class=\"language-css\">.logo-box {\n position: absolute;\n /* 4rem = 40px */\n top: 4rem; \n left: 4rem;\n}\n</code></pre>\n<p><strong><code>!important</code></strong></p>\n<p><code>!important</code> overrides specificity rules. Can save headaches to make it work before you debug accordingly.</p>\n<p>You can add it also on utilities (using SASS), as reusable stylings. <a href=\"https://css-tricks.com/when-using-important-is-the-right-choice/\">Read more</a>.</p>\n<p><strong><code>box-sizing: border-box</code></strong></p>\n<p> With <code>box-sizing: border-box</code> we can change the box model. This is useful when an element’s specified width and height aren’t affected by padding or borders. This has proven so useful in responsive design that has found its way into reset styles. So border-box can help make responsive layouts more manageable.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85438771-eceaa300-b551-11ea-8a51-b767df986fc8.png\" alt=\"Screen Shot 2020-06-23 at 1 02 30 PM\"></p>\n<p><strong><code>clip-path: polygon()</code></strong></p>\n<p>You specify the polygon you want to add the clipping. Then you add clippings with x and y coordinates left to right.  Use <a href=\"https://bennettfeely.com/clippy/\">Clippy tool</a> to calculate it for you! You can make some cool polygon effects. </p>\n<p><strong>CSS Animations with <code>@keyframes</code> and <code>animation</code></strong></p>\n<p>We use <code>@keyframes</code> and then give animation a name. Then you specify what happens when animation starts, ends and anything in the middle.</p>\n<pre><code class=\"language-css\">@keyframes moveInLeft {\n0% {\n opacity: 0;\n transform: translateX(-100px);\n}\n\n100% {\n opacity: 1;\n transform: translate(0);\n}\n}\n</code></pre>\n<p>Then once you define it, you can add it to the specific element you want to apply with the <code>animation</code> keyword.</p>\n<pre><code class=\"language-css\">.btn-animated {\n/* animation name, animation duration\n    animation timing function, \n    animation delay\n*/\nanimation: moveInBottom .5s ease-out .75, \n}\n</code></pre>\n<p><strong><code>backface-visibility: hidden</code></strong></p>\n<p>Whenever you work with animations and with <code>translate()</code>, many times <code>backface-visibility: hidden;</code> fixes many errors. So try to add it if you are having issues!</p>\n<p><strong><code>overflow: hidden</code></strong></p>\n<p>Another trick when an element is too big and is overflowing. You can use <code>overflow: hidden</code> to fix it.</p>\n<p><strong>Pseudo Elements and Pseudo Classes</strong></p>\n<p><em>Pseudo classes</em> are a special state of a selector. For example <code>.btn:link</code> selects the elements on a special condition in this case when a button is a link.</p>\n<pre><code class=\"language-css\">.btn:link {\n  display: inline-block;\n  text-decoration: none;\n  text-transform: uppercase;\n}\n</code></pre>\n<p><em>Pseudo elements</em> allow us to select certain part of an element. They are denoted with two colons to differentiate them from pseudo classes. This is the syntax:</p>\n<pre><code class=\"language-css\">selector::pseudo-element {\n  property: value;\n}\n</code></pre>\n<p>There are various pseudo elements. Take a sneak peak and learn more about them <a href=\"https://blog.logrocket.com/a-guide-to-css-pseudo-elements/\">here</a>.</p>\n<p><strong><code>box-shadow</code></strong></p>\n<p>With box shadow you can add shadow to elements. Take a look at this <a href=\"https://www.cssmatic.com/box-shadow\">box shadow generator</a>.</p>\n<p><strong><code>@supports</code> For Older Browser Support</strong></p>\n<p>You can do graceful degradation with <code>@supports</code>. Example:</p>\n<pre><code class=\"language-css\">@supports (-webkit-backdrop-filter: blur(7px)) or (backdrop-filter: blur(7px)) {\n    -webkit-backdrop-filter: blur(20px);\n    backdrop-filter: blur(20px);\n    background-color: rgba($color-black, .7);\n}\n</code></pre>\n<p>This will make your CSS support older browsers.</p>\n<h2>BONUS - SASS Preprocessor</h2>\n<p>If you wanna use SASS in your project just install it with <code>npm i node-sass --save-dev</code>.</p>\n<p><strong>Implement SASS Variables</strong></p>\n<p>We can use SASS to implement variables, e.g. when specifying colors.</p>\n<pre><code class=\"language-css\">$color-primary: #f9ed69\n\nnav {\n  background-color: $color-primary;\n}\n</code></pre>\n<p><strong>Implement Nesting With SASS</strong></p>\n<p>In SASS you can do nesting and it will read much better.</p>\n<pre><code class=\"language-css\">.navigation {\n  list-style: none;\n\n  li {\n    display: inline-block;\n\n    &#x26;:first-child {\n      margin: 0;\n    }\n  }\n}\n</code></pre>\n<p>Note that <code>&#x26;</code> replaces selectors up to the point. So in normal CSS this will equate  <code>.navigation li:first-child</code>. In CSS we would write everything above as the following (notice how we save a lot of repetition):</p>\n<pre><code class=\"language-css\">.navigation {\n list-style: none;\n}\n\n.navigation li {\n display: inline-block;\n}\n\n.navigation li:first-child {\n  margin: 0;\n}\n</code></pre>\n<p>Be careful on how deeper you go on nesting. Usually don't go deeper than two levels!</p>\n<p><strong>Mixins</strong></p>\n<p><em>Mixin</em> is a reusable piece of code. Let's say we want to implement a <a href=\"https://www.w3schools.com/howto/howto_css_clearfix.asp\">Clearfix</a> in multiple places. We use the <code>@mixin</code> keyword to define it and <code>@include</code> where we want to use it.</p>\n<pre><code class=\"language-css\">@mixin clearfix {\n &#x26;:after {\n     content: \"\";\n     clear: both;\n     display: table'\n }   \n}\n\nnav {\n @include clearfix;\n}\n</code></pre>\n<p>You can also pass in variables to mixin definitions. Just make sure when you want to use it, also pass in the variable for the mixin to work. Mixins then do become like functions. There are also extends and functions in SCSS so become familiar with them, but mixins are used the majority of times.</p>\n<p><strong>Fast Development Environment with SASS</strong></p>\n<p><em>Remember</em> to install SASS. Then you can compile by adding this script in package.json:</p>\n<pre><code class=\"language-ruby\">\"scripts\": {\n \"compile:sass\": \"node-sass sass/main.scss css/style.css -w\"\n},\n</code></pre>\n<p>The <code>-w</code> will keep watching for whatever we do in our code. You can also install <code>npm i live-server -g</code>. Then run it as <code>live-server</code> on root folder. For the changes to be reflected without needing to reload manually.</p>\n<p><strong>Build Scripts for SASS</strong></p>\n<p>We can implement simple NPM build processes after we finish a feature.</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85962487-9a0c5380-b976-11ea-8dae-b021b308f223.png\" alt=\"Screen Shot 2020-06-28 at 7 35 10 PM\"></p>\n<p>There are a couple of NPM packages we use, we can install as <code>npm i concat --save-dev</code>, <code>npm i autoprefixer --save-dev</code>, <code>npm i postcss-cli --save-dev</code>, <code>npm i npm-run-all --save-dev</code>.</p>\n<p>We do this on <code>package.json</code>, check it on <a href=\"https://github.com/fbohz/css-learning/blob/master/museo-demo/package.json\">Github repository</a> or see below the updated scripts part on package.json:</p>\n<pre><code class=\"language-ruby\">\"scripts\": {\n  \"watch:sass\": \"node-sass sass/main.scss css/style.css -w\",\n  \"devserver\": \"live-server\",\n  \"start\": \"npm-run-all --parallel devserver watch:sass\",\n  \"compile:sass\": \"node-sass sass/main.scss css/style.comp.css\",\n  \"concat:css\": \"concat -o css/style.concat.css css/linea-icon-fonts.css css/style.comp.css\",\n  \"prefix:css\": \"postcss --use autoprefixer -b 'last 10 versions' css/style.concat.css -o css/style.prefix.css\",\n  \"compress:css\": \"node-sass css/style.prefix.css css/style.css --output-style compressed\",\n  \"build:css\": \"npm-run-all compile:sass concat:css prefix:css compress:css\"\n},\n</code></pre>\n<p>Note the <code>--parallel</code> flag on start script. It means both run at the same time. On compile script be careful of your own .scss and .css file locations and update it accordingly.</p>\n<p>It doesn't matter if you don't understand everything. To compile your SASS into CSS all you do:</p>\n<p><code>npm run build:css</code></p>\n<p>With this, your CSS will be compiled, concat, compressed and ready for production! Bam💥</p>\n<h2>Even More Tricks and Resources</h2>\n<ul>\n<li><a href=\"http://tympanus.net/codrops/css_reference/\"><strong>CSS Reference</strong></a> you can take a look. </li>\n<li><a href=\"https://docs.emmet.io/cheat-sheet/\"><strong>Emmet Cheat Sheet</strong></a>. Write HTML faster in VS Code</li>\n<li><a href=\"https://css-tricks.com/box-sizing/\"><strong>Box Sizing</strong></a></li>\n<li><a href=\"https://css-tricks.com/snippets/html/glyphs/\"><strong>HTML Glyphs</strong></a></li>\n<li><a href=\"https://linea.io/\"><strong>Linea Free Icons</strong></a></li>\n<li><a href=\"http://coverr.co/\"><strong>Coverr - Free Videos</strong></a></li>\n<li><a href=\"https://easings.net/\"><strong>Easings.net</strong></a>.Pick your favorite transition and then copy the <code>cubic-bezier</code> function and voila! You can compare bezier curves with <a href=\"https://cubic-bezier.com/#.17,.67,.83,.67\">this tool</a>.</li>\n<li><a href=\"https://sizzy.co/\"><strong>Sizzy</strong></a>, a tool for responsive website building.</li>\n<li><a href=\"https://github.com/jonasschmedtmann/advanced-css-course\"><strong>Good Udemy Course</strong></a></li>\n<li><a href=\"https://caniuse.com/\"><strong>Can I Use</strong></a>, for browser support checking</li>\n</ul>"},{"url":"/posts/2020-08-10-three_tier_full_stack/","relativePath":"posts/2020-08-10-three_tier_full_stack.markdown","relativeDir":"posts","base":"2020-08-10-three_tier_full_stack.markdown","name":"2020-08-10-three_tier_full_stack","frontmatter":{"title":"Three-Tier Architecture & Full-Stack Development","template":"post","date":"2020-08-10 09:31:03 -0400","permalink":"three_tier_full_stack","filename":"2020-08-10-three_tier_full_stack"},"html":"<blockquote>\n<p>We often hear people talking about the three tier architecture for web development...while these tiers often have different languages, there are systems that implement a single language for all tiers</p>\n</blockquote>\n<h1>Three-Tier Architecture &#x26; Full-Stack Development</h1>\n<p>We often hear people talking about the three tier architecture for web development. In this approach, the entire web application is organized into three different layers. </p>\n<ol>\n<li>The <em>presentation layer</em> which is concerned with delivering the information to the user. So, those are usually the UI related concerns that are dealt with at the presentation layer. Here we usually have HTML, CSS, and JavaScript.</li>\n<li>The <em>business logic layer</em> on the other hand is concerned more about the data, the data validation, the dynamic content processing, and generating the content to be delivered to the user. Here we usually have, Node, Ruby, Python, Java, C++ or PHP.</li>\n<li>This is backed up behind the scenes with the data persistence layer or the <em>data access layer</em>. So, this is concerned with how we store and interact with the data, typically in the form of a database and access this data through an API. So business logic layer interacts with the database like MongoDB or PostgreSQL.</li>\n</ol>\n<p>Today, we could have an specialist in one of these layers. </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82156217-93e76b00-983f-11ea-9ed2-efcb1b31db65.png\" alt=\"1\"></p>\n<p>Also, while these tiers often have different languages, there are systems that implement a single language for all tiers.</p>\n<p><strong>Frontend vs Backend</strong></p>\n<p><em>Front End</em></p>\n<p>Typically, in a browser where the user can access the information, and this is where we use technologies like HTML, CSS and JavaScript are used to render content for the user.</p>\n<p><em>Backend</em></p>\n<p>This information delivery is managed behind the scenes by a back end support which is typically implemented nowadays using technologies like PHP, Java, ASP.NET, Ruby, Python or Node.</p>\n<p><strong>Unifying a Single Language</strong></p>\n<p>There's a trend in using <strong>one language</strong> for all three tiers. This will make one more prone to specialize as <em>full-stack web developer</em>. This is what Javascript tries to do by implementing for example React presentation, Node business logic and MongoDB for data access. </p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/82156410-8b436480-9840-11ea-97ce-92bbe22307a7.png\" alt=\"2\"></p>\n<p>So, you could have the front end implemented as a single page application using frameworks like Angular or React. You have the server side or the business logic layer being implemented using technologies like Node, which is also dependent on JavaScript, and then you have the data storage itself being implemented using technologies like Mongo DB, which stores data in the form of JSON documents. The information exchange between the server-side and the client-side is usually done using JSON as the format, and the server-side supports a REST API endpoint.</p>\n<p><strong>Resources</strong></p>\n<ul><li><a href=\"http://www.laurencegellert.com/2012/08/what-is-a-full-stack-developer/\" target=\"_blank\" rel=\"noopener nofollow\">What is a Full Stack developer?</a></li><li><a href=\"http://edward-designer.com/web/full-stack-web-developer/\" target=\"_blank\" rel=\"noopener nofollow\">Wait, Wait… What is a Full-stack Web Developer After All?</a></li><li><a href=\"http://andyshora.com/full-stack-developers.html\" target=\"_blank\" rel=\"noopener nofollow\">The Myth of the Full-stack Developer</a></li><li><a href=\"https://en.wikipedia.org/wiki/Multitier_architecture\" target=\"_blank\" rel=\"noopener nofollow\">Multi-tier Architecture</a></li><li><a href=\"http://www.tonymarston.net/php-mysql/3-tier-architecture.html\" target=\"_blank\" rel=\"noopener nofollow\">What is the 3-Tier Architecture?</a></li></ul>"},{"url":"/posts/2020-08-26-learning_about_flexbox_css/","relativePath":"posts/2020-08-26-learning_about_flexbox_css.markdown","relativeDir":"posts","base":"2020-08-26-learning_about_flexbox_css.markdown","name":"2020-08-26-learning_about_flexbox_css","frontmatter":{"title":"Learning About Flexbox","template":"post","date":"2020-08-26 09:31:03 -0400","permalink":"learning_about_flexbox_css","filename":"2020-08-26-learning_about_flexbox_css"},"html":"<blockquote>\n<p>It might be common to think that software engineers don't have to deal or worry about UI, since it is delegated to UX designers. However learning about CSS patterns such as Flexbox is crucial to becoming a more thorough developer and problem solve with a design/layout mindset.</p>\n</blockquote>\n<h1>Learning About Flexbox</h1>\n<p>It might be common to think that software engineers don't have to deal or worry about UI, since it is delegated to UX designers. However learning about CSS patterns such as Flexbox is crucial to becoming a more thorough developer and problem solve with a design/layout mindset.</p>\n<p><strong>What Is Flexbox</strong></p>\n<p>You can apply Flexbox to setup the initial layout of a website, app, and mobile application (with React Native). The first thing we need to do to start using Flexbox is to apply the following to the parent container:</p>\n<p><code>display: flex</code></p>\n<h2>Flex Parent (Container) Properties</h2>\n<p>Now lets imagine you have a container with 3 boxes:</p>\n<pre><code class=\"language-html\">&#x3C;div class=\"flex-container\">\n  &#x3C;div>1&#x3C;/div>\n  &#x3C;div>2&#x3C;/div>\n  &#x3C;div>3&#x3C;/div>\n&#x3C;/div>\n</code></pre>\n<p>In the container we could apply one of the following and each will have a different effect on the child:</p>\n<ul>\n<li>flex-direction</li>\n<li>flex-wrap</li>\n<li>flex-flow</li>\n<li>justify-content</li>\n<li>align-items</li>\n<li>align-content</li>\n</ul>\n<p><strong>Flex Direction</strong></p>\n<p>Lets say we'll apply <code>flex-direction: column</code> what do we get?</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85189215-6775a300-b272-11ea-8de6-02d230574e0a.png\" alt=\"Screen Shot 2020-06-19 at 9 17 54 PM\"></p>\n<p>So pretty much we decide if we want them left-right or right-left, top-bottom etc. These are your options:</p>\n<pre><code class=\"language-css\">.container {\n  flex-direction: row | row-reverse \n  | column | column-reverse;\n}\n</code></pre>\n<p><strong>Flex Wrap</strong></p>\n<p>By default flex will try to fit all items into a single line if you don't want this you can change it:</p>\n<pre><code class=\"language-css\">.container {\n  flex-wrap: nowrap | wrap | wrap-reverse;\n}\n</code></pre>\n<ul>\n<li>nowrap (default): all flex items will be on one line</li>\n<li>wrap: flex items will wrap onto multiple lines, from top to bottom.</li>\n<li>wrap-reverse: flex items will wrap onto multiple lines from bottom to top.</li>\n</ul>\n<p><strong>Flex Flow</strong></p>\n<p>With flex flow we combine flex-wrap and flex-direction into one property for example <code>flex-flow: column wrap;</code>.</p>\n<p><strong>Justify Content</strong></p>\n<p>With justify-content we can align our items along the main axis. You can distribute extra space. Here are our options:</p>\n<pre><code class=\"language-css\">.container {\n  justify-content: flex-start | flex-end \n  | center | space-between | space-around \n  | space-evenly | start | end \n  | left | right ... + safe | unsafe;\n}\n</code></pre>\n<p>For example we can display our items in the center with <code>justify-content: center;</code>:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85189316-97717600-b273-11ea-8cd9-150395753be7.png\" alt=\"Screen Shot 2020-06-19 at 9 26 40 PM\"></p>\n<p><strong>Align Items</strong></p>\n<p>We use it with justify-content to align items. This more specifically with align-items on a cross axis of the current line, so perpendicular to main-axis. We could apply this:</p>\n<pre><code class=\"language-css\">.container {\n  align-items: stretch | flex-start | flex-end \n  | center | baseline | first baseline \n  | last baseline | start | end |\n   self-start | self-end + ... safe | unsafe;\n}\n</code></pre>\n<p><strong>Align Content</strong></p>\n<p>With align-content you can align items along multiple lines:</p>\n<pre><code class=\"language-css\">align-content: flex-start | flex-end | center\n | space-between | space-around | stretch\n</code></pre>\n<p>If there's only one line, this property will have no effect.</p>\n<h2>Flex Children (Items/Elements) Properties</h2>\n<p>You can apply the following to child elements of the container:</p>\n<pre><code class=\"language-css\">order: &#x3C;integer>;\nflex-grow: &#x3C;number>; /* default 0 */\nflex-shrink: &#x3C;number>; /* default 1 */\nflex-basis: &#x3C;length> | auto; /* default auto */\nflex: none | [ &#x3C;'flex-grow'> &#x3C;'flex-shrink'>?\n || &#x3C;'flex-basis'> ]\nalign-self: auto | flex-start | flex-end\n | center | baseline | stretch;\n</code></pre>\n<p><strong>Order</strong></p>\n<p>With order you specify the order of the children elements. The default is 0.</p>\n<p><strong>Flex Grow / Flex Shrink</strong></p>\n<p>With flex-grow you can specify how many a specify item will grow compared to others. Default is 0. Consider this:</p>\n<pre><code class=\"language-html\">&#x3C;div class=\"flex-container\">\n  &#x3C;div style=\"flex-grow: 1\">1&#x3C;/div>\n  &#x3C;div style=\"flex-grow: 1\">2&#x3C;/div>\n  &#x3C;div style=\"flex-grow: 8\">3&#x3C;/div>\n&#x3C;/div>\n</code></pre>\n<p>What we get:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85189460-f5528d80-b274-11ea-8cff-9be118384ba1.png\" alt=\"Screen Shot 2020-06-19 at 9 36 26 PM\"></p>\n<p>Flex-shrink is kind of the opposite thus how it will shrink related to its sibling items. Default is 1.</p>\n<p><strong>Flex Basis</strong></p>\n<p>You can specify the initial length of an item. Default is auto.</p>\n<p><strong>Flex</strong></p>\n<p>With flex you can apply <code>flex-grow, flex-shrink, and flex-basis</code> at the same time. The second and third parameters are optional. It is <em>recommended</em> to use <code>flex</code> instead of the individual properties.</p>\n<p><strong>Align Self</strong></p>\n<p>Align self sets how the selected item will be aligned. It also overrides the align-items parent property. </p>\n<pre><code class=\"language-css\">.item {\n  align-self: auto | flex-start \n  | flex-end | center | baseline | stretch;\n}\n</code></pre>\n<p>Here we can align the third item in the middle of its parent container:</p>\n<pre><code class=\"language-html\">&#x3C;div class=\"flex-container\">\n  &#x3C;div>1&#x3C;/div>\n  &#x3C;div>2&#x3C;/div>\n  &#x3C;div style=\"align-self: center\">3&#x3C;/div>\n  &#x3C;div>4&#x3C;/div>\n&#x3C;/div>\n</code></pre>\n<p>We then get:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85189784-99d5cf00-b277-11ea-8720-b1e4c18ff770.png\" alt=\"Screen Shot 2020-06-19 at 9 55 21 PM\"></p>\n<p><strong>Flex Tips</strong></p>\n<ul>\n<li>For centering try <code>justify-content: center; align-items: center;</code>.</li>\n<li><code>float, clear, vertical-align</code> have no effect on a flex item.</li>\n</ul>\n<h2>Resources</h2>\n<ul>\n<li><a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\"><strong>Complete Guide to Flexbox</strong></a></li>\n<li><a href=\"https://yoksel.github.io/flex-cheatsheet/\"><strong>Flex Cheatsheet</strong></a></li>\n<li><a href=\"https://www.w3schools.com/css/css3_flexbox.asp\"><strong>W3 Schools Flexbox</strong></a></li>\n<li><a href=\"https://www.freecodecamp.org/news/css-flexbox-tips-and-tricks/\"><strong>CSS Flexbox Tips and Tricks</strong></a></li>\n<li><a href=\"https://flexboxfroggy.com/\"><strong>Flexbox Froggy: Learn Flexbox by Playing</strong></a></li>\n</ul>"},{"url":"/posts/2020-08-31-big-o/","relativePath":"posts/2020-08-31-big-o.markdown","relativeDir":"posts","base":"2020-08-31-big-o.markdown","name":"2020-08-31-big-o","frontmatter":{"title":"Simply BIG-O","template":"post","date":"2020-08-31 09:31:03 -0400","permalink":"big-o","filename":"2020-08-31-big-o"},"html":"<blockquote>\n<p>If you apply to 100 companies, it can be that 1% would actually get back to you. This could be the case if you're starting as a software developer. With that 1% you really need to be good at algorithms to take advantage of those precious opportunities. </p>\n</blockquote>\n<h1>Simply BIG-O</h1>\n<p>If you apply to 100 companies, it can be that 1% would actually get back to you. This could be the case if you're starting as a software developer. With that 1% you really need to be good at algorithms to take advantage of those precious opportunities. </p>\n<p><strong>What is good code?</strong></p>\n<p>It usually means Readable and Scalable. <em>BIG-O means  scalable code</em>:</p>\n<ul>\n<li>Scalable means speed. It also means memory. </li>\n<li>What's the memory usage of code? You can use Big-O for this too. </li>\n<li>Memory vs. Speed is usually a sacrifice. You get better speed (performance) but you might have more memory.  </li>\n</ul>\n<p><em>Note</em>: Faster code (in terms how long it takes to compile) also depends of what CPU you have, the server etc. So it's hard to measure good code in terms of how 'fast' it performs.</p>\n<p><strong>What is Big-O?</strong></p>\n<p>Big-O means as inputs grows, how much does your function slow down? As elements, input increases how many <em>operations</em> does your function has to do?</p>\n<ul>\n<li>The slower it slows down, the better.</li>\n<li>Big-O calculates the number of steps and calculations <em>not</em> time it takes to run.</li>\n</ul>\n<p>Big-O is important for big applications. Scalable code is thinking long term. Since we cannot pin down the exact runtime (in seconds) of an algorithms we measure how <em>quickly the runtime grows in relation to its input and as the input gets immensely large</em>.</p>\n<p>Good developers make these decisions efficiently. Big-O can give us reliable data in terms of <em>Time Complexity</em>. At the end of this article we'll discuss about Space Complexity as well.</p>\n<p>As we drill down on Big-O notations, please refer to the <a href=\"https://www.bigocheatsheet.com/\">Big-O Cheatsheet</a> and to the graph below:</p>\n<p><img src=\"https://user-images.githubusercontent.com/15071636/85084334-1db98980-b19a-11ea-8b28-d5e2076dc251.png\" alt=\"Screen Shot 2020-06-18 at 7 29 26 PM\"></p>\n<p>Have in mind that we <em>cannot express speed in seconds</em>. The size of the input we usually call it <code>n</code>. And the relationship with the algorithm so we could say for example our runtime grows lineally to the size of the input as O(n) or of the square of the size of the input as O(n^2). </p>\n<p>With that in mind, let's go through each of these Big-O examples. </p>\n<h3><code>O(n)</code> - Linear - PREFERRED</h3>\n<p>This is <strong>linear</strong>. As the number of elements increase so does the number of operations. Example:</p>\n<pre><code class=\"language-javascript\">function findingNemo(message, array) {\n let t0 = performance.now()\n for (let i = 0; i &#x3C; array.length; i++) {\n     if (array[i] === 'nemo' || array[i] &#x3C;= 40) {\n     console.log(message, 'Found NEMO!');\n     break;\n     }\n }\n // Time is just for demo purposes.\n let t1 = performance.now() \n console.log(t1-t0, 'miliseconds')\n }\n\nconst nemo = ['nemo'];\nconst large = Array.from({length: 40000}, () => \n   Math.floor(Math.random() * 40000\n));\n\nfindingNemo('With Nemo: ', nemo); \nfindingNemo('Larger Array: ', large); \n</code></pre>\n<p>If you run this you might notice that the time varies a lot. Again there are CPU, processor and other considerations that makes it hard to evaluate performance in terms of time. That is why we use Big-O and with this algorithm we say it is O(n).</p>\n<h3><code>O(1)</code> - Constant Time - EXCELLENT</h3>\n<p>With O(1) it will always be the same calculation no matter how big the input grows.</p>\n<pre><code class=\"language-javascript\">  function OnFn(box) {\n      console.log(box[1])\n  }\n</code></pre>\n<p>Note the 1 is arbitrary. This can be O(2), O(3) but do narrow it down to O(1), to represent constant time. O(1) is used with Objects/Hash Tables data structures.</p>\n<h3><code>O(n^2)</code> - Nested Loops - BAD</h3>\n<p>If you see nested loops you it is O(n^2). Performance decreases n^2 as input grows, so it is not lineally.</p>\n<p><strong>You might get interview questions to make O(n^2) into an O(n) or better</strong>. Here's an example:</p>\n<pre><code class=\"language-javascript\">//Log all pairs of an array\n\nconst boxes = ['a', 'b', 'c', 'd', 'e'];\nfunction logAllPairsArray(array) {\nfor (let i = 0; i &#x3C; array.length; i++) {\n  for (let j = 0; j &#x3C; array.length; j++) {\n  console.log(array[i], array[j])\n  }\n}\n}\n// nested loops so O(n^2)\nlogAllPairsArray(boxes)\n</code></pre>\n<h3><code>O(log n)</code> - EXCELLENT - Used in Tree Data Structures</h3>\n<p>There is a certain way to calculate number of nodes of perfect binary trees:</p>\n<ul>\n<li>\n<p>You calculate 2 to the power of level in question.</p>\n<ul>\n<li>E.g. Level 0: 2^0 = 1. Number of nodes: 1. Lvl 2: 2^2 = 4. etc.</li>\n<li>Based on this formula you can do 2^treeHeight, to know how many total nodes. E.g. 3 Level Tree: 2^3 - 1 = 7 nodes.</li>\n<li>We can simplify as <strong>log notes = treeHeight</strong>. So you by knowing this, you can limit steps by going in one branch.</li>\n<li>So O(log n) is like <strong>divide and conquer</strong>. Choice of next element is one of several. We only choose one not all. </li>\n<li>This like <strong>looking through a phone book</strong>. You look based upon the names you want. So <strong>divide an conquer</strong>. Only need to explore subset of tree.</li>\n<li>Binary search trees allows us to search efficiently. Google uses this method too.</li>\n</ul>\n</li>\n</ul>\n<p>If this sounds too complicated. Don't worry it sounds for me too 😅.</p>\n<h3><code>O(2^n)</code> Exponential time - PRETTY BAD - Worst Than O(n^2)</h3>\n<p>A classic example is the fibonacci with recursion:</p>\n<pre><code class=\"language-js\">function fibonacci(num){\n  if (num &#x3C;= 1){\n      return num\n  }\n\n  return fibonacci(num - 2) \n    + fibonacci(num - 1)\n}\n</code></pre>\n<h3><code>O(n log n)</code> - OK - Better than O(n^2) but worst than O(n)</h3>\n<ul>\n<li>This performs better than others.</li>\n<li><strong>Divide and conquer: Merge sort and quick sort use this conquer along with recursion</strong>.</li>\n<li>These <strong>don't have nested loops</strong>. See merge / quick sort for example.</li>\n<li>This O(n log n) is because it is still compared, everything at least once, but it is not compared everything to everything.</li>\n</ul>\n<pre><code class=\"language-javascript\">  // O(2^n)\nfunction fibonacciRecursive(n) {\n  if (n &#x3C; 2){\n      return n;\n  }\nreturn fibonacciRecursive(n - 1) \n  + fibonacciRecursive (n - 2)\n}\n\nfibonacciRecursive(6)\n</code></pre>\n<h3><code>O(n!)</code> - Factorial Time - MOST Expensive One</h3>\n<p>It means you add a nested loop for every input. You probably would never see it.</p>\n<h2>BIG-O RULES</h2>\n<ol>\n<li>\n<p><strong>Worst Case</strong>: Big-O looks at the worst case only.</p>\n<ul>\n<li>Identify worst case. You could have O(1) but if O(n), then the Big-O is O(n).</li>\n</ul>\n</li>\n<li>\n<p><strong>Remove Constants</strong>.</p>\n<ul>\n<li>Identify things that don't change and remove them.</li>\n<li>E.g. you have two loops and so O(2n) but 2 is constant so it's actually O(n)</li>\n</ul>\n</li>\n<li><strong>Different terms for inputs</strong></li>\n</ol>\n<pre><code class=\"language-javascript\">function compressBoxesTwice(box1, box2)\nbox1.forEach(b => {\n       console.log(b)\n\n})\nbox2.forEach(b => {\n       console.log(b)\n\n})\n</code></pre>\n<p><em>This is actually O(a + b) NOT O(n)</em>. This because of different terms for inputs. </p>\n<ul>\n<li>If parallel loops you <em>add</em>. E.g. a + b. </li>\n<li>If nested loops you <em>multiply</em>. E.g. a * b</li>\n<li><strong>Drop Non-Dominants</strong></li>\n</ul>\n<pre><code class=\"language-javascript\">function printNumsThenAllPairSums(numbers) {\n\nconsole.log('these are the numbers:');\nnumbers.forEach(function(number) {\n   console.log(number);\n});\n\nconsole.log('and these are their sums:');\nnumbers.forEach(function(firstNumber) {\n   numbers.forEach(function(secondNumber) {\n   console.log(firstNumber + secondNumber);\n   });\n});\n}\n\nprintNumsThenAllPairSums([1,2,3,4,5])\n</code></pre>\n<ul>\n<li>This could be as <code>O(n + n^2)</code>. But you need to drop non-dominants. n^2 is more important since it is worst. So drop <code>n</code> and it will be as <code>O(n^2)</code>. </li>\n<li>Worry about the MOST important then drop the rest.</li>\n<li>Focus on dominant terms.</li>\n</ul>\n<h3>Space Complexity (Memory)</h3>\n<p>When a program executes it will <strong>heap</strong> (store variables) or <strong>stack</strong> (keep track of function calls).\nYou also look at total size and see how much memory is being used.</p>\n<p>What adds space complexity?</p>\n<ul>\n<li>Adding variables</li>\n<li>Adding data structures</li>\n<li>Function calls and allocations</li>\n</ul>\n<p>Space complexity refers to additional space. Example:</p>\n<pre><code class=\"language-javascript\">// Space complexity O(n)\nfunction sayHola(n) {\n  var holaArray = [];\n  for (let i = 0; i &#x3C; n; i++) {\n      holaArray[i] = 'hola👋🏼';\n  }\n  return holaArray;\n}\n\nsayHola(100)\n</code></pre>\n<p>Remember that tradeoff of optimizing code it is often that it <em>will increase space complexity</em>.</p>\n<h2>Final Notes</h2>\n<p><strong>For Technical Interviews</strong>: Sometimes optimizing might not be the right choice at beginning. Get the problem solved first. In interviews most of time you'll wanna do <code>O(n)</code> and <code>O(1)</code>!</p>\n<p>You also need to get the right balance between run time, space and readability. Big-O is crucial for bigger apps, still you need to work and understand it. It will make you a better engineer. </p>\n<p><strong>How to Start</strong>: Focus on <code>O(1)</code>, <code>O(n)</code> and <code>O(n^2)</code> then expand into others.</p>\n<h2>Read More</h2>\n<ul>\n<li><a href=\"https://www.digitalocean.com/community/tutorials/js-big-o-notation\"><strong>Understanding Big O Notation via JavaScript</strong></a></li>\n<li><a href=\"https://www.udemy.com/course/master-the-coding-interview-data-structures-algorithms/\"><strong>Master The Coding Interview</strong></a></li>\n<li><a href=\"https://dev.to/b0nbon1/understanding-big-o-notation-with-javascript-25mc\"><strong>Understanding Big-O Notation With JavaScript</strong></a></li>\n</ul>"},{"url":"/posts/2020-09-14-data-structures_pt1/","relativePath":"posts/2020-09-14-data-structures_pt1.markdown","relativeDir":"posts","base":"2020-09-14-data-structures_pt1.markdown","name":"2020-09-14-data-structures_pt1","frontmatter":{"title":"Learning About Data Structures Part 1","template":"post","date":"2020-09-14 07:31:03 -0400","permalink":"data-structures_pt1","filename":"2020-09-14-data-structures_pt1"},"html":"<blockquote>\n<p>Learning about data structures is an essential part of becoming a more experienced developers. Such knowledge will also help you to be a better problem solver. </p>\n</blockquote>\n<h1>Learning About Data Structures Part 1</h1>\n<p>Learning about data structures is an essential part of becoming a more experienced developer. Such knowledge will also help you to be a better problem solver. </p>\n<p>While reading this article have this in mind:</p>\n<p><code>Programs = Data Structures + Algorithms</code></p>\n<p>OR</p>\n<p><code>Data Structures + Algorithms = Programs</code></p>\n<h2>What are Data Structures (DS)</h2>\n<p>If you know about data structures you can adapt to other coding problems and languages. If you know the fundamentals then you can make decisions in different areas.</p>\n<p>Data Structures (DS):</p>\n<ul>\n<li>Collection of values, you can have functions apply to them. Each one is different of what it can do.</li>\n<li>They are specialized to do certain things. like tools. Most of the time they are prebuilt.</li>\n<li>You can put things in DS and take them out.</li>\n<li>\n<p>There are <strong>ton of Data Structures</strong>. Most of them you wouldn't encounter them most of the time.</p>\n<ul>\n<li>E.g. Blockchain is a DS a way to hold info, Arrays and Objects in JS are DS.</li>\n</ul>\n</li>\n<li>There are always <strong>tradeoffs</strong>. Just like readability, memory and speed. </li>\n<li>\n<p>Common DS questions: </p>\n<ul>\n<li>How to build one?</li>\n<li>How to use it?</li>\n</ul>\n</li>\n<li>Each language has <strong>data structures to organize data types</strong>.   </li>\n<li>With each data structure you can do access, search, insertion, deletion, sort. Each data structure might be good for one or the other. See <a href=\"https://www.bigocheatsheet.com/\">Big-O CheatSheet</a>.</li>\n</ul>\n<h2>Computers and Data</h2>\n<ul>\n<li>Variables are stored in RAM and is not persistent. Storage is persistance. RAM is faster than regular storage (e.g Hard Drive)</li>\n<li>RAM is like a shelf with a lot of info. Each shelf holds 1 byte of storage.</li>\n<li>DS in modern PCs are stored in different ways. E.g. a variable as number can stored in 32 bits or 4 bytes.</li>\n<li>Each data type has a number of bits and allocated on the system. Some data structures are organized next to each other others more apart. That is why DS are powerful, thinking a bit low level.</li>\n<li>This could help us write great code.</li>\n<li>In JS we could build our own data structures such as stacks as they are not included.</li>\n</ul>\n<h2>Arrays</h2>\n<ul>\n<li>Arrays are stored in sequential order, and have <strong>smallest footprint</strong>.</li>\n<li>Array methods like lookup are fast <code>O(1)</code>. Push <code>O(1)</code>. </li>\n<li>Unshift or splice is <code>O(n)</code>: so we think add items at beginning, or deleting for is not the best data structure to do so.</li>\n</ul>\n<p><strong>Static vs Dynamic Arrays</strong></p>\n<ul>\n<li><em>Static</em>: you specify array and items. We copy array to new location to allocate space with new item in sequential order. C++ does this.</li>\n<li><em>Dynamic</em>: Allow not think about memory and machine takes care of it. Like JS.</li>\n</ul>\n<p>With this in mind <code>push</code> can also be O(n). JS usually doubles space when creating array and if you <code>push</code> JS could copy the array again and allocate new space.</p>\n<h1>Hash Tables / (Objects in JS)</h1>\n<p>Like hashes in Ruby. They are referred as objects in JavaScript. </p>\n<ul>\n<li>\n<p>Hash Tables allow to set key/value pair.</p>\n<ul>\n<li>With hash tables key is like our index in arrays.</li>\n<li>This is done through a hash function.</li>\n</ul>\n</li>\n<li>\n<p>Hash Functions:</p>\n<ul>\n<li>Functions that generates a value of fix length for every input received.</li>\n<li>Idempotent: an function that given an input always has the same output.</li>\n</ul>\n</li>\n<li>\n<p>Hashes could be a bit slower because of hash functions.</p>\n<ul>\n<li>We need them to be really fast then. The hashing function then is really fast.</li>\n</ul>\n</li>\n<li>When declared hash properties are created somewhere in memory.</li>\n<li>Accessing properties some cases can be O(1)</li>\n<li>\n<p><strong>Probably the most common interview question</strong>.</p>\n<ul>\n<li>Optimizing nested loops <code>O(n^2)</code> to <code>O(n)</code> with hash tables.</li>\n</ul>\n</li>\n</ul>\n<p>Remember: </p>\n<ul>\n<li>Hashes have fast lookups, fast inserts, and flexible keys.</li>\n<li>However they are unordered and have slow key iteration.</li>\n<li>With hash tables we <strong>increase space complexity (tradeoff)</strong>.</li>\n</ul>\n<p><strong>Hash Collisions</strong></p>\n<ul>\n<li>Nothing tells the hash function to evenly distribute data.</li>\n<li>\n<p>Sometimes collisions occur. This is inevitable.</p>\n<ul>\n<li>When two data are stored in same memory spaces, hashes needs to do something to deal with it.</li>\n<li>Hash collisions theoretically <strong>slows downs reading and writing as O(n)</strong></li>\n<li>You can deal with collisions many ones one of them is linked lists.</li>\n</ul>\n</li>\n<li>So lookups in hash tables occasionally are <code>O(n)</code>.</li>\n<li>As hashes do not have order, JS in ES6 implemented ways to have order such as Map() and Set() which are particular hashes/objects.</li>\n</ul>\n<p><strong>Hash Tables vs Arrays</strong></p>\n<ul>\n<li>Hash tables allow very fast quick access to items <code>O(1)</code>. Arrays in search are <code>O(n)</code>.</li>\n<li>Most of the time in hash tables insert is O(1), although there are collisions.</li>\n<li>Arrays are placed next to each other and not order. Hash tables are kind of all over the place.</li>\n</ul>\n<h2>Hashes and Arrays Questions Examples</h2>\n<p>Note: Usually string questions are <strong>array questions</strong>. Like reversing strings etc. If you cannot see question examples below, click <a href=\"https://repl.it/@fbohz/DataStructuresBlogQA#index.js\">here</a>. </p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/DataStructuresBlogQA?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h2>Linked Lists</h2>\n<ul>\n<li>Two types: Singly and doubly.</li>\n<li>Remember arrays had bad performance with insert and delete and they had to re-arrange themselves in memory once in a while. </li>\n<li>Hashes brought problems like ordering. Hashes can be solved by linked lists.</li>\n</ul>\n<p>What is a linked list?</p>\n<ul>\n<li>Link lists have pointers to next node.</li>\n<li>First node is called the head, and the last is usually the last node.</li>\n<li>Linked lists are <strong>null terminated</strong> so the tail <strong>points to null</strong></li>\n<li>So these lists are simply elements that link to each other and the last points to null.</li>\n</ul>\n<pre><code class=\"language-javascript\">    linkedList: apples --> grapes --> pears\n\n    apples\n    8947 --> grapes\n             8742 --> pears\n                       372 --> null\n</code></pre>\n<p>Javascript <strong>doesn't have linked lists</strong> but <strong>we can build them</strong>.</p>\n<p><strong>Linked Lists vs Array vs Hashes</strong></p>\n<ul>\n<li>In link list you start at head then traverse / iterate as needed until hit null</li>\n<li>Array are located next to each other, linked lists are all over kind of like hashes</li>\n<li>Inserts in middle of linked lists are better than arrays.</li>\n<li>Linked lists have advantages from hash tables that it can sort data.</li>\n<li>Prepend and append is <code>O(1)</code>, lookup, insert, delete is <code>O(n)</code>. </li>\n</ul>\n<p>What is a pointer? Is a reference to another in memory. Example: </p>\n<pre><code class=\"language-javascript\">  const o1 = {a: true}\n  // o2 has a pointer to o1 in memory, NOT copying it.\n  const o2 = o1\n  o1.a = false\n  console.log('1', o1)\n  console.log('2', o2)\n  // => should log false both, since its a pointer.\n</code></pre>\n<p>If you delete the pointer then the reference sticks. There's garbage collection in JS.</p>\n<h2>Building our JS Linked List</h2>\n<p>Check below or click <a href=\"https://repl.it/@fbohz/BlogLinkedLists\">here</a> for the code.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogLinkedLists?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<ul>\n<li><code>insert()</code> is the hardest method to implement in linked lists.</li>\n<li>All you're doing is <strong>removing pointers</strong> or <strong>adding pointers</strong> as a way to add or delete from linked lists</li>\n<li><strong>How is inserting and deleting O(1)?</strong> One step to add a new item, constant time, independent of total list length, therefore <code>O(1)</code>.</li>\n<li>If you were to implement the Stack as an array, you could add the element to the far end of the array and keep a length count. That’s also O(1). However, you’d need to prebuild the array to some maximum length otherwise you’d have to copy its contents to a new larger array when it was filled up. That copy counts as part of the computational work in maintaining the stack, so it’s <code>O(n)</code>.</li>\n</ul>\n<p>Read more: <a href=\"https://www.quora.com/How-is-inserting-into-a-linked-list-O-1-I-dont-understand-how-this-is-the-worst-case\">https://www.quora.com/How-is-inserting-into-a-linked-list-O-1-I-dont-understand-how-this-is-the-worst-case</a></p>\n<h2>Doubly Linked Lists</h2>\n<ul>\n<li>In doubly link lists the difference is that <strong>there is a extra piece of data that points to previous node. So you can reverse</strong>.</li>\n<li>In doubly you can traverse backwards. </li>\n<li>Searching can be more efficient than singly linked list.</li>\n<li>However you <strong>increase space complexity</strong>.</li>\n</ul>\n<h3>Converting Single to Doubly Linked list</h3>\n<p>Check below or click <a href=\"https://repl.it/@fbohz/BlogLinkedLDoubly\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogLinkedLDoubly?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n  \n## Singly vs Doubly Linked Lists\n<ul>\n<li>Singly requires less memory. <strong>Could be a bit faster than doubly</strong>.</li>\n<li>Singly is used for expensive memory and not that much searching.</li>\n<li>With doubly you can delete, insert backwards as needed. But there's more space complexity.</li>\n<li>With doubly you can delete fairly easy. They are good with good operations for searching.</li>\n<li>Most of the time the questions are theoretical and about singly linked lists.</li>\n</ul>\n<h2>Linked Lists: Interview Questions</h2>\n<p>Reverse singly list. Create method reverse() that will reverse singly list. See below or click <a href=\"https://repl.it/@fbohz/BlogLinkLQA#index.js\">here</a>:</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogLinkLQA?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h2>Linked Lists Conclusion</h2>\n<ul>\n<li><code>reverse()</code> method above is probably the most difficult concept in data structures.</li>\n<li>Linked Lists are low level DS. Used in hashes and stacks.</li>\n<li>Linked Lists have slow lookup and more memory. But they are ordered, fast deletion/insertion and flexible size.</li>\n<li>Linked Lists working with them can be difficult to manage all pointers but <strong>linked lists are useful in implementing browsing history, file systems etc</strong>.</li>\n<li>You might want to use linked lists when deleting in hash tables, but this is up to you.</li>\n</ul>\n<p>In our next chapter, things will get more interesting. So stay tuned for more data structures! 💫</p>"},{"url":"/posts/2020-09-07-unix_cheatsheet/","relativePath":"posts/2020-09-07-unix_cheatsheet.markdown","relativeDir":"posts","base":"2020-09-07-unix_cheatsheet.markdown","name":"2020-09-07-unix_cheatsheet","frontmatter":{"title":"Unix Cheatsheet🤓📗","template":"post","date":"2020-09-07 07:31:03 -0400","permalink":"unix_cheatsheet","filename":"2020-09-07-unix_cheatsheet"},"html":"<blockquote>\n<p>Following in our cheatsheet series. We now tackle into Unix. As Web developers we live a lot in the terminal so knowing Unix commands is a key skill, so let's dive in!</p>\n</blockquote>\n<h1>Unix Cheatsheet 🤓📗!</h1>\n<p>Following in our cheatsheet series. Today we tackle into Unix. As Web developers we live a lot in the terminal so knowing Unix commands is a key skill. Let's dive in!</p>\n<h2>Terminal Basic Commands</h2>\n<p><strong>Every command line command is actually a little computer program</strong>, even with simple commands. These commands tend to have the following structure:</p>\n<pre><code class=\"language-js\">    [command][options][arguments]\n</code></pre>\n<p>Starting Tip: Your home directory (<code>~</code>) is the directory where your terminal always starts.</p>\n<p><strong>Basics Cheats</strong></p>\n<ul>\n<li>Exit terminal with <code>Ctrl + D</code></li>\n<li>Press <code>tab</code> when writing and will autocomplete.</li>\n<li><code>ls -l</code>: long detailed info</li>\n<li><code>wc</code>: word count. e.g. <code>wc todo.txt</code></li>\n<li><code>cat</code>: The cat command is often used to print text files to the terminal, despite the fact that it’s really meant to <strong>concatenate files</strong>. E.g. <code>cat todo.txt todo2.txt</code></li>\n<li>You can see the contents of the file you created using either the <code>cat</code> to display the contents, or <code>less</code> to open the file for viewing. After viewing with <code>less</code>, remember that you should hit <code>q</code> to get back to the terminal.</li>\n<li><code>head</code> and <code>tail</code>: There are also two easy to remember programs for glimpsing the beginning or end of a text file: head and tail.</li>\n<li>\n<p><code>></code> output direction: One easy way to create a file is using <strong>output redirection</strong>. Output redirection stores text that would be normally printed to the command line in a text file. You can use output redirection by typing the greater-than sign (>) at the end of a command followed by the name of the new file that will contain the output from the proceeding command. E.g. <code>echo \"I'm in the file.\" > echo-out.txt</code></p>\n<ul>\n<li>You can also append text to the <strong>end of a file</strong> using two greater-than signs <em>(>>).</em> Let’s try this feature out: <code>echo \"I have been appended.\" >> echo-out.txt</code></li>\n</ul>\n</li>\n<li>\n<p>Edit files:</p>\n<ul>\n<li>use <code>nano</code>: Control + O in order to save the changes you’ve made to the text file, or Control + X in order to exit nano and go back to the prompt.</li>\n</ul>\n</li>\n</ul>\n<p><strong>Migration and Destroy</strong></p>\n<ul>\n<li>\n<p>Use cmd <code>mv</code> to move things</p>\n<ul>\n<li>Also <code>mv</code> can <em>rename</em> things as second argument. E.g.  <code>mv todo.txt todo2.txt</code></li>\n</ul>\n</li>\n<li>\n<p><code>cp</code> copies, first argument the file you want to copy the second the location. <code>cp hi.txt Desktop</code></p>\n<ul>\n<li><code>-r</code> option, ensures that the underlying directory structure of the directory you wish to copy remains intact.</li>\n</ul>\n</li>\n<li>\n<p>Delete <strong>(not recommended)</strong></p>\n<ul>\n<li>Use <code>rm</code> command. Be careful in terminal there's no undo button. E.g. <code>rm text.txt</code></li>\n</ul>\n</li>\n</ul>\n<h2>More Cheats</h2>\n<ul>\n<li>\n<p><em><code>man</code> command</em>: Each of the commands that we’ve discussed so far are thoroughly documented, and you can view their documentation using the man for <em>manual</em> command, where the first argument to man is the command you’re curious about.</p>\n<ul>\n<li>e.g. <code>man</code> ls</li>\n</ul>\n</li>\n<li>You could type <code>apropos editor</code> into the command line which will print a list of results</li>\n<li>\n<p><code>less</code> command</p>\n<ul>\n<li>Once you’ve opened a log file (or any file) using less file-name, use the following keys to search. Please note that the match will be highlighted automatically by default.</li>\n</ul>\n</li>\n</ul>\n<p>Forward Search:</p>\n<ul>\n<li><code>/</code>: search for a pattern which will take you to the next occurrence.</li>\n<li><code>n</code>: for next match in forward</li>\n<li><code>N</code>: for previous match in backward\nBackward Search</li>\n<li><code>?</code>: search for a pattern which will take you to the previous occurrence.</li>\n<li><code>n</code>: for next match in backward direction</li>\n<li><code>N</code>: for previous match in forward direction</li>\n<li>The <strong><code>*</code> (“star”) wildcard</strong> represents zero or more of any character, and it can be used to match names of files and folders in the command line. For example if I wanted to list all of the files in my Photos directory which have a name that starts with “2017” I could do the following <code>ls 2017 *</code></li>\n</ul>\n<p><strong>Searching</strong></p>\n<ul>\n<li><code>grep</code>: used to search <strong>within</strong>. <code>grep \"California states.txt</code></li>\n<li><code>find</code>: you can find files with any flags. <code>find . -name \"*.jpg\"</code></li>\n<li>\n<p><code>history</code>: shows history of your commands.</p>\n<ul>\n<li><code>head -n 5 ~/.bash_history</code> look for recent history and <strong>access actual file</strong>.</li>\n<li>history does not show the content of ~/.bash_history. Instead, it shows the current content of Bash's history list in memory for this session.</li>\n</ul>\n</li>\n<li>\n<p><code>~/.bash_profile</code></p>\n<ul>\n<li>The ~/.bash_profile is a list of Unix commands that are run every time we open our terminal, usually with a different command on every line. </li>\n<li>One of the most common commands used in a ~/.bash_profile is the alias command, which creates a shorter name for a command. E.g. <code>alias docs='cd ~/Documents'</code> now you can use it with <code>docs</code>.</li>\n</ul>\n</li>\n<li>\n<p><em>Differences in files</em></p>\n<ul>\n<li><code>diff</code>: <code>diff first.txt second.txt</code></li>\n<li>We could also compare differing lines in a side-by-side comparison using sdiff: <code>sdiff four.txt six.txt</code></li>\n<li>we could do checksum with <code>md5</code>.  E.g. <code>md5 states.txt</code>. Same with <code>shasum</code>.</li>\n</ul>\n</li>\n<li>\n<p>Using pipes <code>|</code>: The pipe allows us to take the output of a command, which would normally be printed to the console, and use it as the input to another command. It’s like fitting an actual pipe between the end of one program and connecting it to the top of another program. You use it with <code>grep</code>.</p>\n<ul>\n<li>E.g. count all names that end in vowel: <code>grep \"[aeiou]$\" index.html | wc -l</code></li>\n</ul>\n</li>\n<li>\n<p><code>makefile</code></p>\n<ul>\n<li>You would get all files then cd into directory, get a makefile and run make.</li>\n<li>E.g. <code>cd ~/Documents/Bio makefile install.make</code></li>\n</ul>\n</li>\n</ul>\n<h2>Resources</h2>\n<p>Read this <a href=\"https://www.digitalocean.com/community/tutorials/basic-linux-navigation-and-file-management\">article</a>.</p>"},{"url":"/posts/2020-10-27-technical_interviewing_tips/","relativePath":"posts/2020-10-27-technical_interviewing_tips.markdown","relativeDir":"posts","base":"2020-10-27-technical_interviewing_tips.markdown","name":"2020-10-27-technical_interviewing_tips","frontmatter":{"title":"Beating The Technical Interview","template":"post","date":"2020-10-27 09:31:03 -0400","permalink":"technical_interviewing_tips","filename":"2020-10-27-technical_interviewing_tips"},"html":"<blockquote>\n<p>In the last couple of months I’ve had the opportunity to interview with many companies...Today I’ll talk about some interviewing tips when tackling with such technical questions!</p>\n</blockquote>\n<h1>Beating The Technical Interview</h1>\n<p>In the last couple of months I've had the opportunity to interview with many companies (couple of even had a FANG 🧛🏼‍♂). Today I'll talk about some interviewing tips when tackling with such technical questions!</p>\n<p><strong>Knowing How to Solve Coding Problems</strong></p>\n<ul>\n<li>This is what will set you apart from others.</li>\n<li>Thought process is important in a coding interview.</li>\n<li>You must understand tradeoffs.</li>\n</ul>\n<h2>What To Expect</h2>\n<p>When called for an interview, you can expect one (or a combination) of the following formats:</p>\n<ul>\n<li>\n<p>Coding challenges</p>\n<ul>\n<li>Week long coding (or data) project</li>\n<li>Timed technical assessment</li>\n<li>HackerRank, CoderPad or Codility challenge</li>\n<li>Data science case study</li>\n</ul>\n</li>\n<li>\n<p>Technical phone screens</p>\n<ul>\n<li>Trivia</li>\n<li>Pair-programming</li>\n</ul>\n</li>\n<li>\n<p>In-person technical interviews</p>\n<ul>\n<li>Trivia</li>\n<li>White-boarding</li>\n<li>Pair-programming</li>\n</ul>\n</li>\n</ul>\n<p>Be ready for common questions such as:</p>\n<ul>\n<li>What is your understanding of <em>X_ROLE</em>?</li>\n<li>Describe your ideal day at work?</li>\n<li>Tell me about yourself.</li>\n<li>Why do you think you are great fit for <em>X_ROLE</em>?</li>\n<li>Share your experience with <em>X_TECHNOLOGY</em> (from your resume).</li>\n</ul>\n<p>Make sure you <em>are prepared</em></p>\n<ul>\n<li>\n<p>Know the structure / time-length of the interview.</p>\n<ul>\n<li>Know if your interview is divided in x parts and how long is each part.</li>\n</ul>\n</li>\n<li>Know the position you're interviewing for.</li>\n<li>Research about the company</li>\n<li>Prepare a list of study materials. Include videos, articles, courses etc.</li>\n<li>Practice, practice, practice! Use HackerRank, LeetCode etc.</li>\n</ul>\n<p><strong>What are companies looking for</strong></p>\n<ul>\n<li>Analytic skills: hear your thought process</li>\n<li>Coding Skills: code clean, readable</li>\n<li>Technical skills: do you know the fundamentals</li>\n<li>Communication skills: personality matches company's personality?</li>\n</ul>\n<p>They want smart people that solve problems themselves without having other people to walk them by the hand all the time.</p>\n<h2><em>The Flow</em>: Follow It and You Will Cruise the Interview.</h2>\n<p>As you follow the flow below, refer to <a href=\"https://www.youtube.com/watch?v=4UWDyJq8jZg&#x26;t=7s\">this video</a> for an example coding challenge. </p>\n<p><strong>Ask Questions</strong></p>\n<ul>\n<li>Any restrictions? Any additional info I need?</li>\n<li>What data structure, is it an array, object?</li>\n<li>Is data in sorted? Are there duplicates?</li>\n<li>Are you getting one data structure or two?</li>\n<li><em>Repeat the question to the interviewer</em>.</li>\n</ul>\n<p><strong>Talk out the Solution</strong></p>\n<ul>\n<li>\n<p>You can diagram an example data with as much info as possible.</p>\n<ul>\n<li>Depict example in a more visual way. Here e.g line with years.</li>\n</ul>\n</li>\n<li>\n<p>Come up with brute force <em>DON'T CODE YET</em>.</p>\n<ul>\n<li>Go through all years, find alive and get highest population</li>\n<li>Get min birth year and max death year. What's Big-O? O(N).</li>\n<li>Have extra counter for number of peopleAlive ..etc</li>\n</ul>\n</li>\n</ul>\n<p><strong>Brute force</strong></p>\n<ul>\n<li>\n<p>State brute force out-loud then code.</p>\n<ul>\n<li>Ask clarifying questions what if X, what do I return?</li>\n<li>Think about <em>unnecessary work</em>. E.g. do you need to check death year?</li>\n<li>Death decrements population. Birth adds population.</li>\n<li>Ask interviewer if they die that year does the death count that same year or following?</li>\n</ul>\n</li>\n<li>\n<p>Think about your data structure:</p>\n<ul>\n<li>A hash with years: E.g. 1750: 1 birth, 2 deaths and so on.</li>\n<li>Need your min and max birth year since birth is what increments.</li>\n</ul>\n</li>\n</ul>\n<p><strong>Refine solution with style</strong></p>\n<ul>\n<li>\n<p><em>Modularize code</em></p>\n<ul>\n<li>Each code one function.</li>\n<li>It helps you focus on the <em>most interesting things to write</em></li>\n<li>If you modularize you don't have to write all code.</li>\n<li>As you code:</li>\n<li><em>Talk out loud</em> what each function is doing.</li>\n<li>Test code.</li>\n<li>Check for any math.</li>\n</ul>\n</li>\n<li>Yes, <em>test</em> your code. Start with small test cases, then throw larger cases.</li>\n</ul>\n<p><strong>Repeat after me</strong>: <em>A solution (even brute force solution) is better than no solution</em>.</p>\n<h2>Some Reminders</h2>\n<ol>\n<li>Listen, ask questions. <strong>Look for clues</strong>.</li>\n<li>Draw and example. Big and with no special cases.</li>\n<li>Create (<em>don't code</em>) a descriptive solution. Walk through example before coding. State <strong>Brute force algorithm</strong>, if you feel you can do better than brute-force do the latter if not do brute-force. Again, a solution, is better than no solution.</li>\n<li><strong>State Run-Time, Big-O</strong></li>\n<li><strong>Solidify your understanding of algorithm</strong></li>\n<li>Code and optimize as needed.</li>\n<li>Modularize as much as possible.</li>\n<li>Test your code. Simple test cases, then bigger test cases.</li>\n</ol>\n<h2>K.O. Reminders</h2>\n<ul>\n<li>\n<p>In order to solve problems we need to learn Data Structures and Algorithms. 90% of the time you'll use these:</p>\n<ul>\n<li>Data Structures: E.g. arrays, stacks, queues, linked lists, trees, tries graphs, hash tables</li>\n<li>Algorithms: E.g. sorting, dynamic programming, BFS + DFS (searching), recursion</li>\n</ul>\n</li>\n<li><strong>Don't jump straight into coding!</strong> ask questions about parameters, how large are the parameters received, anything as needed. If not very large then you don't have to worry about time vs space complexity and Big-O.</li>\n<li>Stop and question as much as you can (but don't be annoying).</li>\n<li>\n<p>Start with brute force approach:</p>\n<ul>\n<li>Tell interviewer about it. Don't necessarily have to code this part.</li>\n</ul>\n</li>\n<li>Avoid nested loops such as O(n^2) or O(a*b).</li>\n<li>\n<p>Interviewer wants to see:</p>\n<ul>\n<li>You understand problem</li>\n<li>Can solve it naively and brute by thinking it out loud.</li>\n<li>Make logical steps towards the solution.</li>\n<li>Modularize code (pieces of code that do one thing).</li>\n<li>When you have a solution. Talk with interviewer as ways in which it can be broken down.</li>\n<li><strong>AFTER YOU SOLVE IT</strong> you can talk about your thinking and research you might do to make it better. Like ES6+ functions, other data structures that could make it more readable or work better.</li>\n</ul>\n</li>\n<li>Interviewer if satisfied, or out of time, will end the interview accordingly.</li>\n</ul>\n<h2>One Last Thing...</h2>\n<ul>\n<li><strong>Be nice and be a team player</strong>: A lot of times your interviewer wants to see how you perform as a team. This part is hugely underestimated but how your interviewer perceives how you <strong>listen</strong> to them and how you take feedback can have a tremendous effect on whether you'll get or not the job. At the end of the day you will be working with other people, so they want to see not only your coding chops but also that you are a team player and a nice person to be around. If you come off as a jerk they probably would not want to work with you. Don't just pretend to be nice: BE nice and you might be in for a big surprise 😁.</li>\n<li>Practice solving problems <strong>without a text editor</strong> and with a <strong>time limit</strong>.</li>\n<li>Mock interview with a friend.</li>\n<li>Brush up on things you don't know.</li>\n<li>Ask for clarifying questions</li>\n<li><strong>Focus on getting a working solution</strong>. Done is better than perfect.</li>\n<li>\n<p>You <strong>won't know all the answers</strong></p>\n<ul>\n<li>Don't be afraid of say 'I don't know'.</li>\n<li><strong>Make an educated guess</strong>.</li>\n</ul>\n</li>\n<li>If you can, prepare your own questions ahead of time.</li>\n<li><strong>You don't know everything</strong>. You can always follow up with your interviewer with additional details/improvements on a question or technical challenge. It will show your interviewer you are always learning and improving yourself. </li>\n</ul>\n<h2>BONUS: SAMPLE QUESTION</h2>\n<p>I decided to take a chance at the classic Facebook question delineated on <a href=\"https://www.youtube.com/watch?v=4UWDyJq8jZg&#x26;t=7s\">this video</a>.</p>\n<p><strong>The Question</strong></p>\n<p>Given a list of people with their birth and death YEARS, find the (1) year with the highest population.</p>\n<p><strong>The Solution</strong></p>\n<p>I implemented a class-based approach. If you can't see the code below just access it <a href=\"https://repl.it/@fbohz/CodingInterviewQsPractice#index.js\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/CodingInterviewQsPractice?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<p><strong>Note:</strong> There are many variations of this question, and some of them might ask you a different output. Always ask for the edge cases! In this case there were only two test cases with obvious solutions.</p>\n<p>You've got this! 👊🏼</p>\n<h2>Resources</h2>\n<ul>\n<li><a href=\"https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges\"><strong>WomenWhoCodeBoston Github Challenges</strong></a></li>\n<li><a href=\"https://projecteuler.net/\"><strong>Project Euler</strong></a></li>\n<li><a href=\"https://github.com/WomenWhoCodeNYC/Algorithms\"><strong>WomenWhoCodeNYC Algorithms</strong></a></li>\n<li><a href=\"https://www.hackerrank.com/\"><strong>Hackerrank</strong></a></li>\n<li><a href=\"https://interviewing.io/\"><strong>Interviewing.io</strong></a></li>\n<li><a href=\"https://leetcode.com/\"><strong>Leetcode</strong></a></li>\n<li><a href=\"https://coderbyte.com/\"><strong>Coderbyte</strong></a></li>\n<li><a href=\"https://www.careercup.com/\"><strong>Careercup</strong></a></li>\n<li><a href=\"https://algs4.cs.princeton.edu/cheatsheet/\"><strong>Algorithms and Data Structures Cheatsheet</strong></a></li>\n<li><a href=\"https://github.com/sudheerj/javascript-interview-questions\"><strong>JS Interview Questions</strong></a></li>\n<li><a href=\"https://github.com/MaximAbramchuck/awesome-interview-questions\"><strong>Awesome Interview Qs</strong></a></li>\n<li><a href=\"https://online-learning.harvard.edu/course/cs50-introduction-computer-science\"><strong>Intro to Computer Science</strong></a></li>\n<li><a href=\"https://github.com/young/frontend-interviewing/tree/master/questions\"><strong>Frontend Interview Questions</strong></a></li>\n<li><a href=\"https://www.theodinproject.com/courses/getting-hired/lessons/preparing-to-interview-and-interviewing\"><strong>Odin Project's Preparing for Interviews</strong></a></li>\n</ul>"},{"url":"/posts/2020-09-16-data-structures_pt2/","relativePath":"posts/2020-09-16-data-structures_pt2.markdown","relativeDir":"posts","base":"2020-09-16-data-structures_pt2.markdown","name":"2020-09-16-data-structures_pt2","frontmatter":{"title":"Learning About Data Structures Part 2","template":"post","date":"2020-09-16 09:31:03 -0400","permalink":"data-structures_pt2","filename":"2020-09-16-data-structures_pt2"},"html":"<blockquote>\n<p>Learning about data structures is an essential part of becoming a more experienced developer. This is the second part of the series (and will be the longest one), buckle down 🚀.</p>\n</blockquote>\n<h1>Learning About Data Structures Part 2</h1>\n<p>Learning about data structures is an essential part of becoming a more experienced developer. This is the second part of the series (and will be the longest one), buckle down 🚀.</p>\n<h2>Stacks &#x26; Queues</h2>\n<ul>\n<li>Stack and queues are very similar to linear data structures.</li>\n<li>Only difference is how items are removed.</li>\n<li>Stack and queues have less methods. This could be an advantage as it could limit what can be done. </li>\n</ul>\n<p><strong>Stacks are like plates</strong></p>\n<ul>\n<li>You can only touch the first plate, and go one by one. This is <strong>called last in first out (LIFO)</strong></li>\n<li>These are very good to know the very last value.</li>\n<li>Most programming languages have a stack mindset like LIFO.</li>\n</ul>\n<p><strong>Other uses</strong></p>\n<ul>\n<li>Browser history. Undo/Redo. This idea comes from stack. </li>\n<li>Methods are <code>pop()</code> O(1), <code>push()</code> O(1) and <code>peek()</code> O(1). Traverse is not recommended in stack.</li>\n</ul>\n<p><strong>Queues</strong></p>\n<p>Are like an entrance to a rollercoaster. They have a <strong>first in first out (FIFO)</strong></p>\n<p>Uses:</p>\n<ul>\n<li>If you have a wait-list app, could use queues. Restaurant to see if you have table, could use queues. Uber/Lyft uses queues. Printers too.</li>\n<li>Methods are <code>enqueue()</code> O(1), <code>dequeue()</code> O(1) and <code>peek()</code> O(1). Again traversing is not recommended (lookup())</li>\n<li>Dequeue() unlike pop() takes first one out whereas pop() in Stacks takes last.</li>\n</ul>\n<p><em>Reminder</em>: Do not build a queue using arrays since its inefficient.</p>\n<h2>Stack and Queues Implementations</h2>\n<ul>\n<li>\n<p>Stacks: Use Arrays or build out of Linked Lists</p>\n<ul>\n<li><strong>Both work very well.</strong> </li>\n<li>Think about what are your needs.</li>\n</ul>\n</li>\n<li>\n<p>Queues: Also Arrays or through Linked lists. </p>\n<ul>\n<li>Here <strong>Arrays not recommended</strong>. Because you have to traverse O(n) when you shift and remove.</li>\n<li>Use always Linked Lists for queues.</li>\n</ul>\n</li>\n</ul>\n<p>So, how can you build stack and queues using JavaScript?</p>\n<h3>Stack / Queues Example</h3>\n<p>See below or click <a href=\"https://repl.it/@fbohz/BlogStackQueuesEG#index.js\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogStackQueuesEG?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h3>Stack / Queues Review</h3>\n<ul>\n<li>Stacks are like plates. Queues are like waiting lists</li>\n<li>Stacks and Queues are great for removing and inserting. <strong>fast peek</strong></li>\n<li>Data is ordered.</li>\n<li><strong>Do not use Arrays when building queues. Because you have to traverse O(n) when you shift and remove.</strong></li>\n<li><strong>Slow lookup for both.</strong></li>\n</ul>\n<p>For example interview Question check <a href=\"https://leetcode.com/problems/implement-queue-using-stacks/description/\">discussion</a>. Solution below and <a href=\"https://repl.it/@fbohz/BlogQueueUsingStacksQS#index.js\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogQueueUsingStacksQS?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h2>Trees</h2>\n<ul>\n<li>Trees have a hierarchical structure. </li>\n<li>Linked lists, arrays are linear. Linked lists are considered a type of tree</li>\n<li>Trees have <strong>only one parent</strong> and it can <strong>leaf notes</strong></li>\n<li>Within trees you can have <strong>sub trees</strong></li>\n<li>Facebook comments have a tree DS, with comments of comments etc.</li>\n<li>Abstract syntax tree. Code is broken down by a machine as this.</li>\n<li>There are many tree data structures.</li>\n</ul>\n<p>Examples: DOM is a tree data structure. HTML is parent then body is parent with many children.</p>\n<h2>Binary Trees</h2>\n<ul>\n<li>Each node can only have 0,1,2 nodes. Each node represents a certain state.</li>\n<li>Each child can only have one parent.</li>\n<li>\n<p>Types of binary trees:</p>\n<ul>\n<li><strong>Perfect Binary tree</strong> - nodes are full nothing is missing. They are efficient. Number of nodes double as it goes down. Second property states that bottom levels equal top levels + 1. <strong>So there are some efficiencies here</strong> as O(log N)</li>\n<li><strong>Full binary tree</strong> - the opposite and only meets requirements of binary tree.</li>\n</ul>\n</li>\n</ul>\n<h3><code>O(log n)</code>- Reminder</h3>\n<ul>\n<li>\n<p>There is a certain way to calculate num of nodes of perfect binary trees.</p>\n<ul>\n<li>You calculate 2 to the power of level in question.</li>\n<li>E.g. Level 0: 2^0 = 1. Number of nodes: 1. Lvl 2: 2^2 = 4. etc.</li>\n<li>Based on this formula you can do 2^treeHeight - 1 to know how many total nodes. E.g. 3 Level Tree: 2^3 - 1 = 7 nodes.</li>\n<li>We can simplify as <strong>log notes = treeHeight</strong>. So you by knowing this, you can limit steps by going in one branch.</li>\n</ul>\n</li>\n<li>So O(log n) is like <strong>divide and conquer</strong>. Choice of next element is one of several. We only choose one not all. </li>\n<li><strong>Like looking through a phone book</strong>. You look based upon the names you want. So divide an conquer. Only need to explore subset of tree.</li>\n<li>Binary search trees allows us to search efficiently. Google uses this method too.</li>\n</ul>\n<p>If this sounds complicated, try to get the idea to begin with 😅.</p>\n<h2>Binary Search Trees (BST)</h2>\n<p>Most Common Tree Data Structure. What is BST?</p>\n<ul>\n<li>They are <strong>really good at searching</strong> and comparing things.</li>\n<li>BSTs preserves relationships. Like folders, parent folder, sub-folder etc., unlike Hash Tables.</li>\n</ul>\n<p>Visual example:</p>\n<pre><code>      101\n      /  \\\n      33   105\n      / \\    / \\\n      9  37  104 144\n</code></pre>\n<ul>\n<li>Here lookup is very easy you can find by going left of right depending on number.</li>\n<li>Insert and delete are also <code>O(log n)</code>. For example delete 105, decide which node to start.</li>\n<li>Always use traversing and with conditionals saving time to insert, delete.</li>\n</ul>\n<p>Read more: <a href=\"https://visualgo.net/bn/bst?slide=1\">https://visualgo.net/bn/bst?slide=1</a></p>\n<h3>BST Pros and Cons</h3>\n<ul>\n<li>Very good performance better than <code>O(n)</code>, assuming BST is balanced.</li>\n<li>Ordered and flexible size.</li>\n<li><strong>No</strong> O(1) operations, since traversal is required.</li>\n</ul>\n<p><em>Note</em>: BST is not the fastest, sometimes Arrays outperform them.</p>\n<h3>Unbalanced vs Balanced BSTs</h3>\n<ul>\n<li><strong>Unbalanced BST</strong>: Where are the nodes are either on the right or left. Becoming more like linked lists. Unbalanced become O(n) for lookup, insert, delete. </li>\n<li><strong>Balanced (preferred)</strong>: </li>\n</ul>\n<p>How do you balance your trees?\nBy algorithms. Programming languages do provide libraries and tools to help you build them.</p>\n<h3>BST Example In Code</h3>\n<p>See below or click <a href=\"https://repl.it/@fbohz/BlogBST-eg\">here</a>.</p>\n<h3>AVL Trees + Red Black Tree (Balancing Binary Search Trees)</h3>\n<ul>\n<li>These trees are used with a library and balance trees.</li>\n<li>These balance the trees when it finds they are not unbalanced.</li>\n</ul>\n<p>There are resources for you to visualize them:</p>\n<ul>\n<li><a href=\"https://medium.com/basecs/the-little-avl-tree-that-could-86a3cae410c7\">https://medium.com/basecs/the-little-avl-tree-that-could-86a3cae410c7</a></li>\n<li><a href=\"https://medium.com/basecs/painting-nodes-black-with-red-black-trees-60eacb2be9a5\">https://medium.com/basecs/painting-nodes-black-with-red-black-trees-60eacb2be9a5</a></li>\n<li><a href=\"https://www.cs.usfca.edu/~galles/visualization/AVLtree.html\">https://www.cs.usfca.edu/~galles/visualization/AVLtree.html</a></li>\n<li><a href=\"https://www.cs.usfca.edu/~galles/visualization/RedBlack.html\">https://www.cs.usfca.edu/~galles/visualization/RedBlack.html</a></li>\n</ul>\n<p>🤓📗 Always look up how to visualize trees and any data structure in fact. </p>\n<h3>Heaps and Tries</h3>\n<p><strong>Heaps</strong></p>\n<p>Heaps are mostly <em>Binary Heaps</em>.</p>\n<ul>\n<li><strong>Parent greater than children</strong>.</li>\n<li>Like priority queues, sorting algorithms.</li>\n<li>But left and right can be any value. So lookup as <code>O(n)</code> here.</li>\n<li>They are good at doing comparative.</li>\n<li><strong>There's left to right insertion</strong>. You can implement binary heap with arrays.</li>\n</ul>\n<p>Priority Queues:</p>\n<ul>\n<li>Different than queues with FIFO.</li>\n<li><strong>Elements with higher priority are server before than lower priority</strong>.</li>\n<li>\n<p>Example of priority queue:</p>\n<ul>\n<li>Emergency room, airplane boarding.</li>\n</ul>\n</li>\n<li>It gives a sense of structure and order.</li>\n</ul>\n<p><strong>Remember</strong></p>\n<ul>\n<li><code>Memory Heap != Heap Data Structure in JS.</code></li>\n<li>Searching lookup is slower.</li>\n<li>Gives idea of priority.</li>\n<li>Most of the time insert is fast.</li>\n<li>Methods like find max and fin min are available and very fast.</li>\n</ul>\n<p><strong>Trie</strong></p>\n<ul>\n<li>Specialized tree used in searching, most often with text.</li>\n<li>In most cases it outperform most data structures, depending what is doing.</li>\n</ul>\n<p><strong>How Tries work</strong></p>\n<ul>\n<li>Empty root node.</li>\n<li>Letters are added after.</li>\n<li>They are also called <strong>prefixed tree</strong>, like autocompleted.</li>\n<li>Used for searching words on dictionary, word suggestions. </li>\n<li>Lookup here is fast, you look for length then move. Space complexity also has advantages. Prefixes save space.</li>\n</ul>\n<h2>Recap on Trees</h2>\n<ul>\n<li>You need to understand how they work.    </li>\n<li>Try to practice and build one from scratch.</li>\n</ul>\n<p><a href=\"https://github.com/afiore/arboreal\"><strong>Arboreal.js</strong></a> lets you use it and create the tree you want. You won't be creating trees from scratch.</p>\n<h2>Graphs</h2>\n<p>Our last data structure! 🙌🏼</p>\n<p>What are Graphs?</p>\n<ul>\n<li>Graph is a set of values related in pair fashion.</li>\n<li>Like a network</li>\n<li>Each item is called a node or vertex.</li>\n<li>Nodes are connected with edges.</li>\n<li>They model real work relationships. Kind of like how the internet works. </li>\n<li>Used to represent roads, friends. Google maps uses graphs to determine the shortest route.</li>\n</ul>\n<p><strong>Linked lists, trees are a type of graphs!</strong></p>\n<h3>Types of Graphs</h3>\n<p>Directed vs Undirected</p>\n<ul>\n<li>\n<p><strong>Directed</strong>:</p>\n<ul>\n<li>One way street.</li>\n<li>Twitter is more directed if they follow me i don't necessarily follow them</li>\n</ul>\n</li>\n<li>\n<p><strong>Undirected</strong>:</p>\n<ul>\n<li>Two way street.</li>\n<li>Facebook is undirected a friend can be connected to another</li>\n</ul>\n</li>\n</ul>\n<p>Unweighted and Weighted</p>\n<ul>\n<li>Weighted graphs has information in the edges / connections too.</li>\n<li>Google Maps uses weighted graphs. Like fastest way in 1-6.</li>\n</ul>\n<p>Cyclic vs Acyclic</p>\n<ul>\n<li>\n<p>If vertices are connected in a cycle are cyclic.</p>\n<ul>\n<li>Cyclic are common in weighted because there's a way to go back.</li>\n</ul>\n</li>\n<li>Directed Acyclic Graph is common in projects such as IOTA a blockchain project. Many trees can also create this data structure.</li>\n<li>There are some online graph resources you can see and check to test your knowledge.</li>\n</ul>\n<p>Example: <a href=\"https://internet-map.net/\">https://internet-map.net/</a></p>\n<h3>Graph Exercise</h3>\n<p>Building / representing a graph. Considering this graph how can you build it.</p>\n<pre><code>    2 - 0\n    /  \\\n    1   3\n</code></pre>\n<p>Some options:</p>\n<p><strong>Edge List</strong>: Like with an array of arrays. Stating the connections.</p>\n<pre><code class=\"language-javascript\">  const graph = [[0,2], [2,3], [2,1], [1,3]]\n</code></pre>\n<p><strong>Adjacent List</strong>: A graph like array, objects, linked lists. Index is the node, and value is the node neighbors.</p>\n<pre><code class=\"language-javascript\">  const graph = [[2], [2,3], [0,1,3], [1,2]]\n</code></pre>\n<p><strong>Adjacent Matrix</strong>: will only have 0s and 1s if X have connections to note Y. 0 is no Y is yes.</p>\n<pre><code class=\"language-javascript\">  const graph = {\n   0: [0,0,1,0],\n   1: [0,0,1,1],\n   2: [1,1,0,1],\n   3: [0,1,1,0]\n  }\n</code></pre>\n<h3>Graph (Undirected / Unweighted) Implementation:</h3>\n<ul>\n<li>Using adjacency list. <strong>Use a hash table</strong>.</li>\n<li>We use objects because shifting/unshifting in Arrays is expensive.</li>\n</ul>\n<p>See below or click <a href=\"https://repl.it/@fbohz/BlogGraphExample#index.js\">here</a> for the example code.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogGraphExample?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h2>Last Words on Graphs</h2>\n<ul>\n<li>They look pretty complex but they are pretty simple once you have other DS taken care of.</li>\n<li><strong>In interviews graphs aren't that big because it takes time to build them</strong>.</li>\n</ul>\n<p>Learn the fundamentals.</p>\n<ul>\n<li>Think how you hold data in graphs such as adjacency matrix</li>\n<li>Types of graphs. How you can create graphs.</li>\n<li>Performance and Big O is complicated because of so many graphs.</li>\n<li>There are algorithms to help.</li>\n<li>Scaling is hard as you will need a big team to build graph structures that scale well</li>\n</ul>\n<p><a href=\"https://neo4j.com/\"><strong>Neo4j</strong></a> a tool to build complex structures as this.</p>\n<h1>Data Structures (DS) Review</h1>\n<ul>\n<li>Technology is built on data structures. There might be more to come but make sure you have a strong foundation on the basics.</li>\n<li>Anyone can build their own data structure. E.g. with Blockchain we have special hashes, linked lists, tries etc. </li>\n<li>With DS understood now you can take on algorithms, the other piece of the puzzle that many large companies ask.</li>\n<li>Programming languages do provide libraries and tools to help you build many data structures.</li>\n<li>Don't feel you have to reinvent the wheel!</li>\n</ul>\n<p><strong>Remember</strong> all this information is important to know it high level but do not worry if you can't grasp it all. The more you study it and see it and with time concepts will settle in and. In no time you'll be making magic with data structures! 🧙🏾‍♂️</p>"},{"url":"/posts/2020-12-18-algorithms_ch1/","relativePath":"posts/2020-12-18-algorithms_ch1.markdown","relativeDir":"posts","base":"2020-12-18-algorithms_ch1.markdown","name":"2020-12-18-algorithms_ch1","frontmatter":{"title":"On CS Algorithms: Chapter I","template":"post","date":"2020-12-18 19:31:03 -0400","permalink":"algorithms_ch1","filename":"2020-12-18-algorithms_ch1"},"html":"<blockquote>\n<p>Today we'll discuss regarding the last piece of the puzzle on good problem solving in software engineering, namely algorithms. On this first chapter we'll talk about Recursion and Sorting Algorithms.</p>\n</blockquote>\n<h1>On CS Algorithms: Chapter I</h1>\n<p>Today we'll discuss regarding the last piece of the puzzle on good problem solving in software engineering, namely algorithms. On this first chapter we'll talk about Recursion and Sorting Algorithms. These are mostly notes from articles and online courses I've taken. Enjoy!</p>\n<h2>Intro To Algorithms and Recursion Pattern</h2>\n<p>Remember: <code>DS + ALG = programs</code>:</p>\n<ul>\n<li>A two line function is technically an algorithm.</li>\n<li>There are thousands of well established algorithm.</li>\n<li>There are important algorithms we'll learn. </li>\n<li>With good algorithms we can enhance our Big-O</li>\n</ul>\n<p><strong>What is Recursion?</strong></p>\n<ul>\n<li>It's more of a concept, than an algorithm</li>\n<li>Common topic in an interview.</li>\n<li>E.g. type <code>ls -R</code> on terminal in a folder: it will give you all files and folders.</li>\n<li><strong>Recursion is a function that refers to itself inside of the function</strong>. Sounds too philosophical? 🤯</li>\n</ul>\n<p>It can be, recursive function can be easy as this:</p>\n<pre><code class=\"language-javascript\">// Caution: Stack Overflow\nfunction(inception) {\n    inception()\n}\n</code></pre>\n<p>Recursion will be used in searching and sorting algorithms. DOM traversal on a website uses recursion. An object inside of an object you can use recursion.</p>\n<p>Two problems of recursion</p>\n<ul>\n<li>Difficult to understand at first.</li>\n<li><strong>Stack overflow</strong> also could happen. Self calling function could cause your function to ran out your memory. Infinite loops.</li>\n<li>A <strong>base case</strong> will help the recursive function to stop.</li>\n</ul>\n<h2>Anatomy of Recursion</h2>\n<p>Base case will help it stop. An example could be:</p>\n<pre><code class=\"language-javascript\">let counter = 0\nfunction(inception) {\n    if (counter > 3) {\n        return 'done'\n    }\n    counter++\n// will ensure 'done' returned    \n    return inception()\n}\ninception()\n</code></pre>\n<p>Three rules to build recursion:</p>\n<ol>\n<li>Identify the base case</li>\n<li>Identify the recursive case</li>\n<li>Get closer and closer and return when needed. <strong>Usually you have 2 returns</strong>.</li>\n</ol>\n<h3>Recursion Exercise - Factorial</h3>\n<p>A factorial multiplies itself depending on number for example:\n<code>5! = 5 * 4 * 3 * 2 * 1</code></p>\n<p>You can solve this through looping or recursion. See below or click <a href=\"https://repl.it/@fbohz/BlogRecursionEg1#index.js\">here</a>. Note both are <code>O(n)</code>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogRecursionEg1?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h3>Recursion Exercise - Fibonacci</h3>\n<p>Fibonacci adds first two items equals third item. Again this one can be done either loops or recursive. See below or click <a href=\"https://repl.it/@fbohz/BlogRecursionEg2#index.js\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogRecursionEg2?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<h2>Recursion vs Iteration</h2>\n<ul>\n<li><strong>Anything that can be done recursively can be done with a loop (iteratively)</strong></li>\n<li>You can go all life without recursion.</li>\n<li>Thoughts:</li>\n<li><strong>Recursion can keep your code DRY</strong></li>\n<li><strong>Recursion creates an extra memory footprint</strong> and stack overflow</li>\n<li>Takes time to learn.</li>\n<li><strong>So not always a good idea.</strong></li>\n<li><strong>When to use recursion</strong></li>\n<li>When you don't know how deep the data structure is.</li>\n<li>Useful for tree data structure.</li>\n<li>Traversing through trees and graphs, sorting through items.</li>\n</ul>\n<h2>Recursion Tips:</h2>\n<ul>\n<li>Every time <strong>using a tree or converting to a tree consider recursion</strong></li>\n<li>You see a lot of divide and conquer in recursive solutions like a phone-book. These divide and conquer usually have recursive solutions.</li>\n<li>Tail call optimization</li>\n<li>Allows recursion without increasing the call stack. Read <a href=\"https://2ality.com/2015/06/tail-call-optimization.html\">here</a>.</li>\n<li>Great <a href=\"https://stackoverflow.com/questions/105838/real-world-examples-of-recursion\">real world application example</a> of when to use recursion: </li>\n</ul>\n<p>Interview triggers: </p>\n<ol>\n<li>A problem can be divided into small problems, smaller instances of those problems. </li>\n<li><strong>Each of these instances of problems are identical in nature</strong>. Calculations are same over and over</li>\n<li>If you solve smaller problems (leaf notes of tree) and you combine them, that solves problem at hand. </li>\n</ol>\n<p><strong>Conclusion</strong></p>\n<ul>\n<li>Remember try to avoid stack overflow with recursion.</li>\n<li>Use recursion to make code DRY, but be careful with performance in recursion.</li>\n<li>Recursive although expensive, with graphs and sort can use recursion.</li>\n</ul>\n<h1>Sorting</h1>\n<p>Sorting is very important for interviews. But, why you care about sorting if you have <code>sort()</code> in JS?</p>\n<p><strong>Sorting is not a big deal with small input data</strong>. But as it grows it gets more complicated.</p>\n<p>Examples:</p>\n<ul>\n<li>Google needs to sort articles on a particular event in time</li>\n<li>Amazon needs to sort articles</li>\n<li>Netflix needs to show all movies, tv shows.</li>\n</ul>\n<p><strong>All these example cannot use built in sort methods. They need to create their own sort method</strong>.\n<strong>Most scaled companies sort their data</strong>. </p>\n<p>This topic is very important:</p>\n<ul>\n<li>What sorting algorithm you can use depending on the problem.</li>\n<li>There are a lot of sorting algorithms. Most likely you'll never implement your own, except for a small example on an interview.</li>\n<li>The goal is to understand high level these sorting algorithms to talk intelligently on interviews.</li>\n<li>Key to learn as more companies grow, <strong>sorting and searching become more and more crucial</strong>.</li>\n<li>\n<p>We'll go through these sorts:</p>\n<ul>\n<li>Easier to remember, might come up in interviews:</li>\n<li>Bubble Sort, Insertion Sort, Selection Sort</li>\n<li>More complex, more efficient sometimes:</li>\n<li>Merge Sort, Quick sort</li>\n</ul>\n</li>\n</ul>\n<h2>Built-in <code>sort()</code></h2>\n<pre><code class=\"language-javascript\">const basket = [2,65,34,1,6]\nconst sp = ['único', 'árbol', 'cosas']\n\n// to implement sp sort you'll do this:\nbasket.sort((a,b) => {\n    return a - b \n})\nspanish.sort(function(a,b){\n    return a.localCompare(b)\n})\n</code></pre>\n<p>Try running line sort(). You might have surprise because JS converts to string. With JS each browser will use their own ECMAScript implementation so differences might come as well.</p>\n<p>Read more <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\">here</a>.</p>\n<h3>Sorting Algorithms</h3>\n<ul>\n<li>You don't need to write from scratch, more likely ever, but need to know about them.</li>\n<li>Most of the time talk about it, and implement it with frameworks.</li>\n<li><strong>Interviews, will ask you for sure.</strong></li>\n<li>There are Big O tradeoffs when using sorting algorithms.</li>\n<li><a href=\"https://www.toptal.com/developers/sorting-algorithms\">Great learning resource</a>. </li>\n</ul>\n<h2>Bubble Sort - DO NOT USE</h2>\n<ul>\n<li>\n<p>How would you bubble sort: 6,5,4,3,2?</p>\n<ul>\n<li>Compare each one and swap them out. <strong>Bubble up the highest number</strong></li>\n</ul>\n</li>\n<li>A lot of comparison, and slow. Space complexity O(1) but time complexity is <code>O(n^2)</code> so slow.</li>\n<li>Probably <strong>not the best algorithm</strong></li>\n</ul>\n<p>Example Bubble Sort: Scroll until the end of this article.</p>\n<h2>Selection Sort - DO NOT USE</h2>\n<ul>\n<li>\n<p>Scan list of items for smallest then swap to first position.</p>\n<ul>\n<li>It also means a lot of passes to find the smallest item through the list.</li>\n</ul>\n</li>\n<li>Time complexity is <code>O(n^2)</code> and O(1) as space. So also <strong>not very efficient</strong>.</li>\n</ul>\n<p>Example Selection Sort: Scroll until the end of this article.</p>\n<h2>Insertion Sort</h2>\n<ul>\n<li>Not most efficient, but <strong>it is efficient in some ways</strong>.</li>\n<li>If the list is almost sorted, it can give you O(n)</li>\n<li><strong>Works as comparing and inserting into the list</strong>. More like you'll do with your brain. Works well with small data set.</li>\n</ul>\n<p>Insertion Sort Example: Scroll until the end of this article.</p>\n<p>Best case scenario is O(n) <strong>very fast</strong>. If your set is <strong>mostly sorted use insertion sort</strong>.</p>\n<h2>Merge Sort and <code>O(n log n)</code></h2>\n<ul>\n<li>This performs better than others.</li>\n<li><strong>Divide and conquer: Merge sort and quick sort use this conquer along with recursion</strong>.</li>\n<li>These <strong>don't have nested loops</strong>.</li>\n<li>This O(n log n) is because it is still compared, everything at least once, but it is not compared everything to everything.</li>\n<li>\n<p>The list is divided until there's 1 item per group.</p>\n<ul>\n<li>This is building a <strong>reversed tree</strong>. </li>\n<li>These groups are compared until sorting is done.</li>\n</ul>\n</li>\n<li>Very efficient than most, but *<em>more space complexity</em> with <code>O(n)</code>.</li>\n<li>You probably won't be asked to do merge sort by yourself.</li>\n</ul>\n<p>Merge sort is stable but very hard to implement for yourself. <a href=\"https://stackoverflow.com/questions/1517793/what-is-stability-in-sorting-algorithms-and-why-is-it-important\">More about stability in sorting algorithms</a>.</p>\n<p>Merge Sort example: Scroll until the end of this article.</p>\n<h2>Quick Sort</h2>\n<p>Also divide and conquer <code>O(n log n)</code>.</p>\n<p>Uses pivoting technique. <strong>Pretty complex to understand.</strong></p>\n<ul>\n<li>\n<p>Picks random pivot, e.g. random value.</p>\n<ul>\n<li>Compares it with all numbers less than pivot to left and higher to move to right.</li>\n<li>With pivot you have two lists and keep doing and breaking things down like a tree until everything is sorted and then combine.</li>\n</ul>\n</li>\n<li>How you pick pivot point? It depends.</li>\n<li>How will you code it? Pretty challenging.</li>\n<li>Quick sort is very useful. Space complexity is very good could better than merge sort O(log n) but in worst cases very bad O(n^2).</li>\n<li><strong>Selecting pivot is very important to avoid worst case</strong>.</li>\n<li>Quick sort is fastest on average, but can have bad consequences if you don't know how to use it. You can rely on merge or others if unsure.</li>\n</ul>\n<p><strong><a href=\"https://repl.it/@fbohz/quickSort\">Quick sort example</a></strong>.</p>\n<h2>Which Sort is Best?</h2>\n<p><strong>This can come in an interview, choose sorting sort based upon x case</strong>?</p>\n<ul>\n<li>\n<p>Insertion Sort can be used:  </p>\n<ul>\n<li>If you only have few items, small input, and already sorted.</li>\n</ul>\n</li>\n<li>\n<p>Merge Sort (<strong>often used</strong>)</p>\n<ul>\n<li>O(n log n) fast b/c of divide and conquer. Best fast and worst case is consistent.</li>\n<li>If you're worried about worst case scenarios use this one. </li>\n<li>If space is an issue, it can be very expensive as O(n)</li>\n</ul>\n</li>\n<li>\n<p>Quick sort (<strong>often used</strong>):</p>\n<ul>\n<li>Better than merge sort. Best space complexity and popular</li>\n<li>Downside is worst case which is bad.</li>\n</ul>\n</li>\n<li>Bubble Sort: <strong>never use it</strong>. Only for educational purposes.</li>\n<li>Selection Sort: <strong>never use it</strong>. Only for educational purposes.</li>\n</ul>\n<p>Others:</p>\n<ul>\n<li>Heapsort: can be slower but merge/quick are preferred most cases.</li>\n<li>Bucket, Radix: will learn more.</li>\n</ul>\n<h2>Other Sorts:</h2>\n<p>Can we beat <code>O(n log n)</code>? Mathematically, is impossible. Means we have to sort by comparison.</p>\n<p>Tell me more about the other sorts:</p>\n<ul>\n<li><a href=\"https://brilliant.org/wiki/heap-sort/\">Heap sort</a>.  </li>\n<li><a href=\"https://stackoverflow.com/questions/2467751/quicksort-vs-heapsort\">Quick vs Heap sort comparison</a>. </li>\n</ul>\n<p><strong>Non Comparison Sorts</strong>:</p>\n<ul>\n<li>Radix sort and Counting Sort use this.</li>\n<li>Non comparison uses the way that number and data are stored on computers and take advantage of that.</li>\n<li>This <em>only work with numbers</em>, specifically integers in a specific range.</li>\n<li><em>Doesn't work</em> on other data universally.</li>\n<li>So you could use it with numbers.</li>\n</ul>\n<p><strong>Resources</strong>:</p>\n<ul>\n<li><a href=\"https://brilliant.org/wiki/radix-sort/\">Radix Sort</a>. </li>\n<li><a href=\"https://www.cs.usfca.edu/~galles/visualization/RadixSort.html\">Radix Sort Animation</a>. </li>\n<li><a href=\"https://brilliant.org/wiki/counting-sort/\">Counting Sort</a>.</li>\n<li><a href=\"https://www.cs.usfca.edu/~galles/visualization/CountingSort.html\">Counting Sort Animation</a> </li>\n</ul>\n<h2>Common Sorting Interview Questions</h2>\n<ol>\n<li>\n<p>Sort 10 schools around your house by distance:</p>\n<ul>\n<li>insertion sort. Really fast and easy to code with good space. Schools could be presorted.</li>\n</ul>\n</li>\n<li>\n<p>eBay sorts listings by the current Bid amount:</p>\n<ul>\n<li>radix or counting sort. Because are numbers and set amount.</li>\n</ul>\n</li>\n<li>\n<p>Sort scores on ESPN</p>\n<ul>\n<li>Quick sort. Since it varies with decimals etc. Take advantage of better space complexity.</li>\n</ul>\n</li>\n<li>\n<p>Massive database (can't fit all into memory) needs to sort through past year's user data</p>\n<ul>\n<li>Merge Sort. Worried about performance b/c big data so no Quick sort.</li>\n</ul>\n</li>\n<li>\n<p>Almost sorted Udemy review data needs to update and add 2 new reviews</p>\n<ul>\n<li>Insertion Sort. Assuming prev data is already sorted and adding 2 new reviews will take less.</li>\n</ul>\n</li>\n<li>\n<p>Temperature Records for the past 50 years in Canada</p>\n<ul>\n<li>radix or counting sort IF no decimals</li>\n<li>Quick sort IF decimal places</li>\n</ul>\n</li>\n<li>\n<p>Large user name database needs to be sorted. Data is very random.</p>\n<ul>\n<li>Quick / Merge sort. Not a lot of info here. If not worried on worst case.</li>\n</ul>\n</li>\n<li>\n<p>You want to teach sorting</p>\n<ul>\n<li>Bubble sort, Selection sort</li>\n</ul>\n</li>\n</ol>\n<h2>Sorting Review</h2>\n<ul>\n<li>JS included <code>.sort()</code>, depending on its engine might use merge / quick or insertion sort for smaller arrays. So depends on engine used by browser.</li>\n<li>Quick Sort: average space performance concern.</li>\n<li>Merge sort: more stable always gives same results in order if two items are same.</li>\n<li>In real life you won't use others unless small (insertion).</li>\n<li>\n<p><strong>In interview TIP</strong>: </p>\n<ul>\n<li>You can say you can use implement a bubble sort b/c time constrain.</li>\n<li>OR say will implement Merge sort and explain.</li>\n</ul>\n</li>\n<li><a href=\"https://www.youtube.com/user/AlgoRythmics/videos\"><strong>Dancing Algorithms (Videos)</strong></a>. </li>\n</ul>\n<h2>Sorting Algorithms Examples</h2>\n<p>Wanna see the code in action? Check them out below or click <a href=\"https://repl.it/@fbohz/BlogSortingAlgorithmsExamples#index.js\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogSortingAlgorithmsExamples?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>"},{"url":"/posts/2021-01-06-algorithms_ch2/","relativePath":"posts/2021-01-06-algorithms_ch2.markdown","relativeDir":"posts","base":"2021-01-06-algorithms_ch2.markdown","name":"2021-01-06-algorithms_ch2","frontmatter":{"title":"On CS Algorithms: Chapter II","template":"post","date":"2021-01-06 19:31:03 -0400","permalink":"algorithms_ch2","filename":"2021-01-06-algorithms_ch2"},"html":"<blockquote>\n<p>We must remember that programs can be defined pretty much as <code>data structures + algorithms</code>. As we conclude this exploration we'll be discussing Searching algorithms and Dynamic Programming. </p>\n</blockquote>\n<h1>On CS Algorithms: Chapter II</h1>\n<p>We must remember that programs can be defined pretty much as <code>data structures + algorithms</code>. As we conclude this exploration we'll be discussing Searching algorithms and Dynamic Programming. </p>\n<h1>Searching + Traversal, BFS, DFS</h1>\n<p>We'll talk about:</p>\n<ul>\n<li>Searching + Traversal</li>\n<li>Breadth-first search (BFS), Depth-first search (DFS)</li>\n</ul>\n<p>Searching is super useful:</p>\n<ul>\n<li>We search Google, YouTube, search in file.</li>\n<li>\n<p>How computers/software can search so fast? Some strategies</p>\n<ul>\n<li>Linear Search</li>\n<li>Binary Search </li>\n<li>BFS</li>\n<li>DFS</li>\n</ul>\n</li>\n</ul>\n<h2>Linear / Sequential Search</h2>\n<ul>\n<li>Find target value within a list.</li>\n<li>\n<p>Like loop through arrays to find items.</p>\n<ul>\n<li>Check one-by-one.</li>\n</ul>\n</li>\n<li>Best case <code>O(1)</code> and worst case check every single item <code>O(n)</code></li>\n<li>Some JS strategies using linear:</li>\n</ul>\n<pre><code class=\"language-javascript\">var beasts = ['Centaur', 'Godzilla'];\n\n// ALL are linear\n\nbeasts.indexOf('Godzilla');\n\nbeasts.findIndex(function(item){\nreturn item === 'Godzilla';\n});\n\n// return item instead of index\nbeasts.find(function(item){\nreturn item === 'Godzilla';\n})\n\n// true / false\nbeasts.includes('Godzilla')\n</code></pre>\n<p>We can't use this on Google or Facebook, since it will cost time.</p>\n<h2>Binary Search</h2>\n<p><strong>Good on sorted lists</strong>. E.g. you're looking for 34 and list is sorted: 1, 4, 5, 9, 34, 45</p>\n<p>Instead of checking everything you can do binary search:</p>\n<ul>\n<li>\n<p>You can start in middle of list:</p>\n<ul>\n<li>Is 9 higher than 34? NO. <strong>Then discard to left</strong>.</li>\n<li>Go to middle of group again and do comparison.</li>\n</ul>\n</li>\n<li>If it's sorted we can do better than O(n), creating a <strong>binary search tree</strong>. Data complexity since its a tree then it gives great storage too.</li>\n<li>Divide and conquer too.</li>\n<li>Binary search has lookup method by <strong>implementing trees as we saw on tree DS</strong>.</li>\n<li>This has <code>O(log n)</code>.</li>\n<li>But sometimes we need to traverse all nodes, there are other strategies for that.</li>\n</ul>\n<h2>Traversal - Graph + Tree Traversals</h2>\n<p>Sometimes we want to add color property to all nodes. <strong>Traversals is like visiting every node</strong>.</p>\n<ul>\n<li>\n<p>How can we traverse a Tree / Graph?</p>\n<ul>\n<li>With Breadth-first search (BFS), Depth-first search (DFS).</li>\n<li>Both have <code>O(n)</code>.</li>\n</ul>\n</li>\n<li>Main benefit we don't put them on Arrays or Hash Tables is order and good O(log n) instead of O(n).</li>\n<li>Trees / Graphs are used a lot in traversal.</li>\n</ul>\n<h2>Breadth-first search (BFS) &#x26; Depth-first search (DFS)</h2>\n<h3>BFS &#x26; DFS Intro</h3>\n<ul>\n<li>\n<p>BFS:</p>\n<ul>\n<li>Start with root node and move left to right across second, third level, and so on.</li>\n<li>Until you find node you're looking OR tree ends.</li>\n<li><strong>BFS uses more memory b/c it tracks child nodes</strong>. So there are implications</li>\n</ul>\n</li>\n<li>\n<p>DFS:</p>\n<ul>\n<li>Follows one branch until is on last leave then moves forward checking unexplored children and branches.</li>\n<li><strong>Lower memory requirement. Don't need to store all child pointers</strong>.</li>\n<li>So until it hits dead end then moves.</li>\n</ul>\n</li>\n<li>BFS / DFS:</li>\n</ul>\n<pre><code class=\"language-javascript\">//OUR TREE\n//     9\n//  4     20\n//1  6  15  170\n\n\n// BFS: Visits all levels and outputs a list as it finds what it needs \n// [9,4,20,1,6,15,17]\n\n\n// DFS: List is different\n// [9,4,1,6,20, 15,17]\n</code></pre>\n<h3>BFS vs DFS</h3>\n<p>BFS is like water from top to down. DFS is like lines.</p>\n<p>When to use BFS or DFS? Time complexity is <strong>same for both</strong> <code>O(n)</code></p>\n<ul>\n<li>\n<p>BFS:</p>\n<ul>\n<li>Good for <strong>finding shortest path</strong>. As it checks closer nodes.</li>\n<li>Bad: More memory</li>\n<li>If you have additional info and know where the node is, use BFS.</li>\n</ul>\n</li>\n<li>\n<p>DFS:</p>\n<ul>\n<li>When you know node is in lower level then use DFS.</li>\n<li>Ask the question <strong>does the path exist</strong></li>\n<li>Good: Less memory</li>\n<li>Bad:** it can get slow if tree is very deep not very good finding shortest path**</li>\n</ul>\n</li>\n<li><a href=\"https://stackoverflow.com/questions/9844193/what-is-the-time-and-space-complexity-of-a-breadth-first-and-depth-first-tree-tr\">Good Resource</a>.</li>\n</ul>\n<h2>Common Interview Questions BFS vs DFS</h2>\n<p>Study to see how you explain to interviewer</p>\n<ol>\n<li>\n<p>If you know a solution is NOT far from the root of the tree:</p>\n<ul>\n<li>BFS - starts searching closest nodes first. </li>\n</ul>\n</li>\n<li>\n<p>If the tree is VERY deep and solutions are rare, </p>\n<ul>\n<li>BFS (DFS will take long time. )</li>\n</ul>\n</li>\n<li>\n<p>If the tree is very wide:</p>\n<ul>\n<li>DFS (BFS will need too much memory as it has to keeps track of all the nodes)</li>\n</ul>\n</li>\n<li>\n<p>If solutions are frequent but located DEEP in the tree</p>\n<ul>\n<li>DFS</li>\n</ul>\n</li>\n<li>\n<p>determining whether a path exists between two nodes</p>\n<ul>\n<li>DFS</li>\n</ul>\n</li>\n<li>\n<p>Finding the shortest path</p>\n<ul>\n<li>BFS</li>\n</ul>\n</li>\n</ol>\n<h2>Coding BFS &#x26; DFS</h2>\n<h3>Breadth-first Search - Exercises</h3>\n<ul>\n<li><a href=\"https://repl.it/@fbohz/Data-Structures-Trees-traversals-bfs\">Code Here</a>. </li>\n<li>Uses a queue array</li>\n<li>Usually is done with iteration.</li>\n</ul>\n<h3>Breadth-first search (Recursive) - Exercises</h3>\n<ul>\n<li><a href=\"https://repl.it/@fbohz/Data-Structures-Trees-traversals-bfs-recursive\">Code Here</a>. </li>\n<li>Just for fun.</li>\n</ul>\n<h3>Depth-first search - Exercises</h3>\n<ul>\n<li><a href=\"https://repl.it/@fbohz/DFS-InOrder-PostOrder-PreOrder-Trees-Traversals\">Code here</a>.</li>\n<li><strong>stack</strong> DS used here as it is Recursion. Height of tree will tell how much memory, memory consumption will depend on that.</li>\n<li>preOrder: from parent</li>\n<li>inOrder: order of nodes</li>\n<li>postOrder: order from trees at the bottom</li>\n<li>Play with code and console log to see how it inputs</li>\n<li><strong>main difference is the order you get output</strong></li>\n<li><strong>depending on your needs you might implement one or the other</strong></li>\n<li>You just learned how to traverse through tree try to implement in a graph!</li>\n</ul>\n<h3>Validate a BST - Interview Qs</h3>\n<ul>\n<li>A very common question you will get asked in an interview is <strong>how to validate a binary search tree</strong>! Hint, you want to use <strong>BFS</strong> for this.</li>\n<li>Try it <a href=\"https://leetcode.com/problems/validate-binary-search-tree/\">here</a>. </li>\n</ul>\n<h3>Graph Traversals</h3>\n<ul>\n<li>Tree traversal will be the same as Graph traversal. <strong>Trees are a type of graphs</strong>.</li>\n<li>Graphs model real life, like recommendation engine (items related) using like BFS. Facebook what type of friend request or LinkedIn connection with DFS. </li>\n<li><a href=\"https://visualgo.net/en/dfsbfs?slide=1\"><strong>See it in action</strong></a> </li>\n</ul>\n<p> <strong>Remember</strong> </p>\n<ul>\n<li>DFS is for shortest path. Closest to our node. Related items on Amazon, closest connections.</li>\n<li>DFS check if it exists. We can go very deep very fast.</li>\n<li>\n<p>BFS in Graphs:</p>\n<ul>\n<li>What's the closest node to 0? BFS is very good as it looks closest nodes first.</li>\n</ul>\n</li>\n<li>\n<p>DFS in Graphs:</p>\n<ul>\n<li>Great for solving a maze. Because it goes deep then backtracks to solve the puzzle until finds exit.</li>\n<li>Idea of backtracking after dead end is just recursion.</li>\n<li>It answers does the path exist? </li>\n<li>If very deep branch can get very slow. Needs to keep track of all the functions on the stack.</li>\n</ul>\n</li>\n</ul>\n<h2>Dijkstra + Bellman-Ford Algorithms</h2>\n<ul>\n<li><strong>In interview you'll probably don't implement them</strong></li>\n<li>BFS <strong>doesn't care about weight</strong>. So doesn't take to account weighted graphs.</li>\n<li>\n<p>Dijkstra / Bellman-Ford Algorithms:</p>\n<ul>\n<li><strong>Find the shortest path between two nodes on a weighted graph</strong>.</li>\n<li>Bellman can accommodate negative weights and Dijkstra doesn't.</li>\n<li>Dijkstra is faster than Bellman's (worst case is O(n^2)).</li>\n</ul>\n</li>\n</ul>\n<p>In an Interview:</p>\n<ul>\n<li>These algorithms are very <strong>complex</strong></li>\n<li>Know that they exist and how to use them.</li>\n<li>\n<p>If you see a weighted graph and asked to find best algorithm:</p>\n<ul>\n<li>BFS can't be used because is weighted</li>\n<li>Negative weights? If YES, Bellman. If NO, Dijkstra.</li>\n</ul>\n</li>\n</ul>\n<p><a href=\"https://medium.com/basecs/finding-the-shortest-path-with-a-little-help-from-dijkstra-613149fbdc8e\">Read more</a>. </p>\n<h2>Searching + Traversal Review</h2>\n<ul>\n<li>Searching and Traversal are one of the most popular algorithms.</li>\n<li>Learned about how to traverse tree/graph.</li>\n<li>Now we're better to equipped to answer questions.</li>\n<li>Review the <strong>Technical Interview Mind Map</strong>. </li>\n<li><a href=\"https://coggle.it/diagram/W5E5tqYlrXvFJPsq/t/master-the-interview-click-here-for-course-link\">More here</a>.</li>\n</ul>\n<h2>Dynamic Programming (DP)</h2>\n<ul>\n<li>DP is just optimization technique using cache. If you can cache then you can do DP. So its just a buzz word a lot of times.</li>\n<li>DP solves problems by breaking it down into sub problems, storing solutions in case those sub problems arise.</li>\n<li>\n<p>DP</p>\n<ul>\n<li>Divide and Conquer + Memoization (cache)</li>\n</ul>\n</li>\n</ul>\n<h2>Memoization</h2>\n<ul>\n<li>Caching is a way to store values that you can use later. Like a backpack that holds items you need.</li>\n<li>Memoization is a specific caching we use in our programs.</li>\n</ul>\n<p><strong>Memoization example</strong></p>\n<pre><code class=\"language-javascript\">function add80(n) {\n    return n + 80\n}\n\nadd80(5)\n</code></pre>\n<p>What if this operation took a long time? Can we optimize it with memoization?</p>\n<pre><code class=\"language-javascript\">function add80(n) {\n    return n + 80\n}\n\nlet c = {}\n\nfunction memoAdd80(n) {\n    if (n in cache) {\n        //O(1)\n        return cache[n]\n    } else {\n        cache[n] = n + 80\n        return cache[n]\n    }\n}\n</code></pre>\n<p>What is then memoization?</p>\n<ul>\n<li>Caches return value based on parameters. <strong>If param of function doesn't change then its memoized then it will return cache version</strong>. If parameter changes then calculates as usual.</li>\n<li><strong>So its a way to remember a solution to a problem so you don't have to calculate again</strong>.</li>\n</ul>\n<h3>Closures in Memoization</h3>\n<p>Patterns in DP:</p>\n<pre><code class=\"language-javascript\">function memoAdd80() {\n    let cache = {}\n    //closure returns a function\n    return function(n) {\n      if (n in cache) {\n          //O(1)\n          return cache[n]\n      } else {\n          cache[n] = n + 80\n          return cache[n]\n      }\n    }\n}\n\nconst memoized = memoAdd80()\nconsole.log(1, memoized(6))\n// console.log(cache)\n// console.log('-----------')\nconsole.log(2, memoized(6))\n</code></pre>\n<ul>\n<li>Closures <strong>return a fn inside a fn</strong></li>\n<li>Because of closure we can <strong>avoid global scope</strong> and access cache.</li>\n</ul>\n<h3>Fibonacci and DP (caching)</h3>\n<p>Remember recursion example.</p>\n<pre><code class=\"language-javascript\">let calculations = 0\nfunction fib(n) {\n    calculations++\n    if (n &#x3C; 1) {\n        return n\n    }\n\n    return fib(n-1) + fib(n-2)\n}\n\nfib(6)\n//will take a long time\n// fib(30)\n</code></pre>\n<ul>\n<li>\n<p>Remember this is pretty bad! O(2^n). <strong>We'll never want to implement this in real life</strong>.</p>\n<ul>\n<li>This because we repeat a lot of calculations.</li>\n</ul>\n</li>\n<li>\n<p><strong>Can we fix this with caching (DP)</strong>? Reduce it to O(n)</p>\n<ul>\n<li>Yes we can because the solution is optimal and we do the same.</li>\n<li>We can actually return a memoized version with O(1) and use the cached version.</li>\n</ul>\n</li>\n</ul>\n<p>Solving fibonacci. See below or <a href=\"https://repl.it/@fbohz/BlogDPSolvingFibonacci#index.js\">here</a>.</p>\n<iframe height=\"400px\" width=\"100%\" src=\"https://repl.it/@fbohz/BlogDPSolvingFibonacci?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"></iframe>\n<p>Note: we increased the space complexity with memoization.</p>\n<h2>Assess when to use DP (caching / memoization)</h2>\n<p>Think about your problem like this to implement DP:</p>\n<ol>\n<li>Can it be divided into subproblem. Problem broken down into smaller problems.</li>\n<li>Recursive solution</li>\n<li>\n<p>Are there repetitive sub-problems?</p>\n<ul>\n<li>Same calculation over and over? <strong>we can memoize the problem!</strong> </li>\n</ul>\n</li>\n<li>Memoize sub-problems </li>\n<li>Implement caching! and save a lot of calculations!</li>\n</ol>\n<h2>Interview Questions: Dynamic Programming</h2>\n<p>Here are some popular Dynamic Programming Questions (see if you can notice the pattern):</p>\n<ol>\n<li><a href=\"https://leetcode.com/problems/house-robber\">House Robber</a>     </li>\n<li><a href=\"https://leetcode.com/problems/best-time-to-buy-and-sell-stock\">Best Time to Buy and Sell Stock</a>    </li>\n<li><a href=\"https://leetcode.com/problems/climbing-stairs\">Climbing Stairs</a>       </li>\n</ol>\n<h2>Review of DP</h2>\n<ul>\n<li><strong>All you need is to remember the pattern of saving a cache variable and use closures to return a function within a function</strong>.</li>\n<li>If there's repeated calculation then get the memoized result.</li>\n<li>Memoized version has more space complexity, so this tradeoff is necessary.</li>\n<li><strong>Other way to incorporate DP is bottom up approach</strong>.</li>\n<li>This one avoids recursion. Starts from simple to higher solutions.</li>\n<li>This one is <strong>harder to know how/when to use</strong></li>\n<li>Interview is unlikely that they will ask you to implement both methods.</li>\n<li><strong>In short memoization help us to avoid having to do repeated tasks</strong>. If you can implement this you're on your way to become a great engineer. </li>\n</ul>"},{"url":"/blog/","relativePath":"blog/index.md","relativeDir":"blog","base":"index.md","name":"index","frontmatter":{"title":"Blog","seo":{"title":"All Entries","description":"This is the blog page","extra":[{"name":"og:type","value":"website","keyName":"property"},{"name":"og:title","value":"Blog","keyName":"property"},{"name":"og:description","value":"This is the blog page","keyName":"property"},{"name":"og:image","value":"images/1.jpg","keyName":"property","relativeUrl":true},{"name":"twitter:card","value":"summary_large_image"},{"name":"twitter:title","value":"Blog"},{"name":"twitter:description","value":"This is the blog page"},{"name":"twitter:image","value":"images/1.jpg","relativeUrl":true}]},"template":"blog"},"html":""},{"url":"/posts/2021-02-11-next_npm_virus_outbreak/","relativePath":"posts/2021-02-11-next_npm_virus_outbreak.markdown","relativeDir":"posts","base":"2021-02-11-next_npm_virus_outbreak.markdown","name":"2021-02-11-next_npm_virus_outbreak","frontmatter":{"title":"Preventing the Next NPM Virus Outbreak☣","template":"post","date":"2021-02-11 09:31:03 -0400","permalink":"next_npm_virus_outbreak","filename":"2021-02-11-next_npm_virus_outbreak","thumb_img_path":"/images/1.jpg","thumb_img_alt":"Preventing the Next NPM Virus Outbreak☣","content_img_path":"/images/2.jpg","content_img_alt":"Preventing the Next NPM Virus Outbreak☣"},"html":"<blockquote>\n<p>Doing <code>npm install</code> seems like second nature these days for developers. But did you know that without proper attention and auditing of npm packages, the next time we unknowingly do <code>npm i</code> you could also be installing malicious scripts?</p>\n</blockquote>\n<h1>Preventing the Next NPM Virus Outbreak☣</h1>\n<p>Doing <code>npm install</code> seems like second nature these days for developers. But did you know that without proper attention and auditing of npm packages, the next time we unknowingly do <code>npm i</code> you could also be installing malicious scripts?</p>\n<h2>Is NPM Virus Free?</h2>\n<p>We know that most of the npm packages we use are maintained by third party actors. This can be a single developer, a team of developers or a super large corporation. </p>\n<p>NPM in itself is very reliable. But does NPM guarantee you that any package that you install will be virus free? Unfortunately not.</p>\n<p>So these days, it is not uncommon to hear <a href=\"https://youtu.be/24tQRwIRP_w?t=935\">some developers</a> foreseeing a day in which a successful virus attack will spread through millions of machines through NPM. </p>\n<p>Sorry if I'm the first person to tell you: <strong>NPM it's not virus free</strong> 🤦🏼‍♂️. </p>\n<p>I won't go into all technical details of how exploits are possible in NPM. Just know that NPM has <a href=\"https://blog.npmjs.org/post/141702881055/package-install-scripts-vulnerability\">disclosed publicly</a> that it is possible for an apparently 'normal' npm package (or its dependencies) to execute malicious code in your machine and wreak havoc. </p>\n<p>For <em>any</em> package can be compromised. You probably have ESLint installed right? Well, guess what? One of its dependencies was (not long ago) compromised and installed malicious code on users machines. The ESLint team and NPM acted quickly to solve the issue and their incident report can be seen <a href=\"https://status.npmjs.org/incidents/dn7c1fgrr7ng\">here</a>. But this is not the last time a virus incident happened. Now the NPM security team is publishing <a href=\"https://www.npmjs.com/advisories\">weekly reports</a> of such incidents.</p>\n<h2>Preventing Exposure To Future NPM Virus Outbreaks</h2>\n<p>Exploits can be defined as scripts that take advantage of vulnerabilities in code to cause unintended or malicious behaviors to occur. An exploit was possibly the culprit of the ESLint incident. There are some actions we can take to safeguard our code to avoid become infected with any future malicious script incidents.</p>\n<p>NPM Security Recommendations:</p>\n<ol>\n<li><strong>Think twice before installing a new NPM package</strong>. Are you sure you really need it? Is it well maintained? Can you just code it yourself? Ask yourself this questions before adding a new dependency. The best way to safeguard yourself is simply having <em>less</em> packages. If you are part of a team you could also <strong>consult with your team</strong> before installing a new package. Even if you are just trying it. You might not wanna be one of those using a seemingly harmless package that is then reported to contain an exploit, as it happened in a <a href=\"https://www.zdnet.com/article/malicious-npm-packages-caught-installing-remote-access-trojans/\"><strong>recent report</strong></a>.</li>\n<li><strong>Use <code>npm audit</code> manually</strong>. This command was released by NPM as a response to its vulnerability. Actually each time you do <code>npm i</code>, npm audit will also run automatically. The <code>npm audit</code> command will scan your packages for vulnerabilities. You can even fix vulnerabilities automatically by just doing <code>npm audit fix</code>. The efficacy of this command depends on how it is up to date to latest threats and reports, but it must be part of your coding arsenal. You should manually run this command to inspect and fix as needed. You can learn more about it on the <a href=\"https://docs.npmjs.com/cli/v6/commands/npm-audit\"><strong>documentation</strong></a>. Here's also a <a href=\"https://youtu.be/rXV6-eXB26s\"><strong>good video</strong></a> that covers common cases when running this command.</li>\n<li><strong>Github Alerts</strong>: If you use Github then just take advantage of Github through its Dependantbot alerts which comes with any repository for free. If you been ignoring those alerts, don't. Read more about it on the <a href=\"https://docs.github.com/en/github/managing-security-vulnerabilities/about-alerts-for-vulnerable-dependencies\"><strong>Github documentation</strong></a>.</li>\n<li><strong>Use third-party software</strong>. This is useful if you are part of larger team. There are plenty of development security of tools that scan your dependencies for vulnerabilities. Some options are <a href=\"https://snyk.io/\"><strong>Snyk</strong></a> and <a href=\"https://www.whitesourcesoftware.com/\"><strong>WhiteSource</strong></a>.</li>\n<li><strong>Pay open source maintainers</strong>. You heard it right. A lot of NPM packages are open source. Maintainers have to pay their bills at the end, and support them could not only help them financially but also hold them ethically accountable.</li>\n<li><strong>Report suspicious packages to NPM</strong>. Just like you hear at the airport. For NPM, if you see anything suspicious, report it to <a href=\"mailto:support@npmjs.com\"><strong>support@npmjs.com</strong></a>.</li>\n<li><strong>Disable NPM scripts</strong>. You can prevent malicious scripts by opting-out of using scripts altogether by doing <code>npm config set ignore-scripts true</code>. This might be a deal breaker for some since it also disables custom scripts on package.json. You can also do this case-by-case when installing a package with <code>npm install --ignore-scripts</code>. There might be unintended consequences of your packages not installing correctly and common commands such as npm run or npm test breaking. Some people have done workarounds by having shell aliases such as <code>nrun = npm run --ignore-scripts=false</code> or <code>ntest = npm test --ignore-scripts=false</code> to allow some particular scripts to work. I cannot assure what other problems will you encounter. Try this last strategy at your own risk. </li>\n</ol>\n<h2>Conclusion</h2>\n<p>So when is the next doomsday NPM package virus that will affect millions of computers coming? Who knows. So while we might not be able to prevent the next outbreak, we as developers need to guard ourselves. </p>\n<p>We are always eager to get to coding and wanna get setup as fast as possible. But the next time you are about to npm install, ask yourself: <em>Are there any security checks I should be performing before installing?</em> There are always things we can do to audit our NPM packages. </p>\n<p>By applying these NPM security recommendations our code becomes more secure and we can greatly decrease the risk of getting infected when the next outbreak happens ☣</p>"},{"url":"/posts/2021-06-15-new-site-announcement/","relativePath":"posts/2021-06-15-new-site-announcement.markdown","relativeDir":"posts","base":"2021-06-15-new-site-announcement.markdown","name":"2021-06-15-new-site-announcement","frontmatter":{"title":"🚨 New Site Alert! + Updates 🚨","template":"post","date":"2021-06-15 19:31:03 -0400","permalink":"new-site-announcement","filename":"2021-01-06-algorithms_ch2"},"html":"<blockquote>\n<p>✅  Modern JS Framework (Gatsby) ✅  Markup used for generating posts ✅  Fast Deployment Through Github Pages...So I hope you are enjoying the fast rendering, new UI and colors. I'm loving it! 😍</p>\n</blockquote>\n<h1>🚨 New Site Alert! 🚨</h1>\n<p>After using <a href=\"https://jekyllrb.com/\"><strong>Jekyll</strong></a> for such a long time, I've been wanting to give this site a much needed facelift. </p>\n<p>Today I'm happy to announce the official launch of my new JAMSTACK site:</p>\n<p>✅  Modern JS Framework (<a href=\"https://www.gatsbyjs.com/\"><strong>Gatsby</strong></a>)</p>\n<p>✅  Markup Files for Post Generation</p>\n<p>✅  Fast Deployment Through Github Pages</p>\n<p>I hope you are enjoying the fast rendering, new UI and colors. I'm loving it! 😍</p>\n<h1>P.S. 📨</h1>\n<p>I know I've been a bit MIA in the past months 😂. </p>\n<p>I decided to dedicate some time on personal projects in areas which I'm passionate such as writing, art and food. </p>\n<p>So here's what I've been working:</p>\n<ul>\n<li>Launched <a href=\"https://medium.com/elevarte/about\"><strong>Elevarte</strong></a> ✍🏽! in collaboration with ZDM Writing. We are in baby steps but this will be a space to publish content on a variety of topics to elevate diverse voices.</li>\n<li>Started developing <strong>Catoro</strong> on mobile 📱. Some backbone work has been done. Will be using Firebase and React Native. Really looking to launch this FREE coffee tasting app by Q4 2021.</li>\n<li>New Website for <a href=\"http://artesanospirit.com/\"><strong>ArtesanoSpirit</strong></a> project 🎨. Trying to re-imagine my beloved food and art project. More on this to come.</li>\n</ul>\n<p>So if you don't see me posting tech articles here, check other recent publications at 📃<a href=\"https://fbohorqu.medium.com/\"><strong>Medium</strong></a>. </p>\n<p>And in case you haven't, just connect with me on <a href=\"https://www.linkedin.com/in/fbohz/\"><strong>LinkedIn</strong></a> and let's chat!</p>"},{"url":"/_templates/TEMPLATE/","relativePath":"_templates/TEMPLATE.md","relativeDir":"_templates","base":"TEMPLATE.md","name":"TEMPLATE","frontmatter":{"title":"Preventing the Next NPM Virus Outbreak☣","template":"post","date":"2021-02-11 09:31:03 -0400","permalink":"copy_from_file_name","filename":"2021-02-11-next_npm_virus_outbreak"},"html":"<blockquote>\n<p>Quote Text Here</p>\n</blockquote>\n<h1>Title Here?</h1>\n<p>Text</p>"}],"site":{"siteMetadata":{"siteUrl":"https://fbohz.com/","layout_style":"overflow","palette":"fbohz","header":{"title":"Felipe Bohórquez","tagline":"","profile_img":"images/avatar.png","profile_img_alt":"Author avatar","background":"","has_nav":true,"nav_links":[{"label":"Home","url":"/","style":"link"},{"label":"Blog","url":"/blog/","style":"link"},{"label":"About","url":"/about/","style":"link"},{"label":"Resume","url":"https://fbohz.com/assets/Resume.pdf","style":"link"}],"has_social":true,"social_links":[{"label":"Medium","url":"https://fbohorqu.medium.com/","style":"icon","icon_class":"medium","new_window":true},{"label":"GitHub","url":"https://github.com/fbohz","style":"icon","icon_class":"github","new_window":true},{"label":"LinkedIn","url":"https://www.linkedin.com/in/fbohz/","style":"icon","icon_class":"linkedin","new_window":true}]},"projects":[{"label":"Catoro","deploy_url":"https://catoro.vercel.app/","image_url":"/images/catoro.png","repo_url":"https://github.com/fbohz","year":"2021","icon_class":"react","excerpt":"Implemented UI employing React and Redux with React-Boostrap for styling. ES6+, React Hook-Form, and Chart.js.","tags":"React, Rails"},{"label":"Yijing Ball Z","deploy_url":"https://yijingballz.herokuapp.com/index.html","image_url":"/images/yijing.png","repo_url":"https://github.com/fbohz","icon_class":"javascript","excerpt":"I-Ching Oracle Inspired by Dragon Ball Z. JavaScript frontend and implemented Node.js/Express API server.","tags":"Vanilla JS, Express, MongoDB"},{"label":"Studio Ghibli's Fan Hub","deploy_url":"https://studio-ghibli-fanhub.herokuapp.com/","image_url":"/images/ghibli.png","repo_url":"https://github.com/fbohz","icon_class":"react","excerpt":"React app with eCommerce built-in using Stripe API for payment gateway.","tags":"React, Redux, Firebase"}],"all_projects":[{"label":"Catoro","deploy_url":"https://catoro.vercel.app/","image_url":"/images/catoro.png","repo_url":"https://github.com/fbohz","year":"2021","icon_class":"react","excerpt":"Implemented UI employing React and Redux with React-Boostrap for styling. ES6+, React Hook-Form, and Chart.js.","tags":"React, Rails"},{"label":"Yijing Ball Z","deploy_url":"https://yijingballz.herokuapp.com/index.html","image_url":"/images/yijing.png","repo_url":"https://github.com/fbohz","icon_class":"javascript","excerpt":"I-Ching Oracle Inspired by Dragon Ball Z. JavaScript frontend and implemented Node.js/Express API server.","tags":"Vanilla JS, Express, MongoDB"},{"label":"Studio Ghibli's Fan Hub","deploy_url":"https://studio-ghibli-fanhub.herokuapp.com/","image_url":"/images/ghibli.png","repo_url":"https://github.com/fbohz","icon_class":"react","excerpt":"React app with eCommerce built-in using Stripe API for payment gateway.","tags":"React, Redux, Firebase"},{"label":"Cook-n-Shop","deploy_url":"https://angular-test-e364e.web.app/","image_url":"/images/projects/groceries.jpg","repo_url":"https://github.com/fbohz","year":"2021","icon_class":"angular","excerpt":"Angular cooking app + Firebase. Angular patterns including dynamic components, directives and module patterns","tags":"Angular, Firebase"},{"label":"Magic Realism Library","deploy_url":"https://gabophiles.netlify.app/","image_url":"/images/projects/gabo.png","repo_url":"https://github.com/fbohz","icon_class":"gatsby","excerpt":"Magic Realism book site built with Gatsby plus Firebase backend for dynamic rendering.","tags":"Gatsby, Firebase"},{"label":"Uff! - Street Art Finder","deploy_url":"https://uff-app.herokuapp.com/","image_url":"/images/projects/uff.png","repo_url":"https://github.com/fbohz","icon_class":"rails","excerpt":"REST Rails app. Devise + Omniauth. Bcrypt for password encryption. Google Cloud Storage and MiniMagick.","tags":"Rails, PostgreSQL, ActiveRecord"},{"label":"Retro Snake","deploy_url":"http://fbohz.com/html5_games/retro_snake.html","image_url":"/images/projects/snake.png","repo_url":"https://github.com/fbohz","year":"2021","icon_class":"javascript","excerpt":"Clone of the classic game with HTML5 and JavaScript. Node/Express API + MongoDB backend. Groove with the retro music.","tags":"JS, Node, MongoDB"},{"label":"Coingecko (Ruby Gem)","deploy_url":"https://rubygems.org/gems/coingecko","image_url":"/images/projects/gem.png","repo_url":"https://github.com/fbohz","year":"2021","icon_class":"ruby","excerpt":"Ruby API Gem for Coingecko Blockchain Market Watch. More than 3K downloads to date.","tags":"Ruby"},{"label":"Museo","deploy_url":"http://fbohz.com/css-learning/museo-demo/index.html","image_url":"/images/projects/museo.png","repo_url":"http://fbohz.com/css-learning/museo-demo/index.html","year":"2021","icon_class":"css","excerpt":"Single page landing demo of tour company site. Used SASS + 7-1 architecture pattern with BEM methodology.","tags":"CSS, SASS"}],"body":{"blog_icon":[{"label":"Medium","url":"https://fbohorqu.medium.com/","style":"icon","icon_class":"medium","new_window":true}]},"footer":{"content":"Copyright  &copy; Felipe Bohorquez"},"title":"Felipe Bohórquez Portfolio"},"pathPrefix":"","data":{}},"menus":{}}}}