<![CDATA[Derpy Coder]]>https://www.derpycoder.com/https://www.derpycoder.com/favicon-png.webpDerpy Coderhttps://www.derpycoder.com/Ghost 3.40Sun, 24 Jan 2021 21:18:40 GMT60<![CDATA[Dgraph: 12 Reasons that make it the best Database of 21st Century]]>https://www.derpycoder.com/dgraph-12-reasons-that-make-it-the-best-database-of-21st-century/5fcdacdd0760b900394c39c9Sun, 24 Jan 2021 19:07:44 GMT

With great pride let me introduce you to the best in class Database, & why you must be using this for every project going forward.

Dgraph: 12 Reasons that make it the best Database of 21st Century Dgraph: 12 Reasons that make it the best Database of 21st Century Dgraph: 12 Reasons that make it the best Database of 21st Century

A while back I was dreaming of a project, that I thought had a lot of potential, and started scouring the internet, for the right technology, to make it happen.

I was new to System Design, so I just went blindly through the top of the list for every technology, to make the backend.

Turns out the technology at the top of the list may have been the best in the previous century, but in this century they feel like they could use a revamp.

Not just the tech stack itself, but how we talk to the backend. Everyone needs to get their hands on GraphQL to feel how revolutionary it is compared to what REST has to offer.

That brings us to Dgraph. I would go over each of the feature that will prove why:

Dgraph is truly a 21st Century Database!

Versus

See the official comparison by Dgraph: Dgraph compared to other Databases.

I didn't include a section for Dgraph vs other Graph database because it just wins out right against the biggest contender & Dgraph has a comprehensive comparison available. See: Dgraph vs Neo4j.

1. SQL Databases

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Jan Antonin Kolar / Unsplash

SQL Databases are chosen for ACID Properties, and relational nature.

But can't Graph DBs guarantee the same? What makes it so that only Relation Database are capable of those guarantees?

Dgraph meets all of the criterias a old school Relational Database does:

  • Atomicity: Transactions are there in Dgraph. See: Transactions Documentation.
  • Consistency: The database must remain consistent, before & after transaction. See: Jepsen Test result on Dgraph.
  • Isolation: Multiple transaction occur independently without interference. See: Snapshot Isolation used by Dgraph.
  • Durability: The changes of a successful transaction occurs even if system failure occurs. See: Raft Consensus Algorithm used by Dgraph.

Dgraph outperforms Relational Databases in all frontier, and more. For instance it's Horizontally Scalable, even in free version, which famous RDBMS can't do out of the box!

2. NoSQL Databases

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Sharon McCutcheon / Unsplash

The need for processing unstructured data, and the need for faster processing led to advent of NoSQL.

Startups are said to prefer NoSQL due to flexible schema, to allow future growth. Well Dgraph also has flexible schema, and lots more to benefit a startup!

NoSQL has lots of advantages, and so does Dgraph. Like:

  • Distributed in Nature.
  • Highly Scalable.
  • Auto Sharded.
  • Auto Replicated.
  • Integrated Search.
  • Flexible Schema Design.
  • Reduced Costs.
  • Open Source.
  • Integrated Caching.
  • Faster Writes.

However, Dgraph doesn't suffer from the cons of NoSQL, Like:

  • ACID Transactions in Dgraph is first class.
  • Fine grain security is possible with Dgraph.
  • Dgraph uses GraphQL for queries and not some obscure language.
  • Faster reads.

Features

Following features puts Dgraph at the upper echelon of Databases.

3. Native GraphQL

Build a Twitter Clone in 10-Minutes - Dgraph - YouTube

New Databases are cropping up, that introduce a layer on top of their Relational DB to allow GraphQL query, and all they end up doing is bloating up the stack by using Adapters that convert GraphQL to SQL or some other translations that introduce overhead.

Then there are services like Hasura, that generates the GraphQL API for existing database. But it comes nowhere close to how good a Native GraphQL solution gets.

GraphQL and Graph Databases are meant to play along, and having it as first class citizen of the Database makes it so much better. (Think Apple Hardware & Software.)

Just look how swift Dgraph can let someone make a Twitter Clone!

Using GraphQL means:

  • Overfetching & Underfetching are things of the past.
  • No N+1 problem.
  • Great for mobile devices because of lighter payload.
  • Subscriptions, so server can let front end know when something changes. (For example after file is processed, or when message received from a live chat!). See: Apollo GraphQL Subscriptions.
  • Self documenting, no need to maintain documentation separately & any app can display the documentation via Introspection of the GraphQL Endpoint. See: GraphQL Playground.
  • Ease of handling deprecations, without introducing versioning and fragmenting the backend. See: Deprecation Dgraph.
  • It's scalable, as endpoints don't have fixed payload, so the same endpoint can be used everywhere.
  • Response key aliasing is easy. See: Aliases. (No more sausage case & camel case discrepancies!)
  • Client driven development, no more reliance on Backend to make changes.
  • Caching is possible. See: Apollo GraphQL Caching.
  • GraphQL can even act like an API Gateway between multiple microservices.

4. Distributed

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Science in HD / Unsplash

A distributed system has multiple components located on different machines that communicate and coordinate actions in order to appear as a single coherent system to the end-user.

That means, instead of having one big machine doing all the work, multiple smaller machines can divide the work among themselves.

Which allows a company like Google to scale to Googol!

Traditional RDBMS can't do that, you either move to a recently introduced RDBMs that introduced horizontal scaling or use a plugin, like you do with PostgreSQL. That is you would need Hyperscale (Citus)!

So why not go with a Database, that already beats other Databases in all aspects and is Distributed in nature out of the box!

Being distributed allows a system to be:

  • Horizontally Scalable.
  • Auto balanced across shards.
  • Synchronous Replication.
  • Fault Tolerant due to Raft Consensus Algorithm.

Dgraph is also Jepsen Tested, so it is guaranteed that the Database meets all challenges of a Distributed System.

5. Blazing Fast

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Marc Sendra Martorell / Unsplash

Graph databases are much faster than relational databases for connected data - a strength of the underlying model!

Graph Databases also make modelling and querying much more pleasant, meaning faster development. It's natural to think and draw in Graph shape than in tabular format.

Hence Graph Databases beat the traditional databases hands down, which puts Graph Databases way ahead of other DBs.

Then comes the Dgraph's competitors like Neo4j, which can't even hold candle to Dgraph's lightning performance!

Dgraph is significantly faster compared to Neo4j, as it's:

  • Written in Golang, so no JVM to warm up.
  • Optimized for SSD utilizing Badger DB! (Think of SSD as cheap ram, than costly storage!)
  • Concurrent caching enabled by Ristretto. See: Blog post on Ristretto.

For a comprehensive understanding, look at the benchmark done by Dgraph:

Neo4j vs Dgraph - The numbers speak for themselves - Dgraph Blog
As Dgraph is nearing its v0.8 release, we wanted to spend some time comparing it against Neo4j, which is the most popular graph database. We have divided this post into five parts: Loading dataQueryingIssues facedDgraph vs Neo4j Feature ComparisonPrinciples behind Dgraph
Dgraph: 12 Reasons that make it the best Database of 21st Century
Neo4j vs Dgraph - The Numbers Speak for Themselves - Dgraph Blog

6. Geolocation

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by delfi de la Rua / Unsplash

Geolocation has become an integral part of mobile applications, especially with the advent of smartphones in the last decade, the list of applications which revolves around users location to power application features has grown beyond imagination.

Real-world data is interconnected; they are not sparse; this is more relevant when it comes to location data. The natural representation of railway networks, maps, routes are graphs.

The good news is that Dgraph, the world’s most advanced graph database, comes with functionalities to efficiently store and perform useful queries on graphs containing location data. If you want to run queries like find me the hotels near Golden Gate Bridge, or find me all the tourist location around Golden Gate Park, Dgraph has your back.

Yet databases often lack this basic feature. For example if you use Postgres, you would need Postgis.

Getting started with Dgraph-8: Easily build location-aware apps using our native geolocation features - Dgraph Blog
Welcome to the eighth episode of getting started with Dgraph.In the previous episode, we learned about building a twitter-like user-search feature using Dgraph’s fuzzy search.
Dgraph: 12 Reasons that make it the best Database of 21st Century

7. Truly Relational

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by John Barkiple / Unsplash

Graphs are more relational than the Relational DBs pretend to be.

The primary keys, the foreign keys and all that junk. It's like manually placing the wire on the mechanical board to patch in a call from one end to the other like in old days, when telephones first came to be.

  • Can't we just let the natural Graph Data Structure handle the relations?
  • Can't industry use the Data Structure that was forced down our throats, in University, instead of a tabular structure?
  • Data is multi dimensional, then why do we resort to using two dimensions to store it?
  • Graph can easily handle multiple dimensions, right?

Normalizing data is so much old school. Can we please move on, and just use a Data Structure that doesn't store data repeatedly and yet is able to retrieve data quickly!

So many issues can be avoided, if we just embrace higher dimensions. Instead of living like ants on 2d plane, let us soar through the space with Dgraph.

If Graph Database can handle a complex relational websites like social networks, then it can definitely handle every other kinds of relational data.

8. Easy

Dgraph: 12 Reasons that make it the best Database of 21st Century
Slash GraphQL - Managed Dgraph Hosting Service

It's the easiest Database there is. No need to learn boring syntaxes, joins, normalizations.

Easy to learn, easy to set up, and most importantly easy to use!

Dgraph is Docker & Kubernetes native, so it plays along great. See: Dgraph Docker Images.

The ease with which you can define GraphQL Schema is mind blowing. You can use Interactive Schema builder or just plain text, and all the CRUD APIs get generated by Dgraph!

  • Why even bother writing the backend, if all we need to do is write the schema and the DB Updates itself seamlessly?
  • Manually creating CRUD APIs should be the thing of the past. When can we learn that there is a better way?

Dgraph allows us update the schema whenever we desire, and the Graph updates accordingly.

You can use Swagger Editor to generate Server stubs REST APIs, with OpenAPI specification, but that doesn't even scratch the surface of what Dgraph does.

To top it all, Dgraph even has Slash GraphQL, it's hosted managed Dgraph service. And if that doesn't say easy, I don't know what does!

Pricing - Dgraph
Dgraph is a horizontally scalable database with native support for GraphQL. Now with Slash GraphQL, get a managed GraphQL backend with one click.
Dgraph: 12 Reasons that make it the best Database of 21st Century
Dgraph Pricing
Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Anthony Martino / Unsplash

Search functionality is a must in a Database, having it built in and not having to create a separate Datastore for search functionality is just a blessing.

Dgraph uses indexes to make search efficient.

int, float, geo and date have default indexes, but string has options of what index types to choose. Multiple indexes can be built for the same string valued predicate.

For string the following indexes are available

  • term for use with allofterms and anyofterms. (default)
  • exact for use with inequality - matching whole string.
  • hash as for exact but hashes string - useful with long strings.
  • fulltext for full text search with alloftext and anyoftext.
  • trigram for use with regular expressions.

Fulltext is the most advanced of the lot:

Full text search is what Google does for web pages. It’s different to term matching because it tries to respect language, grammar and tense. For example, matching search term run with documents containing run, running and ran.

It doesn’t match terms exactly and instead makes use of

  • Stemming: Finding a common base word so differences in tense, plural / singular or other inflection are still matched, and
  • Stop Words: Removing words such as and, or, it and maybe that occur too often to search over.

