Text
NestJS + TypeORM + Postgres InMemory DB E2E testing

Photo by Ferenc Almasi on Unsplash
NestJS is a great opinionated and battery-included framework. The day I started using NestJS, there was no turning back. It adapts module-oriented design which makes the backend more versatile. With the help of Typescript, it enables dependency injections which makes testing super easy. NestJS integrates easily with major databases like MySQL, Postgres, Mongo, etc. It also comes with a handy CLI tool which makes scaffolding generation very easy. Basically, NestJS comes with a complete ecosystem.
Testing is one of the most important and a major part of any application development, NestJS by default uses Jest & Supertest for making unit tests & end-to-end testing jobs easier.
But recently in one of the projects I faced an issue with end-to-end testing. The project was built using NestJS + TypeORM + Postgres. Now with Postgres, there are not many options available for an in-memory database, the one I found pg-mem doesn't support the latest TypeORM versions. After digging into the error, I got the fix.
The actual issue with pg-mem was that in the latest versions of TypeORM, it uses a Postgres function to make some initial checks, this function was not available with the pg-mem library but the library had an option to write custom functions which solved my issue.
The workaround is really simple, we just need to create a pg-mem connection for TypeORM and replace it with the actual connection. So in our e2e test, the code will be:
describe('PhotoController (e2e)', () => { let app: INestApplication; let repository: Repository; beforeAll(async () => { const db = newDb(); // Register current_database function db.public.registerFunction({ name: 'current_database', args: [], returns: DataType.text, implementation: (x) => `hello world ${x}`, }); // Get PG in memory DB connection const connection = (await db.adapters.createTypeormConnection({ type: 'postgres', entities: [Photo], synchronize: true, })) as TypeOrmConnectionFactory; const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }) .overrideProvider('DATABASE_CONNECTION') .useValue(connection) .compile(); app = moduleFixture.createNestApplication(); await app.init(); repository = app.get>('PHOTO_REPOSITORY'); }); afterEach(async () => { await repository.query('DELETE from photo;'); }); it('/ (GET) records', async () => { await repository.save({ name: '123', description: 'test', filename: 'test', views: 10, data: { key: 'value', }, isPublished: true, }); return request(app.getHttpServer()) .get('/photo') .expect(200) .expect((response: Response) => { expect(response.body).toHaveLength(1); expect(response.body).toEqual([ { id: 1, name: '123', description: 'test', filename: 'test', views: 10, data: { key: 'value' }, isPublished: true, }, ]); }); }); });
We start by registering the missing function in the in-memory DB. This will not give us the error when connecting to the in-memory DB. Then we create a TypeORM connection with the in-memory DB. Finally when we create the TestingModule, here we override the DB provider and this is the key thing that will make connections to in-memory DB instead of the actual one.
You can find the complete source code here.
0 notes
Text
Who is a Tech lead?

Photo by Javier Allegue Barros on Unsplash
Generally, every company will have roles for understanding seniority in the team, these roles can start from Junior Developer to all the way till Principal/Senior Developer. The term might vary from company to company but the idea is the same. The team will be composed of a set of developers with different expertise & experience. And it’s very important to have a SPOC(Single point of contact) for the engineering team to function. These anchor roles are generally called Tech Leads.
Now it's very important to understand this role before you start judging me 😁. IMHO, a tech lead is a developer who has a wider context of the product from the engineering side, who understands different components/layers used to build a product, can help the team to take tech decisions, and works closely with the product team. Tech Lead is not a person who manages people, that role used to be called as Team Lead/Peoples manager, but in today's agile team, you don’t need one.
So in short,
TechLead !== PeopleManager
Let's try to understand the difference between a developer & a tech lead by their daily schedule.
A developers standard day:
Start the day by checking emails
Attend standup & update the team about the progress
Work on the task assigned
A tech leads standard day:
Start the day by checking emails
Attend standup & update the team about the progress
Work on the task assigned
Attend meetings with the product team
Unblock the team by resolving tech issues, plan tech debts, tech huddles, etc.
Above, the schedule looks almost the same, it's just that the Tech lead is a part of some extra meetings. These meetings will help the Tech lead to understand the product roadmap based on which he/she can start planning any upcoming tech challenges/changes. The Tech lead is also responsible to communicate this back to the team so that all team members are aligned with the upcoming changes.
Apart from attending the meetings, a tech lead also needs to have a good hand-ons experience in the technology. Tech lead also takes the ownership to maintain a healthy team, have good connections with other teams/stakeholders/clients, help the team to deliver a quality product, build trust within the team, and most importantly have a good quality & maintainable codebase.
One fact which we all are aware of, that each and every employee should be replaceable. A Tech lead is not an exception here, so it's also a Tech lead's responsibility to identify a mini-me(someone you think can replace you) within the team and start grooming & upskilling that person. This helps the team to transition smoothly from one Tech lead to another and most importantly this will have a very minimal impact in terms of the team's productivity.
It's also important to understand that it's not a mandate thing to become a Tech lead, every dev will have some unique skill, and it's Ok to continue in the same role. I have personally known some devs who are really good in tech, even better than me, but they are not Tech leads. Becoming a Tech lead should come by choice and not by some organization's rule/pressure.
If you are a dev and trying to upskill yourself to become a Tech lead then the above writing should help you. Also, I would suggest you, talk to your current Tech lead, take some feedback and try to improve in those areas.
My last suggestion to a Tech lead or a dev who is in the transition to become one:
Don't hesitate to ask questions
Maintain transparency & communicate well within the team
Never compromise in the quality just because of the release deadline
Create an environment in the team to failsafe
Hope this helps!!!
1 note
·
View note
Text
One piece 23rd anniversary

Photo by Jie on Unsplash
One piece is officially 23 years old now and I thought of creating a small CSS card of Luffy.
See the Pen luffy-card by Niraj (@nirajmchauhan) on CodePen.
0 notes
Text
CSS: What's the difference between px, em & rem?

Photo by William Warby on Unsplash
Most of us grew up using px CSS unit. This code should be familiar to you width: 100px;. But in the past few years, I saw other units getting added to the CSS specs. So let's understand each of them.
Pixel(px)
So the word pixel doesn't mean a single pixel of your screen. This was shocking for me as well but it's true since 1996. Pixels are relative to the resolution of the canvas. By default, CSS defines the reference pixel which is usually a pixel on a 96 DPI display. Now we know that there are displays with different DPI like retina displays, in that case, the user agent rescales the pixel to match that of the display. So for retina displays, 1 CSS pixel is actually 2 Retina display pixels.
So with newer displays coming up, new CSS units had to be introduced.
em
Unlike pixels that are relative to displays, em's are relative to the parent elements font-size. So for eg: parent elements font-size is 16px then the child elements 1em value is 16px. Now, this sounds interesting but trust me, don't use the em unit. It becomes really messy if you start using it in a nested HTML structure. The following example demonstrates it very nicely.
See the Pen em font-size by Niraj (@nirajmchauhan) on CodePen.
rem
This is a better version of em, it works just like em, but instead of being parent element relative, rem's are always relative to the font-size of the root element i.e. HTML tag. So by default the HTML font-size is 16px so 1rem = 16px unless the HTML documents font-size is changed. Example:
See the Pen rem font-size by Niraj (@nirajmchauhan) on CodePen.
Conclusion:
First thing, try not to use em. Go with rem or px units. Now the place where rem becomes really useful is when it comes to responsiveness. So for eg on a bigger display if you change the default font-size of the browser, then the px unit will not scale, but if its rem then it would scale.
1 note
·
View note
Text
Difference between Map & Flatmap | RXJava
RXJava can be very intimidating at first go. Reactive Extensions - RX is all about data streams & handling them and three important pillars for it are Observables, Operators & Schedulers.
Initially, while using operators I was very confused between map and flatMap. And this confusion still exists today with all beginners. So let me help you to clear this confusion.
Map
Map operator transforms the items from data stream by applying a function to each item. Lets look at below code which will output length of words.
Example:
String line = "Lorem Ipsum is simply dummy text"; List words = Arrays.asList(line.split(" ")); Observable.from(words) .map(w -> { return String.format("%s => %s", w, w.length()); }).subscribe(System.out::println);
Here we are passing list of words to map. For each word it formats it and return back to the stream.
Marble Diagram:
FlatMap
FlatMap operator transforms the items from data stream into observables and then it flattens all observables into single observable. Lets look at below code which will output letters from words.
String line = "Lorem Ipsum is simply dummy text"; List words = Arrays.asList(line.split(" ")); Observable.from(words) .flatMap(w -> { return Observable.from(w.split("")); }).subscribe(System.out::println);
Confused??
In map when word Lorem was passed, it transformed it into Lorem => 5. But when we passed same word to flatMap, it transformed it into ["L","o","r","e","m"]. So flatMap can emit one or more than one values whereas map emits only one. Because its an array, flatMap flattens all values in a single stream.
Marble Diagram:
0 notes
Video
youtube
There is a huge buzz in the market for "Reactive Programming", but the very first question comes in our mid is what is reactive programming? Why we need reactive programming? What is RX?
0 notes
Text
How to write clean code?

A project is much easier to develop and maintain if the codebase is clean, which every developer should strive for. Writing clean code is not rocket science, in fact, it's quite simple.
1. First & foremost you need Focus
When a developer starts to code, the focus is an absolute must. You can't be doing other things in parallel and achieve clean codebase. While coding, a developer is required to do a lot of things apart from just writing the code e.g. ALT+TAB to switch between terminal, browser and code editor, change tabs within the editor, refer or understand the dependent code etc.. this could be time-consuming and if your mind is not focused then you will end up in writing bad code.
2. KISS
I have usually noticed people over-complicating their code by thinking of extreme future scenarios, one should simply avoid these. For instance, the following code for Summing two numbers.
class Calculator{ private int a; private int b; private String operator; Calculator(int a, int b, String operator) { this.a = a; this.b = b; this.operator = operator; } int getCalculatedValue(){ switch (operator){ case "+": return a + b; default : return 0; } } }
While there is nothing wrong with the code, It's been extended to function as a calculator in future, which may or may not be required. Summing up two numbers can simply be a one-liner code.
The example in itself is not very realistic, but the point here is to not make things overcomplicated, Keep it Simple Silly (KISS) !! It's good to design but focus on a simplistic approach to the problem at hand. Follow KISS principle.
3. Naming Conventions
The name of a variable, method or class is very important in your code, it makes a lot of difference while interpreting the logic. For example: Creating a variable for elapsed time in days:
DateTime dT;
Now if someone reads this, it looks like some DateTime type variable. But now if I modify it to something like this:
DateTime elapsedTimeInDays; // or DateTime daysSinceCreation;
This makes a significant difference. So think of a good meaningful name and then write the code.
4. Feedback
Get your code reviewed by someone from time to time. Even if you follow above practices, it's impossible to say that the written code will be clean. By getting your code reviewed, you get feedbacks and feedbacks are always good for improvements.
5. Pairing
Code review helps but it can be time-consuming. Let's say a developer takes an hour to write some code, he then gets it reviewed by some other developer and start making changes based on feedback, which takes another 30-40 mins. This is time-consuming. What if from start the reviewer was sitting next to the developer, then the moment developer started writing the first line of code, it gets reviewed simultaneously. So in an hours time, the developer has a clean reviewed code. Pairing is a nice practice to follow. The way pairing works, developer A & B pairs together for an hour. First 30 mins A codes and B reviews, and in next 30 mins B codes and A reviews. The end result is good quality & clean code.
6. TDD
In general regressions for refactoring happens a lot of time. But after refactoring how can one make sure that the functionality is still the same? Test driven development approach ensures that refactoring your code will never negatively impact the desired functionality. The way TDD works is, you write test-cases first, run it, see it fail, then you write code and make the test-cases pass, repeat this and keep refactoring whenever you feel like. Now while refactoring you don’t need to worry about missing any functionalities because your test cases will help you. In a way, it's kind of an alert mechanism which notifies you when your refactoring has gone wrong.
7. Boy Scout Rule
Follow Boy Scout Rule, which means always leave the code cleaner than you found it. This forces the developer to continuously keep improving the project's code quality by refactoring it and making it simpler.
8. DRY
Don’t Repeat Yourself, basically always write new code, don’t repeat the same code again and again. Try to extract generic behavior in some method and reuse that in other methods.
Conclusion
According to me, a codebase is clean only when it's readable and maintainable. If you follow from point 1 to 5, you will achieve readability, and if you follow from point 6 to 8, you will achieve maintainability. Now combine all of them you achieve clean codebase. Let me know what you think of clean coding practices and if I have missed anything, in the comment section below.
5 notes
·
View notes
Text
React bundling for production using Webpack 2
A quick way to reduce your bundle.js file size is using minification. But that's not it, your react bundle contains the code which you have included, this also means that unused code & big size packages are used.
So first step is to analyze your bundle.js file. Webpack has a nice feature to export your bundle stats to a JSON file, and then just upload this file which will give you a nice graphical report.
In your project folder, run this command:,webpack --json > stats.json upload this JSON file to this website
The output will be something like this:
Now identify your unused, duplicate or replaceable dependencies and then let's minify it using Webpack2.
Webpack2 is more powerful and it has huge support for ES6, a complete feature list is available here
The configuration I am using for my webpack:
const path = require('path'); const output = path.resolve(__dirname, 'public'); const src = path.resolve(__dirname, 'app'); const clientConfig = { target: 'web', entry: `${src}/index.js`, output: { path: output, filename: 'js/bundle.js', }, resolve: { extensions: ['.js', '.jsx'] }, module: { rules: [ { test: /\.html$/, exclude: /node_modules/, use: 'html-loader', }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ 'babel-loader' ], } ] } }; module.exports = [clientConfig];
Now by running, webpack -p will generate a minified version of bundle.js.
Let's take this a step ahead by gzipping our bundled file. To enable gzipping we will require: compression-webpack-plugin
plugins: [ new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.js$|\.html$|\.css$/, threshold: 10240, minRatio: 0.8 }) ]
You can enable gzipping only for production by reading
-p
argument.
const path = require('path'); const CompressionPlugin = require('compression-webpack-plugin'); const PROD = process.argv.indexOf('-p') !== -1; const output = path.resolve(__dirname, 'public'); const src = path.resolve(__dirname, 'app'); const clientConfig = { target: 'web', entry: `${src}/index.js`, output: { path: output, filename: 'js/bundle.js', }, resolve: { extensions: ['.js', '.jsx'] }, module: { rules: [ { test: /\.html$/, exclude: /node_modules/, use: 'html-loader', }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ 'babel-loader' ], } ] }, plugins: PROD ? [ new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.js$|\.html$|\.css$/, threshold: 10240, minRatio: 0.8 }) ] : [] }; module.exports = [clientConfig];
0 notes
Text
Java Vert.x MongoDB Client with Guice
Vert.x is an event-driven non-blocking library. It's not a framework, so you get power to write code in your way. Vert.x is similar to NodeJS. It helps you to achieve concurrency with minimal hardware.
A few months back when I started with vert.x, I was impressed with the documentation and examples what they have on their website. Because, Vert.x is not a framework sometimes it becomes difficult for a developer to construct the entire architecture. When I started, I was facing trouble in getting the DB client available in different services. I didn't want to initialize it again and again, so I decided to use DI. I started with Google's Guice.
Here is my implementation.
AppInjector.java (Guice Injection class)
public class AppInjector extends AbstractModule { private Vertx vertx; public AppInjector(Vertx vertx) { this.vertx = vertx; } @Override protected void configure() { JsonObject mongoConfig = Config.getObject("mongo_config"); MongoClient mongo = MongoClient.createShared(vertx, mongoConfig); bind(MongoClient.class).annotatedWith(Names.named("MongoClient")).toInstance(mongo); } }
Above I created mongo client and bounded it with Guice. Now where ever I want to use this mongo client, I simply use named annotations and Guice injects the client.
So now in my service I simply do the injection:
MongoService.java
public class MongoService { @Inject @Named("MongoClient") private MongoClient client; }
That's it, isn't that simple? Vert.X is really powerful. You can scale Vert.x application by creating multiple verticles. Polyglot, Vert.x can be used in Java, Javascript, Groovy, Ruby & Ceylon.
You can find the entire implementation on my Github repo.
0 notes
Photo