Getting started with Dgraph tutorials series - 7: Give your users powerful search results with fuzzy search on graph - Dgraph Blog
Welcome to the seventh episode of getting started with Dgraph. In the previous episode, we learned about building advanced text searches on social graphs in Dgraph, by modeling tweets as an example.
Dgraph: 12 Reasons that make it the best Database of 21st Century
Fuzzy Search on Dgraph - Dgraph Blog

10. JWT based Auth

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Markus Spiske / Unsplash

Dgraph GraphQL comes with built-in authorization. It allows you to annotate your schema with rules that determine who can access or mutate the data.

There are two important concepts in auth:

  • Authentication: says who you are.
  • Authorization: says what you are allowed to do.

Dgraph does it amicably, and plays nicely with Apollo GraphQL.

A Match Made In Heaven: Authentication and Authorization with Dgraph and Auth0 - Dgraph Blog
When creating a serverless app that integrates both authentication and authorization, using both Dgraph and Auth0 might be the holy grail.
Dgraph: 12 Reasons that make it the best Database of 21st Century
Authentication & Authorization with Dgraph & Auth0 - Dgraph Blog

11. Custom Business Logic

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by Possessed Photography / Unsplash

If generated CRUD API falls short of your requirement, i.e. Factory made superbike doesn't float your boat, then you can add custom business logic using JS Lambda Functions

Dgraph Lambda is a serverless platform for running JavaScript on Dgraph and Slash GraphQL.

Lambda Server - Graphql
Dgraph: 12 Reasons that make it the best Database of 21st Century
Dgraph Lambda

12. Encryption & Compression

Dgraph: 12 Reasons that make it the best Database of 21st Century
Photo by JJ Ying / Unsplash

Encryption is a process that encodes a message or file so that it can be only be read by certain people.

Dgraph has something called Encryption at rest, which refers to the encryption of data that is stored physically in any digital form. It ensures that sensitive data on disks is not readable by any user or application without a valid key that is required for decryption.

Dgraph provides encryption at rest as an enterprise feature. If encryption is enabled, Dgraph uses Advanced Encryption Standard (AES) algorithm to encrypt the data and secure it.

Compression is the method computers use to make files smaller.

Dgraph saves storage space by compressing every block of data using one of the two compression algorithms provided:

Zstandard
google/snappy
A fast compressor/decompressor. Contribute to google/snappy development by creating an account on GitHub.
Dgraph: 12 Reasons that make it the best Database of 21st Century
Snappy

Conclusion

Hope I have shed enough light to convince you to opt for Dgraph.

If you are stuck with other Databases, use Live Loader & Bulk Loader to port the data into Dgraph. Else if you are starting from scratch then definitely go for Slash GraphQL, the official managed offering from Dgraph Labs. See Pricing:

Pricing - Dgraph
Dgraph is a horizontally scalable database with native support for GraphQL. Now with Slash GraphQL, get a managed GraphQL backend with one click.
Dgraph: 12 Reasons that make it the best Database of 21st Century
Dgraph Pricing
YSK: Most System Design Interview questions can be answered with Dgraph!

The community behind Dgraph is massive, and so is the company.

Discuss Dgraph
All talks about Distributed GraphQL Database: Dgraph
Dgraph: 12 Reasons that make it the best Database of 21st Century
Discuss Dgraph

Let me know your thoughts down in the comments below.

]]>
<![CDATA[Ghost Pro: 15 Tips & Tricks to Spice up your Website]]>https://www.derpycoder.com/ghost-pro-15-tips-tricks-to-spice-up-your-website/5ff93443f3066500398eb66fSat, 16 Jan 2021 07:18:52 GMT<![CDATA[Svelte: 10 Reasons that make it the best JavaScript Framework]]>https://www.derpycoder.com/svelte-10-reasons-that-make-it-the-best-javascript-framework/5ff30ba17cdfeb00391a658cSun, 10 Jan 2021 13:29:08 GMT

Svelte is probably the best front end framework till date, given how little mess it leaves in the runtime and how little boilerplate it adds in author time.

Svelte: 10 Reasons that make it the best JavaScript Framework Svelte: 10 Reasons that make it the best JavaScript Framework Svelte: 10 Reasons that make it the best JavaScript Framework Svelte: 10 Reasons that make it the best JavaScript Framework Svelte: 10 Reasons that make it the best JavaScript Framework Svelte: 10 Reasons that make it the best JavaScript Framework

It's simple just like Handlebars (albeit without 2 curly braces), yet powerful. It takes Handlebars further, by facilitating updates of the DOM, event-handling, frontend-backend communication and much much more.

Frameworks are not tools for organizing your code, they are tools for organizing your mind. - Rich Harris
Rich Harris - Rethinking Reactivity - YouTube

Reasons

Here's a list of all the reason front end development should happen using Svelte.

1. Truly Reactive

React is an awful name for React.js

Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.

It uses a labelled statement (aka Destiny Operator), to facilitate change detection. So:

  • App doesn't waste precious compute power going through code that doesn't change.
  • Battery friendly apps should avoid other frameworks altogether.

2. No Virtual DOM

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Pankaj Patel / Unsplash

Virtual DOM is slow, and even the react team knows that.

That's why they have given us, Abstraction Leaks, to tell the dumb framework not to update somethings:

  • shouldComponentUpdate
  • React.pureComponent
  • useMemo
  • useCallback

In Svelte however, change detection is much more precise as the compiler knows what to update when something changes, thanks to its advanced Reactive nature.

So no overhead like a Virtual DOM is even remotely necessary.

3. No Boilerplate

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Markus Spiske / Unsplash

React apps are 40% larger compared to Svelte app, due to boilerplate code. If you have worked with React, you can relate.

I have to make changes to 6+ files to get something done, and that doesn't say how many lines of code I have to repeat. (DRY Principle is thrown out the window.)

  1. Add a Actions Constant.
  2. Create Actions.
  3. Modify Redux.
  4. Create Saga.
  5. Update Target file to fire the action.
  6. Update Destination file to react to changing Redux state.

Svelte overcomes that by:

  • Writing in vanilla HTML, CSS, & JS syntax.
  • Not expecting us to learn something like JSX. No more muddying the HTML with JS.
  • Inbuilt streamlined State manager.

4. No Runtime

Compilers are the New Frameworks

Unlike React, Vue or Angular, that do the bulk of their work in the browser at runtime. Svelte is a compile time framework.

A framework should be thing, that runs in your build step.

It shifts that work into a compile step, taking our high level declarative components and turning them into efficient, imperative, low level code to manipulate the DOM directly.

All these results in a framework free vanilla js code at runtime.

The implications are:

  • Faster initial load.
  • Faster payload delivery due to small size.
  • Unnecessary updates never happen. (Which you get to see when you put a breakpoint in a React app!)
  • Less performance hits on run time as all optimizations gets performed in compile time.
  • Unused CSS gets removed in the build step.
  • It even points out missing attributes, that are necessary. (Like alt attribute in an image tag)

5. Component Scoped Styles

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Pankaj Patel / Unsplash

CSS is component scoped, which saves a lot of headache, Styling won't leak outside a component or leak into one.

Unnecessary styles gets purged by the compiler, so no more forgetting to remove unused CSS.

It's even easy to change style, classes programmatically without even using a CSS in JS library.

6. Server Side Rendering

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Markus Spiske / Unsplash

AWS bills will be lower, as Svelte doesn't need to create a component tree & then serialize it. It just outputs a string.

Sapper takes the component framework and makes it an Application framework and adds:

  • Routing.
  • Code splitting.
  • Progressive Web App.
  • Static Site Generation. (See Jamstack for more)
For fast and secure sites | Jamstack
What is the Jamstack? Why use the Jamstack? How do I get started? Learn what the Jamstack is all about and why it’s the best approach for building faster, more secure websites.
Svelte: 10 Reasons that make it the best JavaScript Framework
For Fast & Secure Sites - Jamstack

7. Transitions & Animations

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Pankaj Patel / Unsplash

Unlike other frameworks, where animations are an afterthought, and not really part of the library. Svelte believes it to be core of the user's experience.

There's libraries like GSAP, to achieve animations, but is it too much to ask for something built in with the framework that doesn't add a lot of weight to the website.

Svelte compiler converts javascript based animation to optimized CSS animations. Which means:

  • Animations will work in low powered devices.
  • Animations will be GPU accelerated.
  • Animations won't block main thread.
  • The build will work even with JavaScript disabled.
  • Applications won't drain as much battery, compared to a CPU based animation.
  • Web Apps look pretty with micro interactions. See: Micro-Interactions: a Designer's Superpower!

See:

Svelte tutorial
Animations / The animate directive
Svelte: 10 Reasons that make it the best JavaScript Framework
Svelte Tutorial - Animate Directive - Todo App

8. Built in State Manager

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Sigmund / Unsplash

Not all application state belongs inside your application component hierarchy. Sometimes, you'll have values that need to be accessed by multiple unrelated components, or by a regular JavaScript module.

There are as many state manager, as there are frameworks. (Redux.js, Effector.js, ...)

But the built in state manger is just sublime.

Svelte tutorial
Stores / Writable stores
Svelte: 10 Reasons that make it the best JavaScript Framework
Svelte Writable Store Tutorial

9. Small yet Fast

Svelte: 10 Reasons that make it the best JavaScript Framework
Svelte has smallest build size - Benchmark

If the points mentioned above, doesn't speak volumes about how revolutionary this Framework is, maybe a demonstration will.

  • Smaller size means, less JS to parse for the Browser.

See: - How Svelte beats react without gimmicks like Async or Debounce.

Benchmark Ranks 18 Front-End Frameworks Implementation of Medium.com Clone
The RealWorld-based benchmark comparing the implementation by 18 front-end frameworks of a non-trivial full-stack application code-named Conduit recently updated its results. Most (13 out of 18) frameworks obtain a top-tier LightHouse performance score. Svelte, Stencil, AppRun, Dojo, HyperApp and El…
Svelte: 10 Reasons that make it the best JavaScript Framework
Benchmark Ranks 18 Front-End Frameworks

10. Uses Observables

Svelte: 10 Reasons that make it the best JavaScript Framework
Photo by Ferenc Almasi / Unsplash

It just works with RxJS out of the box. So:

  • Folks using Angular can just jump right in and feel at home.
  • Folks using Firebase, can use RxFire with Svelte.
  • RxJS is a combination of the best ideas from Observer Pattern, the Iterator Pattern, and Functional Programming.
  • Concurrency becomes easy.
  • Async error handling becomes possible.
If Svelte and RxJS had a baby
Learn how to use RxJS with Svelte and why they are such beautiful couple
Svelte: 10 Reasons that make it the best JavaScript Framework
If Svelte & RxJS had a Baby

Conclusion

Svelte is quite literally the Tesla of Front end frameworks!

However, you can take it to the next level with: Micro-Frontend

Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
It’s high time we break the monolith architecture in the front-end, the way it’s broken in the back-end: stateless, componentized, tech-agnostic & separate!
Svelte: 10 Reasons that make it the best JavaScript Framework
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic - DerpyCoder

Let me know your thoughts down below.

]]>
<![CDATA[Don't Let Him Poo: Angular 2 based game using A Star Algorithm]]>https://www.derpycoder.com/dont-let-him-poo-angular-2-based-game-using-a-star-algorithm/5fef25607cdfeb00391a62feFri, 01 Jan 2021 16:20:56 GMT

A browser based game, driven by A Star path finding algorithm, and made using Angular 2.

The code is deprecated, but feel free to look around the git repo. It was made back in 2018, to showcase what I'm capable of and:

As a tribute to shitty people that made my life a living hell at my first job!
Don’t Let Him Poo!
Prevent the pesky emoji from going to loo. Coz, it’s a game revolving around poo!
Don't Let Him Poo: Angular 2 based game using A Star Algorithm
Don't Let Him Poo

Game

You can either play it here in this page itself, or else visit Don't Let Him Poo website!

Tap around to figure out the controls.


Development

I optimized the site for mobile & desktop. The design resembles a calendar, has dark mode by default.

It has a modified Material Design, as I used paper cutouts!

Resources

  • I picked A star code from PathFinding.js library. Didn't really want to reinvent the cycle.
  • I used GreenSock for js based animations.
  • SVG line rendering for the line between the player emoji & the targets.
  • Angular 2, as it was latest and greatest at the moment.
  • Hosted using GitHub pages, which is a topic for another day!
qiao/PathFinding.js
A comprehensive path-finding library for grid based games - qiao/PathFinding.js
Don't Let Him Poo: Angular 2 based game using A Star Algorithm
PathFinding.js - GitHub

Challenges

  • State machine implementation for the player emotion change.
  • Movement choreography, rhythm, line renderer change.
  • Targeting system, as moment to moment the objective for player kept changing.
  • Line rendering using SVG, based on the source, destination & short path found by the pathfinder.
  • Serialized levels, and loading them at random.
GreenSock
GSAP is an industry standard JavaScript animation library from GreenSock that lets you craft high-performance animations that work in every major browser.
Don't Let Him Poo: Angular 2 based game using A Star Algorithm
GreenSock

Source Code

Although the code has been deprecated, I merely want to have it present in my Blog as a reminder of what I have overcome.

abhijit-kar/dont-let-him-poo
💩🚽 Prevent the pesky emoji from going to loo. Coz, it’s a game revolving around poo! - abhijit-kar/dont-let-him-poo
Don't Let Him Poo: Angular 2 based game using A Star Algorithm
Don't Let Him Poo - GitHub

Inspiration

Back at Cognizant I was experiencing burnout from overwork, so I got the inspiration to make this game.

I was forced to work for 16 hours on average, maxing out at 19 hours 30 minutes. I had to go on Saturday 11 in the morning and return 5:30 AM on Sunday next day. (My morning bowel movements were being interrupted 😅)

Therefore I chose Calendar like design for the game view as it depicts the excruciating mental pain that lasted for my entire stay at Cognizant.

I was neither given compensatory off, nor payment for overtime & weekends. It was demeaning, and inhumane working at Cognizant under those managers.

Employees join companies but leave managers.

All I got out of my ordeal at Cognizant, is a searing back ache, occasional pizza, and this game. The gameplay reflects what I went through.

You play as a manager of a dysfunctional organization and you have to manage your underling in such a way that you don't let him poo. Keep him busy, make him work, get paid. And then use money or pizzas to keep him too occupied to notice.

Conclusion

The game is not fun, it's a casual depiction of my ordeal, and technical wizardry.

You will always win, playing the game as a manager, as the game is rigged against the employee. (Similar to how it is in Real Life)

Let me know your thoughts down in the comments below.

]]>
<![CDATA[Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic]]>https://www.derpycoder.com/micro-frontend-the-best-vaccine-to-react-angular-vue-js-pandemic/5fec03031e8d2f0039253c38Fri, 01 Jan 2021 09:33:22 GMT

It's high time we break the monolith architecture in the front-end, the way it's broken in the back-end: stateless, componentized, tech-agnostic & separate!

Websites today are still made the same way they were 20 years ago, with a cumbersome monolithic approach to building sites, storing data, and delivering content. It’s time for a new way to build the web. - GatsbyJS’s Founder Kyle Mathews

After experiencing development using React & Angular, I have nothing but pure loathing for the current state of front-end web development.

Especially with the Agile and it's weekly delivery mandate, the monolithic approach to front-end development is just a huge pain in the tushy. Requirements changes at the whim of the project manager, or at the last minute, due to misunderstood use case.

Front-end, a monolith, however remains inflexible unlike the micro-service based back-end.

While developing a back-end we strive to make it as stateless as possible, why not for the front-end. Why have a shared state at all, only to have it get unmanageable in the long run? What is a shared state, if not a glorified Global variable?

Then comes along the frameworks and their countless dependencies, verbosity, and hand holding opinions.

Sure there's Storybook.js for those frameworks, to allow development of component in isolation, but the result still remains a monolith.

Defacto front-end frameworks, like React, Angular & Vue.js, aren't even fast enough. On top of that they bloat the site with JavaScript. See: A RealWorld Comparison of Front-End Frameworks with Benchmarks.

Svelte already beats the Monoliths in their own game, however we can take it even further with Micro-Frontend approach.

This post is about taking the front-end to the next level. Breaking the site and building the individual pieces the way back-end development is done.

Pros & Cons

Cons of Monolithic Frontend

  • During inception, the architecture might be solid, but the volley of adjustments made to the system turns the code base into a a big ball of mud, a casual, haphazardly structured system.
  • A version change to any library breaks the whole application, instead of just one component, and we have to fix the issue for each of the component individually in a go.
  • Tiny changes require full deployment.
  • Eventually things get tightly coupled, due to lack of foresight of new requirements streaming in. Components can't function independently once plucked from their location as the same component gets reused in multiple pages, with varying requirements in UI.
  • Everyone in the front end must use the same library, and won't be able to choose best tool for the job.
  • Struggle to scale is real.
  • Teams keep stepping on each other's toes.
  • While the backend is nicely segregated, the front-end remains a large monolith, which requires knowledge about the whole backend.
  • Development blues like: Inability to find the file on which to work on, because we can't see which component the ui view belongs to.
  • Things become stateful, which gets unwieldy eventually.
  • Component discovery suffers and so does reusability.
  • Incremental upgrades are risky, & slow.

Pros of Micro-Frontend

  • This design is resilient to drawbacks of requirement changes.
  • Version change of any library won't require every component to be updated to get the site running. Each component can do it independently.
  • Tiny changes won't require full deployment.
  • Things can never get tightly coupled, as each component are independent and must be able to function without the rest.
  • Everyone's free to choose best tool for the job.
  • Scaling is on par with a Microservice architecture.
  • Teams can't keep stepping on each other's toes, if everything is nicely split.
  • Front end is split, mirroring the back end.
  • Easy to find file on which to work on, as we can clearly see from Bit.dev site. (Try hovering over each component on that site!)
  • Components remain stateless through and through, as they solely interact via their respective public API.
  • Component discovery is easy.
  • Incremental upgrades are easy.

Tools

The following tools are what can help you with Micro-Frontend development. Both of the tools, when combined together, can make one master of webdev.

1. Bit.dev

Share Code Components - Bit.dev - YouTube

Bit is an open-source cli tool for collaborating on isolated components across projects and repositories.

Instead of building the whole project in one build process, the component-driven CI from Bit.dev splits the build process so that it only runs on the components that actually changed, and propagates the changes, to build every impacted component, on every page, in every app.

So instead of messing with cumbersome iframes or finding alternative solutions, we can rely on build-time integrations that do not couple release processes together.

Since components are decoupled, we can easily add, replace, hotfix, or even rollback a single component or feature.

On top of that, features such as visual component documentation, a smart component search, and even live simulations all help to make all the components discoverable so that we don’t have to maintain any additional documentation websites, registries or tools.

See: How We Build Micro Frontends blog post by Bit.dev.

The shared component cloud
Bit is the world’s leading platform for front-end components. It helps over 100,000 developers and teams build faster by sharing and collaborating on reusable components. Join free to create your cloud component library today
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
The Shared Component Cloud - Bit.dev
teambit/bit
Build, distribute, and collaborate on components. Contribute to teambit/bit development by creating an account on GitHub.
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
TeamBit/Bit - GitHub

2. Storybook

Storybook for Front-End Development - YouTube

Storybook is an open source tool for developing UI components in isolation. It makes building stunning UIs organized and efficient.

Checkout how Airbnb react date picker Storybook is organized.

It helps with documentation, mocking hard to reproduce use case, build in isolation, and do visual testing on components.

However Storybook solves half of the equation.

Storybook excels in the visual development of standalone components locally, Bit handles the full lifecycle of components already created. It completes Storybook from the point a component lives in your project, and beyond.

See: How is bit.dev different from Storybook? blog by Bit.dev.

Storybook: UI component explorer for frontend developers
Storybook is an open source tool for developing UI components in isolation for React, Vue, and Angular. It makes building stunning UIs organized and efficient.
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
UI Component Explorer for Front-End Developers - Storybook

Frameworks

There needs to be an overarching framework to glue different components together. And I feel the following frameworks to be the best.

1. Handlebars

Handlebars Tutorial - YouTube

Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.

It's great for readonly content, for instance this blog is made using Handlebars. Try turning off the javascript, and the site will still work as the template have been rendered in the server.

However it's not good for fast (incremental) updates of the DOM, event-handling, frontend-backend communication. - See: When not to use Handlebars?

As for when to use it, checkout Jamstack.

For fast and secure sites | Jamstack
What is the Jamstack? Why use the Jamstack? How do I get started? Learn what the Jamstack is all about and why it’s the best approach for building faster, more secure websites.
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
For Fast & Secure Sites - Jamstack

2. Svelte

Rich Harris - Rethinking Reactivity - YouTube

Svelte takes Handlebars further, by facilitating updates of the DOM, event-handling, frontend-backend communication.

Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic

It’s actually not a framework but a compiler with a templating language like Handlebars.js! (i.e. with single curly braces instead of double)

Svelte being a compiler and templating language is what makes it so powerful.

  1. Unlike React, Vue or Angular, that do the bulk of their work in the browser at runtime, Svelte shifts that work into a compile step which results in a framework free vanilla js code.
  2. Less boilerplate, as it's written in near vanilla HTML, CSS, & JS syntax.
  3. Standard HTML, unlike JSX.
  4. Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.
  5. CSS is component scoped, which saves a lot of headache.
  6. Supports universal rendering & static site gen with Sapper. So no compromise on SEO, and one step closer to Jamstack!
Svelte: 10 Reasons that make it the best JavaScript framework
Svelte is a compile time framework, that take our high level declarative components and turns into efficient, imperative, low level code for browsers.
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
Svelte: 10 Reasons that make it the best JavaScript Framework - DerpyCoder

Svelte tutorial
Introduction / Basics
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
Svelte Tutorial
Sapper: Towards the ideal web app framework
Taking the next-plus-one step
Micro-Frontend: The best Vaccine to React, Angular & Vue.js Pandemic
Companion Library for Svelte - Sapper

Conclusion

Sure, lots of JS libraries come out every minute. Not every one of them is worthy of our attention.

However Svelte does something no other framework does, and that deserves everyone's attention. Combine that with Micro-Frontend architecture, and we are golden.

What do you think, let me know in the comments below.

]]>
<![CDATA[8 Aspects to know for System Design Interviews]]>https://www.derpycoder.com/8-aspects-to-know-for-system-design-interviews/5fe42f53f3b7a700390b687fSun, 27 Dec 2020 16:10:33 GMT

System design interviews are open ended, with no answer that's 100% effective. All we have to do is weigh options and put forth the best one forward.

Here are some of the aspects to keep in mind while designing your next large scale system.

1. Microservices