#comicon #bengaluru (at KTPO Trade Centre)
0 notes
Photo

#onepiece #manga #comicon #bengaluru
1 note
·
View note
Photo

Mere ghar aayi ek nanhi pari #sony #playstation4 (at Evershine city VASAI)
0 notes
Text
Never buy anything from Snapdeal
Today I am going to share my journey on buying a product from Snapdeal.
It was a typical weekday and I was getting ready for my daily office schedule, when I realized that I needed to get a new belt. So I went online and started looking for one. After browsing for sometime, I finally ended up finding the perfect one for me on Snapdeal.com.
Day 1 - “6 Sept 2016 😀” I placed my order and made an online payment. Easy right?
I knew that it would take 4-6 days to get the item delivered and there began my test of patience because clearly there was something else in store for me.
Day 5 - 10 Sept 2016 🙂 I received an SMS from Snapdeal saying that a delivery attempt was made and it failed because the consignee (me) was not available at the given address. This was ?????
My surprise knew no bounds, since that was a weekend and I was home all day, and nobody in fact had even knocked on the door. There had been no communication from the logistics team and no intimation that my package was out for delivery.
Regardless, as a trusting customer, even after the failed attempt, I waited. So what if it could not be delivered today, tomorrow is a new day. How very wrong I was.
Day 9 - 14 Sept 2016 😐 So after exhausting 6 (+3) days of waiting for my belt to arrive, I got a little concerned and ended up trying to contact Snapdeal. I put a one liner tweet querying about my order status.
“Why oh why did you not cancel your order”, you must be thinking. I was thinking the same, but the heart wants what the heart wants.
Over the tweet I gave them my order details, within few minutes I got a callback and they committed that this will get resolved in next 48 hours.
I kept hoping beyond hope that the order will get delivered and a company as big as Snapdeal will not make such horrendous blunders. My faith was about to be taken on a whole new ride.
Day 11 - 17 Sept 2016 😑 Nothing yet. 48 more hours exhausted. No belt, no calls, no concern, nothing. I had to tweet again. Once again, diligent as ever they called me back, this time apologizing, another 48 hours time.
Day 13 - 19 Sept 2016 😒 My patience was waning fast. Nothing still. Agitated and patience running thin, I tweeted again, but this time the call was interesting. I was talking to a support guy who was putting all his efforts into convincing me that I keep waiting. He was even bold enough to tell me, and I quote, “All these things keep happening in e-commerce business.”
He went on to tell me that his experience on Amazon had been the same and that, I quote again, “You should understand and keep calm, its nothing to panic, this had happened with me when I order on Amazon as well.”
Firstly, I do not know whether he should have told me this, especially considering that he is a Snapdeal employee. The sheer irony of the situation was that this guy also does not order from Snapdeal. +1 to you Amazon.
Moreover, this guy was fantastically rude and lacked basic etiquette while speaking with a person over phone, let alone a customer. I was given another 48 hours to wait.
Day 17 - 23 Sept 2016 😤 By this time, I had lost all hope of getting anything, and was searching for other options on Amazon. I got a call from Snapdeal (without any tweet, strange 🤔) and this time a very soft spoken feminine voice asked me politely to cancel the order since they had lost track of it. The logistics team, which by the way had tried to deliver the very same order, has misplaced my package. I do not know whether it was relief or exasperation that I felt, but finally things had reached a closure. My package was lost, I was pissed and had no belt.
The cherry on the cake was when she asked me to reorder the same thing again and assured me that they will try there best to get it deliver in couple of days. Hah! the nerve on her. I politely requested a refund and asked her to delete my Snapdeal account.
Some people might have had good experience with Snapdeal, but still I will suggest to everyone on not buying anything from Snapdeal. Go with Flipkart or Amazon, they are the best.
0 notes
Text
Javascript Naming Conventions