What is a micro-service architecture and its' advantages - Gaurav Sen - YouTube

Monoliths used to be the way of life. A single system capable of doing everything.

Breaking the responsibilities into bite sized micro services is the best way to scale up systems. Those services can be individually updated, can scale independently, can use different tech than others.

It brings lots of other challenges however, such as distributed consensus issue, fault tolerant design issue, health check, service discovery, monitoring, etc.

The following checklist should tell you just how much the landscape has changed, compared to what is being taught in colleges.

Production Readiness Checklist
Are you ready to go to prod on AWS? Use this checklist to find out.
8 Aspects to know for System Design Interviews
Production Readiness Checklist - Gruntwork

2. Horizontal Scaling

Horizontal vs Vertical Scaling - Gaurav Sen - YouTube

Vertical scaling is merely adding more and more to the spec of an existing system. That however is unsustainable at scale.

Horizontally scaling the system is the best way forward if Google's scale is desired. However dividing the system into smaller pieces has challenges of its own.

Scaling vertically up is great when starting out. As apparently engineers are costlier than SSDs and Ram. Which is why Plenty of Fish's Architecture uses the scale up approach and same goes for Stack Overflow's Architecture!

3. Load Balancing

What is Load Balancing? - Gaurav Sen - YouTube

Load balancing is the efficient distribution of network or application traffic across multiple servers in a server farm. Each load balancer sits between client devices and back-end servers, receiving and then distributing incoming requests to any available server capable of fulfilling them.

Some of the best ones are - Nginx, Envoy Proxy.

Envoy Proxy - Home
Envoy is an open source edge and service proxy, designed for cloud-native applications
8 Aspects to know for System Design Interviews
Envoy Proxy

4. API

A Web API is an application programming interface for either a web server or a web browser.

There are several protocols in the stack making it possible for clients & servers to communicate with each other.

a. HTTP

HTTP is the underlying communication protocol of the World Wide Web. HTTP functions as a request-response protocol in the client-server computing model.

It's a one way communication protocol, which means when we send a request we get a response. But server can't send something out of its own volition as the connection is one way.

It's best for passive applications that doesn't need to be updated live.

Few architectural patterns based on HTTP are REST, GraphQL. They are topics for another post.

GraphQL | A query language for your API
8 Aspects to know for System Design Interviews
GraphQL

b. Socket

It's a bi-directional protocol, that supports full-duplex communication - client and server can talk to each other independently at the same time.

It uses Single TCP connection so client and server communicate over that same TCP connection throughout the life-cycle of Web Socket connection. Which means less overhead with handshakes happening again and again.

This is best for real time applications, or real time part of the application.

Socket.IO
SOCKET.IO 3.0 IS HERE FEATURING THE FASTEST AND MOST RELIABLE REAL-TIME ENGINE ~/Projects/tweets/index.js const io = require
8 Aspects to know for System Design Interviews
Socket IO

c. Encoding

In what format the messages are passed between sender and receiver is also one decision that needs to be made.

Binary formats like MessagePack, Protobuf are naturally compact, yet front end can't understand them. They are great for server to server communications.

Text format like JSON is not small in size, however it's natural to JavaScript, hence great for front end applications and can be compressed to match the size of Protobuf or MessagePack.

The trade-offs need to be analysed, as it's done below.

The need for speed - Experimenting with message serialization
As a young developer dealing with the average size payload and the average “few” requests, I struggled to accelerate the communication between my client app and server. I stopped using jQuery’s ajax…
8 Aspects to know for System Design Interviews
Experiments with Message Serialisation - Medium

5. Storage

Depending on the type of data being stored and requirements, several types of storage exist.

a. Databases

What is Database Sharding? - Gaurav Sen - YouTube

A database is a collection of information that is organised so that it can be easily accessed, managed and updated.

Several DB types exists with varieties of query languages to talk to them. Like Relational, No SQL, Graph DB, Key Value, Time Series, etc.

They all have something to offer, with their own advantage & disadvantages which is a topic for another day.

Native GraphQL Database: The Best Graph DB | Dgraph
Dgraph is the world’s most advanced, native GraphQL database with a graph backend. Now with Slash GraphQL, get a managed GraphQL backend in one click.
8 Aspects to know for System Design Interviews
The Best Graph DB - Dgraph

b. Blob Storage

Object stores are best suited for blobs like images & videos. As they can't be stored in Databases.

Object storage is a computer data storage architecture that manages data as objects, as opposed to other storage architectures like file systems which manages data as a file hierarchy, and block storage which manages data as blocks within sectors and tracks.

The main advantage of using object storage are metadata tags, which allow for much better identification and classification. Search capabilities and unlimited scaling make object storage ideal for unstructured data.

MinIO | High Performance, Kubernetes Native Object Storage
MinIO’s High Performance Object Storage is Open Source, Amazon S3 compatible, Kubernetes Native and is designed for cloud native workloads like AI.
8 Aspects to know for System Design Interviews
High Performance, Kubernetes Native Object Storage - MinIO

c. Distributed Caching

What is Distributed Caching? - Gaurav Sen - YouTube

It's an essential component of large scale systems.

Caching is a technique that stores a copy of a given resource and serves it back when requested. When a web cache has a requested resource in its store, it intercepts the request and returns its copy instead of re-downloading from the originating server.

It's the same principle behind Dynamic Programming. i.e. Instead of computing something again and again or retrieving something from slower media, why not cache the data in a faster storage and serve from there instead.

Redis is one such tool. It's an in-memory data store, which is used as a distributed, in-memory key–value database, cache and message broker.

Cache can be sped up further with compression. See: Doordash's LZ4 Study.

Golang Key-Value Store - Badger DB | Dgraph
An open source key-value database, Badger DB is fast, crash resilient, optimized for SSD, and easy to use. Enjoy the fastest speeds and more.
8 Aspects to know for System Design Interviews
Key-Value Store Badger DB - Dgraph

d. Content Delivery Networks

A CDN (Content Delivery Network) is a highly-distributed platform of servers that helps minimise delays in loading web page content by reducing the physical distance between the server and the user. This helps users around the world view the same high-quality content without slow loading times.

They do so by serving the intended content from closest data centre.

KeyCDN - Content delivery made easy
KeyCDN is a high performance content delivery network (CDN). Our global network will deliver any digital content, such as a website, software, or game, at a blazing fast speed.
8 Aspects to know for System Design Interviews
KeyCDN

6. Compression

a. Passive Compression

Some compression algorithms are best used passively like Brotli, or media compression algorithms like MP4.

Netflix has to support lots of devices of varying calibre. Each device has a video format that looks best on that particular device.

Netflix also creates files optimised for different network speeds. If you’re watching on a fast network, you’ll see higher quality video than you would if you’re watching over a slow network.

Stranger Things season 2 has 9,570 different video, audio, and text files!

Excerpt from: Netflix - What Happens When You Press Play?

All of that compression is done passively once, instead of on the fly.

This kinds of decisions need to be taken in requirement gathering phase.

google/brotli
Brotli compression format. Contribute to google/brotli development by creating an account on GitHub.
8 Aspects to know for System Design Interviews
Brotli by Google - GitHub

b. Active Compression

Then there's active compression for text like data, in transit or for storage in memory.

The algorithm needs to be fast in both compression & decompression stage and eat up less CPU while doing so.

Some interesting reads:

Speeding Up Redis with Compression | DoorDash Engineering Blog
One of challenges we face almost everyday is to keep our API latency low. While the problem sounds simple on the surface, it gets interesting sometimes. One of our endpoints that serves restaurant menus to our consumers had high p99 latency numbers. Since it’s a high traffic endpoint we naturally us…
8 Aspects to know for System Design Interviews
Speeding Up Redis with Compression - DoorDash Engineering
How Uber Engineering Evaluated JSON Encoding and Compression Algorithms to Put the Squeeze on Trip Data
Imagine you have to store data whose massive influx increases by the hour. Your first priority, after making sure you can easily add storage capacity, is to try and reduce the data’s footprint to save space. But how? This is the story of Uber Engineering’s comprehensive encoding protocol and compres…
8 Aspects to know for System Design Interviews
Put the Squeeze on Trip Data - Uber Engineering

7. Distributed Consensus

Distributed Consensus & Data Replication - Gaurav Sen - YouTube

The Byzantine Generals Problem is a term used in computing to denote a situation wherein certain components of a system may fail if participants don't agree on a 'concerted strategy' to deal with the problem.

The Byzantine Generals' Problem is the analogy most often used to illustrate the requirement for consensus for distributed systems. i.e. How do you make sure that multiple entities, which are separated by distance, are in absolute full agreement before an action is taken?

I ran into this problem when I designed a Distributed Socket Server. Multiple instances of the same server were disagreeing with each other under load, i.e. they had conflicting data in them.

Eventually I found out about Redlock algorithm algorithm and then used it to achieve distributed consensus.

Raft Consensus Algorithm is the best I found so far, it's used by Dgraph for their distributed graph database!

Raft Consensus Algorithm
Raft is a consensus algorithm that is designed to be easy to understand.
8 Aspects to know for System Design Interviews
Raft Consensus Algorithm

8. Message Queues

What is a Message Queue & Where is it used? - Gaurav Sen - YouTube
Put everything into a queue. Votes, comments, thumbnail creation, precomputed queries, spam processing and corrections.

Excerpt from Reddit - Lessons Learned From Mistakes Made Scaling To 1 Billion Pageviews A Month.

Queues allow you to know when there’s a problem by monitoring queue lengths. Side benefit is queues hide problems from users because things like vote requests are in the queue and if they aren’t applied immediately nobody notices.

It's a clever little trick, often used in single page applications called Optimistic UI. It's a pattern that you can use to simulate the results of a mutation and update the UI even before receiving a response from the server!

So when user clicks on up-vote, instead of showing a loader or loading the whole page, we immediately show the effect of the button press. Meanwhile the user's button press is sent to a message queue which will be processed asynchronously by the server.

There are several message queues, Rabbit MQ, Kafka, NATS.

NATS - Open Source Messaging System | Secure, Native Cloud Application Development
NATS is a high performance messaging system that acts as a distributed messaging queue for cloud native applications, IoT device messaging, and microservices architecture.
8 Aspects to know for System Design Interviews
NATS

Conclusion

If this post doesn't help you crack an interview, perhaps it can help you understand how you should approach your next big project.

Learn from the mistakes of others. You can't live long enough to make them all yourself. - Eleanor Roosevelt

A site called High Scalability has some of the best articles on System Design.

Like the following postmortem!

Netflix: What Happens When You Press Play? - High Scalability -
This article is a chapter from my new book Explain the Cloud Like I’m 10 . The first releas...
8 Aspects to know for System Design Interviews
Netflix: What happens when you press play? - High Scalability

What do you think? Let me know your thoughts down in the comments below.

]]>
<![CDATA[5 Sorting Algorithms for Coding Interviews]]>https://www.derpycoder.com/5-sorting-algorithms-for-coding-interviews/5fdf64a7f3b7a700390b65b6Mon, 21 Dec 2020 07:47:09 GMT

There's tons of Sorting Algorithms, however for interviews, being able to implement a select few and explain their time complexity should be enough.

Also check the sorting algorithms used by different languages, to see what they use.

For JavaScript, Mozilla uses Merge Sort, but Chrome uses Quick Sort and Insertion Sort (for smaller arrays).

Implementation

1. Quick Sort