Many times we face situations in projects for naming our files, variables or classes. Here is the convention I am sharing which I follow in my projects of Javascript.
Filenames: This should be kebab-case, words to be small case and - separated
Example:
routes.js product-service.js
Variables: Variables in Javascript should camel-case.
Example:
let firstName = 'Niraj'; var age = 26;
Functions: Again this will be camel-case.
var getName = () => {}; function setName(){ }
Classes: Classes should be pascal-case.
class User{} class UserController{}
Private functions/variables: Though we don't have the private keyword in ES6, I achieve it by assuming it to be private by just prepending _ to the functions. This helps me to design my classes in a way that makes a convention in my team to not call this function from the outer class.
class UserController{ constructor(){ this._secretKey = ''; } _parse(){} get(){ this._parse(); } }
Now in the above example `_parse()` is meant to be private.
In react I have seen many projects where developers rename the filename of components to be pascal-case which is not wrong but that's the way developers bring change to the programming world.
0 notes
Text
Check if visitor is logged in social website | Javascript
Few years back one of my client had a requirement to make a advertising popup on his website, but the content would be dynamic based on visitors facebook, twitter and google login state. That time I could'nt do it, but thanks to Robin Linus it is possible now.
The way its done is really simple, call a URL of favicon, if the visitor is loggedin then favicon will be returned.
var img = document.createElement('img'); img.src = "https://www.facebook.com/login.php?next=https%3A%2F%2Fwww.facebook.com%2Ffavicon.ico%3F_rdr%3Dp"; img.onload = function() { console.log('Visitor is logged in to facebook '); document.write('Visitor is logged in to facebook '); }; img.onerror = function() { console.error('Visitor is not logged in to facebook '); document.write('Visitor is not logged in to facebook '); };
Demo:
See the Pen Check if visitor is logged in social website by Niraj (@nirajmchauhan) on CodePen.
More links:
Square => https://squareup.com/login?return_to=%2Ffavicon.ico Instagram => https://www.instagram.com/accounts/login/?next=%2Ffavicon.ico Twitter => https://twitter.com/login?redirect_after_login=%2Ffavicon.ico Facebook => https://www.facebook.com/login.php?next=https%3A%2F%2Fwww.facebook.com%2Ffavicon.ico%3F_rdr%3Dp Google => https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.google.com%2Ffavicon.ico&uilel=3&hl=de&service=youtube Google Plus => https://plus.google.com/up/accounts/upgrade/?continue=https://plus.google.com/favicon.ico Skype => https://login.skype.com/login?message=signin_continue&redirect_uri=https%3A%2F%2Fsecure.skype.com%2Ffavicon.ico Flickr => https://www.flickr.com/signin/yahoo/?redir=https%3A%2F%2Fwww.flickr.com/favicon.ico Spotify => https://www.spotify.com/de/login/?forward_url=https%3A%2F%2Fwww.spotify.com%2Ffavicon.ico Reddit => https://www.reddit.com/login?dest=https%3A%2F%2Fwww.reddit.com%2Ffavicon.ico Tumblr => https://www.tumblr.com/login?redirect_to=%2Ffavicon.ico Expedia => https://www.expedia.de/user/login?ckoflag=0&selc=0&uurl=qscr%3Dreds%26rurl%3D%252Ffavicon.ico Dropbox => https://www.dropbox.com/login?cont=https%3A%2F%2Fwww.dropbox.com%2Fstatic%2Fimages%2Ficons%2Ficon_spacer-vflN3BYt2.gif Amazon => https://www.amazon.com/ap/signin/178-4417027-1316064?_encoding=UTF8&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=10000000&openid.return_to=https%3A%2F%2Fwww.amazon.com%2Ffavicon.ico Pinterest => https://www.pinterest.com/login/?next=https%3A%2F%2Fwww.pinterest.com%2Ffavicon.ico Netflix => https://www.netflix.com/Login?nextpage=%2Ffavicon.ico Foursquare => https://de.foursquare.com/login?continue=%2Ffavicon.ico Battle.net => https://eu.battle.net/login/de/index?ref=http://eu.battle.net/favicon.ico Steam => https://store.steampowered.com/login/?redir=favicon.ico Academia.edu => https://www.academia.edu/login?cp=/favicon.ico&cs=www Stack Overflow => https://stackoverflow.com/users/login?ssrc=head&returnurl=http%3a%2f%2fstackoverflow.com%2ffavicon.ico Blogger => https://accounts.google.com/ServiceLogin?service=blogger&hl=de&passive=1209600&continue=https://www.blogger.com/favicon.ico
0 notes
Text
[] == [] is false, why? | JavaScript
I love javascript and its mystery, if you had to compare a set of two identical arrays the first thing in your mind would come is to compare using == operator. But in javascript the result will be different.
Just try it in your console a normal comparison of two identical arrays.
var x = [1,2,3]; var y = [1,2,3]; console.log(x == y); console.log([] == []); console.log([null] == [null]);
Above example will return false, now if you try this in ruby or any different server side language it will return true.
Now why is this happening, the way JavaScript works is different. JavaScript has two types of values Primitives and Objects. All Numbers, Strings, Boolean and Undefineds are primitives. Remaining are objects, array is a part of it. When you create an array, what you get is the instance of an Array class, so now when you compare the two arrays, instances are compared and not their values.
Arrays comparison might turn out to be slow if the array is deep, this might be the reason javascript doesn't supports.
So to compare two identical arrays you can use lodash or a simple way would be to convert arrays into string and then check.
var x = [1,2,3]; var y = [1,2,3]; console.log(JSON.stringify(x) == JSON.stringify(y));
4 notes
·
View notes
Text
Useful Javascript Array Functions
Why to use loops when we have the power of array functions.
var attacks = [ {name:'Rasengan', power:80}, {name:'Chidori', power:75}, {name:'Amatarasu', power:95}, {name:'Rasenshuriken', power:100} ]; var big_attacks = attacks.filter(function(attack){ return attack.power > 80; }); console.log(big_attacks); // [Object { name="Amatarasu", power=95}, Object { name="Rasenshuriken", power=100}] var attack_names = attacks.map(function(attack){ return attack.name; }); console.log(attack_names); //["Rasengan", "Chidori", "Amatarasu", "Rasenshuriken"] var rasenshuriken = attacks.find(function(attack){ return attack.name == 'Rasenshuriken'; }); console.log(rasenshuriken); // Object { name="Rasenshuriken", power=100} var total_powers = attacks.reduce(function(total,attack){ return total + attack.power; },0); console.log(total_powers); //350
1 note
·
View note