Quick Sort - HackerRank - YouTube

Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of Quick Sort that pick pivot in different ways. (e.g. First, Last, Random, or Median Element as pivot)

Keep following aspects in mind while choosing Quick Sort.

  • It's an unstable sort, meaning the order for same keys is not guaranteed.
  • It requires O(1) extra space as it's an in place sort.
  • Best used on Arrays.
  • Randomised version of Quick Sort is the most common one.
  • The Quick Sort is internal sorting method where the data is sorted in main memory, hence it cannot be used for large data sets.
  • Quick Sort exhibits good cache locality and this makes Quick Sort faster than merge sort (in many cases like in virtual memory environment).
function partition(arr, start = 0, end = arr.length - 1) {
    // Let's choose the pivot to be the arr[start] element
    let pivot = arr[start];
    let swapIdx = start;

    for (let i = start + 1; i <= end; i++) {
        if (arr[i] < pivot) {
            swapIdx++;
            // Swap current element with the element at the new
            // pivot index
            [arr[i], arr[swapIdx]] = [arr[swapIdx], arr[i]];
        }
    }
  
    // Swap the pivot element with the element at the pivot index
    [arr[swapIdx], arr[start]] = [arr[start], arr[swapIdx]];
  
    // Return the index of the pivot element after swapping
    return swapIdx;
}

// Recursive
function quickSort(arr, left = 0, right = arr.length - 1) {
    // Base case is that the left and right pointers don't overlap,
    // after which we'll be left with an array of 1 item
    if (left < right) {
        let pivotIndex = partition(arr, left, right);
      
        // For left subarray, which is everything to the left
        // of the pivot element
        quickSort(arr, left, pivotIndex - 1);
      
        // For the right sub array, which is everything to the
        // right of the pivot element
        quickSort(arr, pivotIndex + 1, right);
    }
    // Return the array, when it's of length 1 i.e, left === right
    return arr;
}
Quick Sort - JavaScript
Quick Sort visualize | Sorting | Algorithms | HackerEarth
Visualize your learning on Quick Sort to improve your understanding of Algorithms.
5 Sorting Algorithms for Coding Interviews
Quick Sort Visualiser - HackerRank

2. Merge Sort

Merge Sort - HackerRank - YouTube

Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves.

Keep following aspects in mind while choosing Merge Sort.

  • Merge Sort is a stable sort, unlike Quick Sort and Heap Sort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage
  • Best used with Linked List, as
    • Merging multiple linked list is easier compared to Arrays.
    • Merge Sort requires sequential access, and not random.
  • It requires O(n) extra space, as it's not an in place sort.
  • Merge sort is more efficient and works faster than quick sort in case of larger array size or datasets.
  • Merge sort can work well on any type of data sets irrespective of its size.
function merge(arr1, arr2) {
    // Make a new array, and 2 pointers to keep track of elements of
    // arr1 and arr2     
    let res = [],
        i = 0,
        j = 0;
    
    // Loop until either arr1 or arr2 becomes empty
    while (i < arr1.length && j < arr2.length) {
        // If the current element of arr1 is lesser than that of
        // arr2, push arr1[i] and increment i         
        if (arr1[i] < arr2[j]) {
            res.push(arr1[i]);
            i++;
        } else {
            res.push(arr2[j]);
            j++;
        }
    }

    // Add the rest of the remining subarray, to our new array
    while (i < arr1.length) {
        res.push(arr1[i]);
        i++;
    }
    while (j < arr2.length) {
        res.push(arr2[j]);
        j++;
    }
    return res;
}

// Recursive merge sort
function mergeSort(arr) {
    // Base case
    if (arr.length <= 1) return arr;
  
    // Splitting into two halves
    let mid = Math.floor(arr.length / 2);
    let left = mergeSort(arr.slice(0, mid));
    let right = mergeSort(arr.slice(mid));
  
    // merging the two sorted halves
    return merge(left, right);
}
Merge Sort - JavaScript
Merge Sort visualize | Sorting | Algorithms | HackerEarth
Visualize your learning on Merge Sort to improve your understanding of Algorithms.
5 Sorting Algorithms for Coding Interviews
Merge Sort Visualiser - HackerEarth

3. Insertion Sort

Insertion Sort - GeeksForGeeks - YouTube

Insertion sort works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

  • Very basic algorithm.
  • It's Stable Sorting algorithm.
  • In place.
  • Not suitable for large data sets.
function insertionSort(arr) {
    for (let i = 1; i < arr.length; i++) {
      
        // Start comparing current element with every element before it
        for (let j = i - 1; j > -1; j--) {
          
            // Swap elements as required
            if (arr[j + 1] < arr[j]) {
                [arr[j + 1], arr[j]] = [arr[j], arr[j + 1]];
            }
        }
    }
    return arr;
}
Insertion Sort - JavaScript
Insertion Sort visualize | Sorting | Algorithms | HackerEarth
Visualize your learning on Insertion Sort to improve your understanding of Algorithms.
5 Sorting Algorithms for Coding Interviews
Insertion Sort Visualiser - HackerEarth

4. Heap Sort

Heap Sort - GeeksForGeeks - YouTube

Heap Sort is a comparison based sorting technique based on Max Heap. We first place the maximum element at the root and then poll repeatedly till heap is empty.

  • It's an unstable sort.
  • array-based, space-efficient.
// Create Max Heap
function maxHeap(arr, i) {
    const left = 2 * i + 1;
    const right = 2 * i + 2;
    let max = i;

    if (left < arrLength && arr[left] > arr[max]) {
        max = left;
    }

    if (right < arrLength && arr[right] > arr[max]) {
        max = right;
    }

    if (max != i) {
        swap(arr, i, max);
        maxHeap(arr, max);
    }
}

function swap(arr, i, j) {
    const temp = arr[i];

    arr[i] = arr[j];
    arr[j] = temp;
}

function heapSort(arr) {
    arrLength = arr.length;

    for (let i = Math.floor(arrLength / 2); i >= 0; i -= 1) {
        maxHeap(arr, i);
    }

    for (i = arr.length - 1; i > 0; i--) {
        swap(arr, 0, i);
        arrLength--;

        maxHeap(arr, 0);
    }
    return arr;
}
Heap Sort - JavaScript
Heap Sort Tutorials & Notes | Algorithms | HackerEarth
Detailed tutorial on Heap Sort to improve your understanding of Algorithms. Also try practice problems to test & improve your skill level.
5 Sorting Algorithms for Coding Interviews
Heap Sort Tutorial - HackerEarth

5. Bubble Sort

Bubble Sort - HackerRank - YouTube

Bubble Sort works by repeatedly swapping the adjacent elements if they are in wrong order.

  • Very basic algorithm.
  • It's Stable Sorting algorithm.
  • In place.
  • Not suitable for large data sets.
function bubbleSort(arr) {
    let noSwaps;
    for (let i = arr.length; i > 0; i--) {
        noSwaps = true;
        for (let j = 0; j < i - 1; j++) {
            if (arr[j + 1] < arr[j]) {
                // Swap
                [arr[j + 1], arr[j]] = [arr[j], arr[j + 1]];
                // Make 'noSwaps' false
                noSwaps = false;
            }
        }
        // End the iterations if there were no swaps made in one full pass
        if (noSwaps) {
            break;
        }
    }
    return arr;
}
Bubble Sort - JavaScript
Bubble Sort visualize | Sorting | Algorithms | HackerEarth
Visualize your learning on Bubble Sort to improve your understanding of Algorithms.
5 Sorting Algorithms for Coding Interviews
Bubble Sort Visualiser - HackerEarth

It's terrible, just explaining that should be enough.

Big O

5 Sorting Algorithms for Coding Interviews
Big-O Cheat Sheet

Choice of Sorting algorithm in an interview is done based on time space trade-offs among other factors.

Algorithm Time Complexity Space Complexity
Best Average Worst Worst
Quick Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(log(n))
Merge Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(n)
Heap Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(1)
Bubble Sort Ω(n) Θ(n^2) O(n^2) O(1)
Insertion Sort Ω(n) Θ(n^2) O(n^2) O(1)
Big-O Algorithm Complexity Cheat Sheet (Know Thy Complexities!) @ericdrowell
5 Sorting Algorithms for Coding Interviews
Big-O Cheat Sheet
Sorting Algorithms Animations
Animation, code, analysis, and discussion of 8 sorting algorithms on 4 initial conditions.
5 Sorting Algorithms for Coding Interviews
Sorting Algorithms Animations

Conclusion

In real world, variations of above sorting algorithms are used.

For example Python uses an algorithm called Tim Sort which is a hybrid sorting algorithm, derived from Merge Sort and Insertion Sort, designed to perform well on many kinds of real-world data.

Algorithm Time Complexity Space Complexity
Best Average Worst Worst
Tim Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)

Hope the above resources helped you. Please let me know your thoughts down below.

]]>
<![CDATA[Arrays and 12 related Data Structures & Algorithms for Coding Interviews]]>https://www.derpycoder.com/arrays-and-12-related-data-structures-algorithms-for-coding-interviews/5fdee84af3b7a700390b63a3Sun, 20 Dec 2020 08:29:46 GMT

Lets begin with the basic data structure, in the data structure line up.

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value.

const arr = [1, 2, 3];

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

// Output:
// 1
// 2
// 3
Array Data Structure JavaScript Example
1-D Tutorials & Notes | Data Structures | HackerEarth
Detailed tutorial on 1-D to improve your understanding of Data Structures. Also try practice problems to test & improve your skill level.
Arrays and 12 related Data Structures & Algorithms for Coding Interviews
Array HackerEarth Tutorial

It starts out simple, however this data structure is very versatile and can be used to solve lots of problems.

Arrays and its related Data Structures & Algorithms are used to solve a lot of problems.

Data Structures

All the Data Structures mentioned below, use Array underneath in one way or another.

1. Sorted / Unsorted

There's difference between sorted & unsorted array, in terms of time complexity and problem approaches.

For instance, search becomes faster in a sorted array, but insertion gets slower.

Search, insert and delete in an unsorted array - GeeksforGeeks
A computer science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Arrays and 12 related Data Structures & Algorithms for Coding Interviews
Operations on Unsorted Array - GeeksForGeeks
Search, insert and delete in a sorted array - GeeksforGeeks
A computer science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Arrays and 12 related Data Structures & Algorithms for Coding Interviews
Operations on Sorted Array - GeeksForGeeks

2. Strings

String is like an Array of characters, and all of the Array sub problems / approaches can be applied to it as well.

However it adds lot more variations. Like Sub-string, Palindrome, Regular Expression, ...

const str = "Hello, World";

console.log([...str]);
// ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]

// or

console.log(str.split(''));
// ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
Strings to Array - JavaScript

3. Multi-dimension

Array of arrays is called a matrix.

It can be any number of dimensions. However the common one is a 2D matrix.

It has Pixel Grid, Shortest Path, Graph, Island style problems.

const twoDArr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log(twoDArr); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2D Array - JavaScript
Multi-dimensional Tutorials & Notes | Data Structures | HackerEarth
Detailed tutorial on Multi-dimensional to improve your understanding of Data Structures. Also try practice problems to test & improve your skill level.
Arrays and 12 related Data Structures & Algorithms for Coding Interviews
Multi-dimensional Array Tutorial - HackerEarth

4. Min Heap / Max Heap

It's a complete binary tree, stored in an array. It has few formulas you need to remember and then you are golden.

Variations include: Min heap, Max heap.

In an interview, we don't have to write the whole thing. Instead we can just pretend we already have the data structure ready, as a separate function.

import heapq

li = [5, 7, 9, 1, 3]

heapq.heapify(li)
print(li) // [1, 3, 9, 7, 5]

heapq.heappush(li, 4)

print(li) // [1, 3, 4, 7, 5, 9]
Min Heap - Python
Heaps - HackerRank - YouTube

5. Hash Table

It's is a data structure which stores data in an associative manner i.e. in an array format, where each data value has its own unique index value. Access of data becomes very fast if we know the index of the desired data.

We don't need to know how to implement a Hash Table from scratch to be able to use it.

const hashMap = {
    'hello': 'world',
    'hakuna': 'matata',
};

console.log(hashMap['hakuna']); // 'matata'
Hash Map - JavaScript
Hash Tables - HackerRank - YouTube

6. Stack / Queue

Stack follows LIFO, while Queue follows FIFO.

We can either use array for stack & queue implementation, or a linked list. Later being the better approach if random access is not required.

const stack = [1, 2, 3];

stack.push(4);      // Push at the end of the array
stack.pop(4);       // Pop from the end

console.log(stack); // [1, 2, 3]

const queue = [2, 3, 4];

queue.unshift(1);   // Enqueue at the beginning of the array
queue.pop();        // Dequeue at the end

console.log(queue); // [1, 2, 3]
Stack & Queue with Array - JavaScript
Stacks & Queues - HackerRank - YouTube

Algorithms

All the Algorithms mentioned below use Array one way or other.

It's an efficient search mechanism that is done on a sorted array. It takes Log n time, instead of linear time to search through the array.

It is similar to a dictionary search humans perform.

var search = function(nums, target) {
    let low = 0, high = nums.length - 1;
    
    while(low <= high) {
        mid = parseInt((low + high) / 2);
        
        if(nums[mid] == target) {
            return mid;
        } else if(target > nums[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    
    return -1;
};
Binary Search - JavaScript
Binary Search - HackerRank - YouTube

2. Sliding Window

It's a small category compared to the rest of the line up, however it's worth a mention.

Problems include: Longest Sub-string, Consecutive 1s, ...

3. Two Pointers

This approach will open up doors for solving few tricky problems.

Like: Linked List Cycle, String Reversal, ...

4. Sorting

A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements.

const arr = [5, 4, 3, 2, 1];

console.log(arr.sort((a, b) => a - b)); // [1, 2, 3, 4, 5]
Inbuilt Sort - JavaScript
Merge Sort- HackerRank - YouTube

5. Greedy

A greedy algorithm is a simple, intuitive algorithm that is used in optimisation problems. The algorithm makes the optimal choice at each step as it attempts to find the overall optimal way to solve the entire problem.

6. Dynamic Programming

Dynamic Programming is mainly an optimisation over plain recursion. The idea is to simply store the results of sub-problems, so that we do not have to re-compute them when needed later.

This is the biggest and toughest category of them all.

We shall conquer this category eventually.

Dynamic Programming - HackerRank - YouTube

Conclusion

This was just an introduction to the vast category that is Arrays. I will eventually write about each of the above categories.

Let me know your thoughts below.

]]>
<![CDATA[LeetCode 226 - Invert Binary Tree]]>https://www.derpycoder.com/leetcode-226-invert-binary-tree/5fdd878ff3b7a700390b622eSat, 19 Dec 2020 07:55:23 GMT

While I was just beginning my preparation, I came across this:

by Max Howell

It maybe sarcastic, but big companies still choose to interview using this method and there's no way around it if we want to get in!

The quote scared me a bit as I am not the one who wrote Homebrew! I was merely starting out.

So only way to get over that fear, I feel this question to be the first one I should write about.

Question:

LeetCode 226 - Invert Binary Tree
LeetCode 226 - Invert Binary Tree
Loading...
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
LeetCode 226 - Invert Binary Tree
LeetCode 226 - Invert Binary Tree

Solution:

a. Recursive

A simple preorder traversal is the best way forward.

While visiting the root node, we swap the left & right child and then visit the left & right child respectively.

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    // Recursion must have a base condition.
    if(root == null) {
        return root;
    }
    
    // A simple swap of let & right nodes of a root.
    let tmp = root.right;
    root.right = root.left;
    root.left = tmp;
    
    // Recurse on both sides in Preorder Traversal.
    invertTree(root.left);
    invertTree(root.right);
    
    return root;
};
LeetCode 226 - Invert Binary Tree - Recursive JavaScript Solution

b. Iterative

Implement the preorder traversal in iterative manner.

While visiting the root node, we swap the left & right child and then visit the left & right child respectively.

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    if(root == null) {
        return root;
    }
    
    let stack = [root], node, tmp;
    
    // Use stack as this problem is a variant of Depth First Traversal
    while(stack.length) {
        node = stack.pop();
        
        if(node == null) {
            continue;
        }
        
        // Simple swap of left & right node
        tmp = node.right;
        node.right = node.left;
        node.left = tmp;
        
        stack.push(node.left);
        stack.push(node.right);
    }
    
    return root;
};
LeetCode 226 - Invert Binary Tree - Iterative JavaScript Solution

Conclusion

It's one of the most easy problem, that doesn't seem easy till you do it yourself.

What did you think? let me know down below.

]]>
<![CDATA[Crack the Coding Interview at Big Four in 10 Steps]]>https://www.derpycoder.com/crack-the-coding-interview-at-big-four-in-10-steps/5fdc3401f3b7a700390b5e49Fri, 18 Dec 2020 09:12:11 GMT

In a previous post, I put forth 15 reasons FAANG companies are worth the effort of prepping for interview. It would be unfair if I don't post how we can make it happen!

A little disclaimer before we begin. I have yet to get an interview for any of the Big Four. I'm a fellow aspirant such as yourself, but having prepped for it several times I'm a bit used to the process.

Several resources exist and I'm going to lay them out in an organised fashion for your kind perusal.

1. Pick a Language

Crack the Coding Interview at Big Four in 10 Steps
Photo by Robo Wunderkind / Unsplash

Use whatever you already know.

However, you have to bear in mind that:

  • Speed matters in a coding interview, as each round lasts from 40 - 50 minutes.
  • You shouldn't reinvent the cycle, i.e. you should be able to use inbuilt data structures.
  • Verbosity can be your enemy.
  • Coding interview is not a coding competition, so performance of the language doesn't matter.

So keeping the above points in mind, I would suggest you to choose a simpler language. Perhaps dynamically typed, interpreted one, with lots of inbuilt data structures.

You can't go wrong picking up Python, or JavaScript for the coding interview.

a. Python:

FreeCodeCamp: Learn Python - Full Course for Beginners - YouTube

A pseudo-code like language, best suited for interviews.

Learn Python 3 | SoloLearn
Python is one of the most widely used programming languages, and it’s perfect for beginners and newbies. From web development to machine learning you can do everything with Python.
Crack the Coding Interview at Big Four in 10 Steps
SoloLearn Python

b. JavaScript:

FreeCodeCamp: Learn JavaScript - FUll Course for Beginners - YouTube

Best choice, if you already have a background in web development.

Learn JavaScript | SoloLearn
SoloLearn’s tutorial covers the fundamentals of JavaScript. You will learn how to make websites more interactive, change content, validate forms, create cookies, and utilize many other functions of JavaScript.
Crack the Coding Interview at Big Four in 10 Steps
SoloLearn JavaScript

2. Pick Resources

Don't get lost in the sea of products, websites, books. Rather settle for the following list of resources, as they are more than enough to get you where you want to go.

I would recommend getting a book to orient yourself, followed by lots of practice in an online judging portal, followed by YouTube to help you when you get stuck.

a. Books:

  • Cracking the Coding Interview.
  • Elements of Programming Interview.
  • Programming Interviews Exposed.

b. Websites:

Programming - InterviewBit
Learn and Practice on almost all coding interview questions asked historically and get referred to the best tech companies
Crack the Coding Interview at Big Four in 10 Steps
Interview Bit for a linear walk-through
jwasham/coding-interview-university
A complete computer science study plan to become a software engineer. - jwasham/coding-interview-university
Crack the Coding Interview at Big Four in 10 Steps
Coding Interview University
Derpy Coder
If you’re someone, just starting out in the industry or looking to better yourself or trying to find your way in life. You have come to the right place!
Crack the Coding Interview at Big Four in 10 Steps

c. YouTube Channels:

HackerRank's Algorithm & Data Structure Playlist - YouTube
Gaurav Sen's System Design Playlist - YouTube
Tushar Roy's Dynamic Programming Playlist - YouTube

3. Online Judges

Crack the Coding Interview at Big Four in 10 Steps
LeetCode

Just reading code isn't going to make you a great coder. You have to practice as well.

And best way to practice and get validated for your approach is to write code in an online portal.

There are several online judges, like Topcoder, Codechef, HackerRank, SPOJ.

However best of the best is LeetCode. So don't you waste your time trying to find the best one of the lot, as I have already done the research on your behalf.

LeetCode's is the best because of:

  • Beautiful & Minimalist UI, with proper categorisation of questions.
  • Succinct questions, which doesn't dawdle.
  • Good deal of language support, from interpreted to compiled languages.
  • Great community, so if you can't find solution to a question, chances are people have discussed the solution in a separate tab.
LeetCode - The World’s Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
Crack the Coding Interview at Big Four in 10 Steps
LeetCode

4. Big O

Crack the Coding Interview at Big Four in 10 Steps
Big O Cheat Sheet

Apart from remembering the common ones, you have to learn to analyse the complexity of the code you are writing.

Cracking the Coding Interview has a chapter explaining Big O in great detail.

Big-O Algorithm Complexity Cheat Sheet (Know Thy Complexities!) @ericdrowell
Crack the Coding Interview at Big Four in 10 Steps
Big O Cheat Sheet

5. Data Structures

Crack the Coding Interview at Big Four in 10 Steps
Photo by Daniel / Unsplash

Data Structure is the approach of storing data so as to make it easy to operate on. Each structure has their advantage, which is a topic for another day.

There's tons of data structure, but the ones interviewers are looking for are as follows:

  • Array
    • String
    • Matrix
  • Linked List
  • Stack & Queues
  • Heap, Hash Table
  • Tree
    • Binary Tree / Binary Search Tree
    • Trie
  • Graph

6. Algorithms

Crack the Coding Interview at Big Four in 10 Steps
Photo by Javier Esteban / Unsplash

Algorithms are operations performed on data structures, to come up with the solution to problems.

There's countless algorithms in the wild. However Coding Interviews rarely include those. So it's better to focus on the limited category presented below:

  • Array
    • Two Pointers
    • Binary Search
    • String Manipulations
    • Sliding Window
    • Matrix
  • Bit Manipulations
  • Tree & Graph
    • BFS
    • DFS Traversals - Preorder, Inorder, Postorder
    • Union Find
  • Recursion / Iteration
  • Divide & Conquer
  • Greedy
  • Backtracking
  • Sorting
    • Quick Sort
    • Merge Sort
    • Insertion Sort
    • Heap Sort
    • Bubble Sort
  • Dynamic Programming
Merge Sort visualize | Sorting | Algorithms | HackerEarth
Visualize your learning on Merge Sort to improve your understanding of Algorithms.
Crack the Coding Interview at Big Four in 10 Steps
HackerEarth - Sorting Algorithm - Visualizer
Sorting Algorithms Animations
Animation, code, analysis, and discussion of 8 sorting algorithms on 4 initial conditions.
Crack the Coding Interview at Big Four in 10 Steps
All Sorting Algorithms Animated

7. System Design

Crack the Coding Interview at Big Four in 10 Steps
Photo by Christina @ wocintechchat.com / Unsplash

Candidates with 4+ years experience will be questioned on Low Level & High Level design in their interview.

System Design is not an exact science, hence you aren't expected to make the best design from the get go. Rather your approach and flexibility is monitored in these rounds.

HighScalability is a great place to see how other big companies approach their system design problems.

Then there's YouTube.

Gaurav Sen's System Design Playlist - YouTube

8. Behavioral Questions

Crack the Coding Interview at Big Four in 10 Steps
Photo by Helena Lopes / Unsplash

In the book, Cracking the Coding Interview, you will find a precise guide to prepare for the behavioural interview. See: Cracking the Soft Skills.pdf

You must prepare for each company you are about to interview for, as the expectations are different based on the culture the company portrays.

For example Amazon expects candidates to answer each of the questions, justifying the Leadership Principles.

Amazon’s global career site
We’re a company of pioneers. It’s our job to make bold bets, and we get our energy from inventing on behalf of customers. Success is measured against the possible, not the probable. For today’s pioneers, that’s exactly why there’s no place on Earth they’d rather build than Amazon.
Crack the Coding Interview at Big Four in 10 Steps
Amazon's Leadership Principles

9. Resume Preparations

Crack the Coding Interview at Big Four in 10 Steps
Photo by Markus Winkler / Unsplash

Application Tracking System is the modern gatekeeper, stopping our resume's from ever getting noticed by a real person. So prepare your resume with that in mind.

  • Maybe go with a resume builder, or write your own.
  • Always submit a PDF format.
  • Avoid tables.

Soon I'll be adding a guide to make the best of the best resume.

10. Referral

Crack the Coding Interview at Big Four in 10 Steps
Photo by Elia Pellegrini / Unsplash

Forget applying on the online portal, as your applications will go unnoticed.

Your best bet, after having spent months on prepping for the coding interview, is to get a referral from someone who works for the company.

Conclusion

Starting is the most difficult part of the process, followed by discipline & perseverance to continue down this path. So start your journey today.

What do you think? Let me know your thoughts down below, and subscribe if you want to be updated as and when I post guide on some of the steps mentioned above!

Good luck with your future endeavour.

]]>
<![CDATA[FlatPickr: The best Date Picker Library of 2021]]>https://www.derpycoder.com/flatpickr-the-best-date-picker-library-of-2021/5fd6036a872c5800390e2e1cSun, 13 Dec 2020 12:35:25 GMT

After spending a few days, testing out lots of date pickers, I have found FlatPickr to be the best date picker so far. Here's Why:

FlatPickr: The best Date Picker Library of 2021 FlatPickr: The best Date Picker Library of 2021 FlatPickr: The best Date Picker Library of 2021 FlatPickr: The best Date Picker Library of 2021 FlatPickr: The best Date Picker Library of 2021 FlatPickr: The best Date Picker Library of 2021

Demo

See: Examples

Features

1. Themes

FlatPickr has 8 themes, all separated into different CSS Files that can be imported.

See: Themes.

2. Localization

FlatPickr can be localized locally or globally.

See: Localization.

3. Plugins

FlatPickr supports plugins, like Confirm Date, Week Selection, Range, etc.

See: Plugins.

4. Mobile

When FlatPickr detects a mobile browser, it turns the date input into a native date/time/datetime input.

Native datetime selection provides a UX that’s familiar to the user and is superior to most web-based solutions.

See: Mobile Support.

Conclusion

The API is straightforward, UI is beautiful, and UX just rocks. If those don't make it the best of the best, I don't know what does!

Let me know what you think, below.

]]>
<![CDATA[15 reasons FAANG companies are worth the effort]]>https://www.derpycoder.com/15-reasons-faang-companies-are-worth-the-effort/5fcf1049369b0800392194ffThu, 10 Dec 2020 05:32:40 GMT

Interviewing at FAANG is daunting, heck even getting an interview at one of them is difficult, and downright unfair. But getting into one is worth it!

FAANG is an acronym for Facebook, Amazon, Apple, Netlifx, Google.

Sure you may not like what Facebook stands for, or Amazon's for that matter. But that's a topic for another day.

However that's not the reason I'm writing this post.

I'm merely reiterating some of the reasons you already know, but you need to be constantly reminded, to keep true to your goals.

Also this list is entirely from an outsider's perspective, I may get lucky enough for an interview someday and then after joining I might have the privilege to write why you shouldn't get into one!

Reasons

1. Swagger

15 reasons FAANG companies are worth the effort
Photo by Rajeshwar Bachu / Unsplash

FAANG engineers are some of the smartest people in the world, and that's a fact. Imagine getting in one, you immediately get certified as the best of the best.

Bye bye impostor syndrome, as working in one of those is a huge confidence booster. As body building does to your body, getting into a top tier institution does the same to your brain.

Imaging sitting in a bar and name dropping working at any of the FAANG, the kind of attention you get from people is phenomenal.

2. Perks

15 reasons FAANG companies are worth the effort
Photo by Eric Nopanen / Unsplash

Huge parties, paid leaves, health insurance to name a few. Checkout their respective sites for all the details.

3. Free food

15 reasons FAANG companies are worth the effort
Photo by CHUTTERSNAP / Unsplash

All you can eat food.

People born with silver spoon in their mouth or people with spouse that cooks may not realise this, but having this option is just tremendous.

We don't have to shell out large portion of our earnings to eating, nor do we have to rack our brain to figure out where to eat. (One less decision to fatigue us!)

4. Salary

15 reasons FAANG companies are worth the effort
Photo by Viacheslav Bublyk / Unsplash

A substantial salary is a must.

If you earn 1/10th of the FAANG salary, you will be able to save or invest 1/10th the amount. Thereby postponing your early retirements plan.

Not just saving or investment, being able to afford a house, being able to ride whatever you want is also a huge plus point.

Imagine not needing to use your credit card to purchase something you desire.

5. Stock

15 reasons FAANG companies are worth the effort
Photo by Austin Distel / Unsplash

Stock options sweetens the deal even further.

There's no better way to feel invested, than to get stocks when you join a company. The more the better.

And if you have seen the graph of stock prices of FAANG companies, you know what you will be getting in the long run!

6. World Travel

15 reasons FAANG companies are worth the effort
Photo by Jose Llamas / Unsplash

Outing to foreign countries!

I was surprised to learn that once a year, a outing to different country is part of the deal.

Imagine not going to your local resort for a change, and visiting an entirely different country!

7. Better Employment Opportunity

15 reasons FAANG companies are worth the effort
Photo by Rhii Photography / Unsplash

Ex FAANG engineers have a demand unlike anything.

It's a resume seller. Perhaps ATS systems are tuned to check if an applicant is ex Google or ex Facebook engineer!

It's like graduating from a Ivy League college!

8. Like Minded People

15 reasons FAANG companies are worth the effort
Photo by Marvin Meyer / Unsplash

Nerd out with others that have the same passion as you. I always hoped to find people that are geeks like me from college days.

Not only you get to share what you learnt, you also get to learn from others experience.

You don't get that in a small company, where all your colleagues can think about or do is go home, go to a bar, go to movies...

I understand work life balance is a thing, but if people don't even bother to better themselves in their free time then what's the point?

9. Startup Possibility

15 reasons FAANG companies are worth the effort
Photo by Mika Baumeister / Unsplash

Having an idea is well and good, but execution matters even more.

You might know the pain of mentioning an idea to your peers, for your peers to say no, only to see someone else make it happen!

Since the people you are working with will be of same calibre as you, there's a high chance that you will be able to execute your dream together.

10. Casual Clothing

15 reasons FAANG companies are worth the effort
Photo by Annie Spratt / Unsplash

Ever had that one annoying guy from HR, constantly pester you to wear clothes different from what you are comfortable in?

I have, and it always strikes a nerve.

If wearing casual makes me feel comfortable and I can perform better, what's the point of wearing business attire the whole time?

Instead of making us wear business attire, maybe focus on getting ergonomic desks & chairs. That would at least improve our performance!

11. Flexibility to Change Teams

15 reasons FAANG companies are worth the effort
Photo by Glenn Carstens-Peters / Unsplash

If you have never felt stuck with a team, let me tell you it's exhausting to say the least.

Either they are incompetent, or the manager sucks, or maybe you stopped vibing with the project. Whatever it may be, having a choice to switch teams is a must.

And working in a big company, that has loads of projects on going simultaneously is the best.

12. Shared Workload

15 reasons FAANG companies are worth the effort
Photo by krakenimages / Unsplash

Everyone's a heavy lifter, and they got your back if you falter.

If you have never cried for help with some work, that is just beyond your capabilities, or that is so mundane that you feel like killing yourself, then you can't appreciate this.

Being able to rely on a colleague and helping each other out shouldn't be an issue in a big company, filled to the brim with smart people.

13. Tangible Product

15 reasons FAANG companies are worth the effort
Photo by Neil Soni / Unsplash

Working on an app you use daily, like say YouTube or Apple Maps, is way more satisfying than working on something obscure, which you can't access or which is just for internal use!

And being able to say "You're Welcome!" when your friend praises an App's feature is a cherry on top.

14. In House Libraries

15 reasons FAANG companies are worth the effort
Photo by Perfecto Capucine / Unsplash

It's not a secret, that big companies have lots of internal tools that make life of engineers easier.

Even before React or GraphQL came into lime light, they have been used extensively internally.

Being privy to these tools can be eye opening, and may lead you to making something incredible of your own!

15. Best Workplace

15 reasons FAANG companies are worth the effort
Standing Desks, Superior Chairs, Monitor Arms, Bluetooth Accessories

Superior desks, comfy chair, best of the best devices.

If you have ever worked for a small or medium company, you would know how little they care about ergonomics. Workspace is tightly packed, desks aren't adjustable, chairs are cheap.

If you are an absolute nerd and don't care about any of the stuffs mentioned above, you must care about this.

You don't want to end up in a company with a lacklustre office space, it's nothing but lifetime of lingering pain and suffering, for a short duration you spend your time there.

Conclusion

Which reason attracts your attention the most and which company do you want to get into? Let me know in the comments below.

]]>
<![CDATA[Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021]]>https://www.derpycoder.com/ghost-pro-20-reasons-that-make-it-the-best-choice-for-bloggers-in-2021/5fc9c253bcc44500393fad13Sun, 06 Dec 2020 14:06:42 GMT

By the end of this post, I hope I will have convinced you to choose Ghost (Pro) for your blog.

Since I am using Ghost (Pro) it is only fitting that my first post be a review of the product. Also it makes it easy to choose the topic for the first post I want to write about!

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021 Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021 Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021 Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021 Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021

I’m a fairly technical guy & I have always made the whole website myself. I thought making everything by myself was the best way forward, thereby never using any libraries or templates that would prevent me from reinventing the cycle.

That changed however after making several websites. Several tech changes, countless bugs later, I am done with the manual process.

After assessing several blogging platforms, & weighing them with several criteria, I have chosen Ghost (Pro) to be my partner in crime.

Comparisons

Ghost website has an extensive collection of comparison with alternatives. See Ghost Alternatives page for more.

1. Ghost vs React, Angular or Vue JS

There are several reasons Ghost easily wins out this comparison:

  • Single Page Apps are Development, Maintenance & Update nightmare!
  • Tech changes constantly, so next time you open your code base, code would have rotten!
  • Content update would be a hassle, unless you use Ghost as a Headless CMS.
  • You need to handle Security, SEO, Speed all by yourself.
  • You have to take care of Auth.
  • You have to do everything listed on Ghost's features, that too manually.
  • You'll certainly be out of budget, if you decide to outsource the development and potentially end up inheriting a mess.
  • You'll encounter Dependency hell that is inherent with NPM.

2. Ghost vs Static Site Generators like Hugo, Gatsby

Static Site Generator together with Headless CMS make one master of Jamstack, a modern approach to building secure websites.

But after my little foray into using several Static Site Generators, here's how they pale in comparison to a full fledged solution like Ghost (Pro):

  • Every new change you make, requires a build to happen, as pages are generated in a compile stage. So additional tooling like Netlify is required.
  • Every change takes time, even if you use a fast builder like Hugo, unlike Ghost where changes are instantaneous.
  • Doesn't come bundled with a CMS, so you definitely need something like Ghost CMS, Netlify CMS, or pay some more for a solution
  • Themes are not that great. After going through the whole catalogue of themes, present in Get Hugo Themes, Hugo Themes Free, Hugo Themes, Gatsby JS Starters, Hexo Themes, I can say for certain that Ghost Marketplace has some of the best Themes on offer from a great community.
  • Modifying anything and doing anything more than the theme with Hugo or Gatsby is a lot more involved process.

3. Ghost vs Medium, Tumblr, LinkedIn

Sites like Medium, Dev.to, Write.as or micro-blogging site like have low barrier to entry, and may feel like the best choice for non technical people.

But I would like you to reconsider, because of several issues they posses:

  • You don't own your content.
  • Site policy can change overnight.
  • Your account can be blocked.
  • Lower potential for earning.
  • You can't have fans of your own, as you don't have any user access.
  • Restrictive theming capability.
  • Pay-walled content.

For a detailed argument against Tumblr, read the official versus post by Ghost: Ghost VS Tumblr.

& For a detailed argument against Medium, checkout post by Ghost team: Ghost VS Medium.

4. Ghost vs WordPress, Wix, Joomla

Those are ghost of the past. (Pun intended)

  • Those are slow as heck.
  • WordPress is one complex software.
  • Securing the site yourself, can be a nightmare.
  • Plugins slow down the site and can introduce vulnerability too.
  • You have to pay for each feature you integrate.
  • Old way of hosting your site means, you have to get your hands dirty. Of course managed hosting is a thing, but other demerits still linger.
  • Basically it's boomer tech, something that didn't age well though!

For a detailed argument against WordPress, read what team behind Ghost have to say: Ghost vs WordPress.

5. Ghost vs SquareSpace, Blogger

Ask yourself, are you really in charge when you choose these?

  • Old tech, limited customisation.
  • Limited theme & designs for blogger.
  • SquareSpace is pricey.
  • Not open source.
  • With blogger, your data is owned by Google.
  • Newsletter isn't even offered, which is core to the blogging experience!

Read a post by Ghost team, which plainly mentions why Ghost is way better: Ghost vs Squarespace.

Features

Enough with the comparisons, next comes the fun part.

All the features of Ghost that make it worthwhile for every blogger!

See: Ghost Features Page or Exhaustive Feature Index for all of them.

6. Eye Popping Themes

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Okiro theme by Fueko

Themes for Ghost are some of the best ones I ever encountered. The community behind theme development is great. It's mind boggling how premium the themes feel compared to a free alternative or any other platform.

Some of the theme developer behind Ghost, do build themes for other platforms, but some like Fueko build exclusively for Ghost, which says something about the platform I'm rambling about!

Some of my favourite themes from the Ghost Marketplace are:

  • Newsportal by ElectronThemes.  (It's the theme I'm using for this blog!)
  • Okiro by Fueko.

You can find the full listing either in the Marketplace, or Themeforest!

The response time from theme creators is also commendable. For instance:

  • Fueko stated that they can go above and beyond to implement any feature request made by a premium customer.

7. Elaborate Tutorials & Documentation

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Documentation

Tutorials made by the Ghost team, and so are the Documentation accompanying the site.

I wanted to add Table of Content  and Google News Sitemap. I coveted those, in the theme I chose, but they were missing.

So I looked around and found aptly named tutorials on those (which shows how feature rich Ghost really is):

  • How to add a table of contents to your Ghost site?
  • How to create a Google News Sitemap with Ghost?

And here we are, both TOC & Sitemap integrated into the site. You can see the sitemap here & the table of contents in non AMP view of the site if you go to the top.

8. Built-in SEO

If you have implemented SEO all by yourself, you'll know the huge headache that it is!

From Sitemaps, Robots.txt, to Rich Social Cards, to Google AMP, Ghost has it all. It is simplified to the point where, you won't even know it is happening under the hood!

I don't know what else to say that would further prove how much of a lifesaver Ghost (Pro) is!

See: Exhaustive Feature Index.

9. Powerful yet Simple Editor

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Main Ghost Dashboard

The content management system is just spot on. You can start as draft, publish your posts on a schedule, or immediately release your post to the wild.

Everything is user friendly. Be it adding primary or secondary links on your sites, tags, pages, or posts!

Every feature you can dream of, it's there. Member management, staff management, import / export of data, heck even dark mode is there.

Code Injection can be done on header and footer site wide or per page basis! Imagine how easy it gets to add any external library. You don't have to fire up the VSCode anymore for a minor change.

It's fast too, I was able to easily add in 5,000 words for an article as a test, and the editor didn't even sweat.

Editor works smoothly on desktops, mobile, even on the iPad Pro (With some minor issues).

There's alternatives to the official Editor, of course, you can easily integrate iA Writer, Ulysses, etc. See all the Integrations for yourself.

See: Ghost Editor.

10. AMP

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
AMP View of this post

Never knew it was this easy. I didn't even have to lift a finger to make this happen!

Try adding "/amp" to the end of any post you see on this site and you can see the AMP view of the post. (I have customised the AMP view of my site to match the main theme!)

Google will treat your site with some love, once it sees amp pages!

See: AMP Integration.

Ghost Pro - 20 Reasons that make it the best choice for bloggers in 2021
By the end of this post, I hope I will have convinced you to choose Ghost Pro for your blog.
Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Ghost Pro - 20 Reasons that make it the Best Choice for Bloggers in 2021 - AMP View

11. Open Source & Non-Profit

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Open Source + Non-Profit

Which means, no transaction fees on any earnings. You keep what you earn!

Any recurring payment we do, goes towards the development of Ghost.

And further development of Ghost, means more features for you and me!

See: About Ghost.

12. Email Authentication

Oh the horror that is Authentication! Securely collecting and storing passwords. OAuth, SSO, Mobile Auth!

Of Course there's free services like Firebase Auth, but it doesn't even come close to the Ghost Auth's simplicity.

Ghost (Pro) comes with email authentication & advantages of using Email Auth are:

  • Low friction sign-up and sign-in.
  • Lower risk of password reuse across applications, which can undermine security of even well-selected passwords.
  • The ability to authenticate a user while also verifying that the user is the legitimate owner of an email address.
  • A user only needs an accessible email account to sign in. No ownership of a phone number or social media account is required.
  • A user can sign in securely without the need to provide (or remember) a password, which can be cumbersome on a mobile device.

See: Exhaustive Feature Index.

13. Newsletter

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Newsletter I received for this Post

Ghost (Pro) comes with Newsletter as part of the offering.

Else you would have to rely on an external service. One more expenditure averted and one less thing to work on.

While publishing a new post, you can even choose to send newsletter to members or paid members.

You can add custom content to your post that will only show up in the newsletter, and not on the website.

Thank you note to your subscriber or a secret download link for consumer delight, is absolutely possible.

See: Send Newsletter.

14. Membership

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Ghost Member Portal

This is honestly the biggest reason to pick this up.

No annoying ads, just you your content and your fans, that's the vision Ghost (Pro) is aiming for.

Users mostly use adblock anyways, plus you have to beg them to disable the ads, by showing an annoying pop up, that is likely to piss off readers.

Instead you just post some premium content for free, some in exchange for membership, and some more in exchange for money.

Of course, that doesn't stop you from adding Ads later on, but still Membership might be more reliable form of income, provided content is regular and top notch.

See: Member Setup.

15. Subscription with Stripe

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Stripe Custom Payment Page

Seamless payment with Stripe, which also supports Apple Pay, so Apple users can have a hassle free experience.

  • No hassle remembering or securing customer card info.
  • Plus it's much better than Paypal!
  • Customising the payment page is a breeze on Stripe.
  • It just works, you don't have to fumble with it yourself!

See: Stripe Integration.

16. Countless Integrations

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Ghost Integrations

The amount of tech that can be integrated with Ghost is immeasurable.

iFrames, inline Html, Twitter, Instagram posts, anything and everything works.

Top it up with Zapier integrations and you are golden. Sky's the limit when it comes to automation overlord like Zapier.

You can send email when a member subscribes, automatically post to Social Networks.

See: Exhaustive Feature Index.

17. Blazing Fast

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Ghost (Pro) Loading Speed

Changes take literally milliseconds.

One refresh, and you can see the updated site with the changes you made.

Things that make it fast:

  • The site uses Brotli compression, which is superior to gzip. So files are smaller and arrive to you faster.
  • HTTP/2 protocol is used, so content arrive with less overhead than HTTP/1, it's a great speed boost.
  • Disk Caching is aptly utilised.
  • Super optimised themes, which even mention performance metrics on their page.
  • Architecture makes the difference as well. That however, is a topic for another day!

See: Exhaustive Feature Index.

18. Ghost's approach to Blogs

Ghost has well thought out & well curated list of features that makes it just right for blogging:

  • Search functionality, a must have.
  • Public & Private Tags.
  • Multi Author.
  • Prev/Next post navigation.
  • Related post suggestions.
  • Comment integration.
  • Social share.
  • Featuring posts.

See: Exhaustive Feature Index.

19. Ghost Pro

Spend less time on your server, more time on your site.

Ghost (Pro) is a fully managed, no nonsense service by the team behind Ghost.

In the beginning of this post, I did mention my trials & tribulations doing everything from scratch.

And blogging shouldn't be about behind the scenes, rather the writing of content, & marketing. Instead of spending 80% of the time on the back-end, a blogger should be able to spend 40% of their time on writing, & 60% of their time on promoting that content.

If you can implement all the feature mentioned above, then by all means do so.

Else, this is the way to hassle free blogging.

20. Pricing

Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Ghost (Pro) Pricing in a Nutshell

This diagram, taken from the Pricing page, says everything you need to know about how Ghost (Pro) simplifies life of a blogger!

Conclusion

This is the only post you should have to read to come to a conclusion that Ghost (Pro) wins out in all dimensions and in parallel universes too. (If those exist)

Ghost Pro: 15 Tips & Tricks to Spice up your Website
After using Ghost (Pro) for a while, I have discovered, learnt, & implemented a few niceties, that can help you while authoring content & beyond.
Ghost Pro: 20 Reasons that make it the Best Choice for Bloggers in 2021
Ghost Pro: 15 Tips & Tricks to Spice up your Website

If I couldn't convince you yet, checkout the Changelog for all the features in a reverse chronological order.

What do you think?

If I missed something, let me know in the comments down below, else leave your reaction. And maybe subscribe!

]]>