Theme images by Storman. Powered by Blogger.

Featured Posts

Monday, 11 February 2019

Find the min/max element of an Array in JavaScript

- No comments

I have just figured out some great way to find the min and max value from the array and I just wanted to share with all of you.

See the code below, use it or add console log to understand it in depth.




var arr = [12, 89, 67, 55];

// Method 1
function arrayMax(arr) {
return arr.reduce(function(p, v) {
return Math.max(p, v); // Math.min for min
});
}
arrayMax(arr);

// Method 2
function arrayMax(arr) {
return arr.reduce(function(p, v) {
return p > v ? p : v; // p < v for min
});
}
arrayMax(arr);

// Method 3
Math.max(...arr); // Math.min for min

// Method 4
function findMinMax(arr) {
let min = arr[0],
max = arr[0];

for (let i = 1, len = arr.length; i < len; i++) {
let v = arr[i];
min = v < min ? v : min;
max = v > max ? v : max;
}
return [min, max];
}

findMinMax(arr);

Thursday, 7 February 2019

Bootstrap Custom Theme in react Application

- 1 comment




"Bootstrap" as every developer knows a very popular framework for the CSS and, comes with its build in components, styles and utilities.

Recently I was using bootstrap for one of my react project. but bootstrap comes with its own default styles and I was looking for some mechanism so I can use my own styles or putting into the simple way I can customize the bootstrap styles.

During this process, I figured out the solution, In this post, In a few easy steps I am going to share how you can customize bootstrap.

STEP 1:

Include bootstrap in your application
           

  npm install --save bootstrap



STEP 2:

To customize Bootstrap, create a file called src/custom.scss(decide the place where you want to keep your custom.scss file) and alter the value of the variable you want to customize.


// Override default variables before the import
$primary: #000;

// Import Bootstrap and its default variables
@import '~bootstrap/scss/bootstrap.scss';


You can see all the available variables inside bootstrap\scss\_variables.scss and you can select the one which you want to modify.


STEP 3 :

Import the newly created .scss file instead of the default Bootstrap .css in the beginning of your src/index.js file, for example:


import './customCss/custom.scss';



And its done. Run your react project and see the magic.


Thanks for reading; if you find it useful or something you want to add do comment.

Happy Learning :-)





Wednesday, 12 December 2018

Unit Testing in gatsby using Jest

- No comments

Jest is basically a unit testing framework which is frequently used in React but
in this post I want to share how you can use jest in gatsby for unit testing. gatsby is the static site generator using this you can create websites in react.

1. Installing dependencies

First you need to install Jest and some more required packages. You need to install Babel 7 as it’s required by Jest.


npm install --save-dev jest babel-jest react-test-renderer identity-obj-proxy babel-core@^7.0.0-bridge.0 @babel/core babel-preset-gatsby




2. Creating a configuration file for Jest
Add this in root folder

jest.config.js


module.exports = {
"transform": {
"^.+\\.jsx?$": "<rootDir>/jest-preprocess.js"
},
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss)$": "identity-obj-proxy",
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js"
},
"testPathIgnorePatterns": ["node_modules", ".cache"],
"transformIgnorePatterns": ["node_modules/(?!(gatsby)/)"],
"globals": {
"__PATH_PREFIX__": ""
},
"testURL": "http://localhost",
"setupFiles": ["<rootDir>/loadershim.js"]
}



jest-preprocess.js


const babelOptions = {
presets: ["babel-preset-gatsby"],
}
module.exports = require("babel-jest").createTransformer(babelOptions)


__mocks__/fileMock.js

module.exports = "test-file-stub"


loadershim.js

global.___loader = {
enqueue: jest.fn(),
}

3. Useful mocks to complete your testing environment


Mocking Gatsby

Finally it’s a good idea to mock the gatsby module itself. This may not be needed at first, but will make things a lot easier if you want to test components that use Link or GraphQL.

This mocks the graphql() function, Link component, and StaticQuery component.

__mocks__/gatsby.js


const React = require("react")
const gatsby = jest.requireActual("gatsby")

module.exports = {
...gatsby,
graphql: jest.fn(),
Link: jest.fn().mockImplementation(({ to, ...rest }) =>
React.createElement("a", {
...rest,
href: to,
})
),
StaticQuery: jest.fn(),
}

4.Writing tests

Put test inside test folder with the extension .spec.js or .test.js. 

a) Snapshot test :-

Testing simple page

-- src/pages/samplePage.js

import React from 'react'

const SamplePage = () => (
<div>
<h1>renders correctly</h1>
</div>
)

export default SamplePage


-- test/dummyTest.test.js


import React from "react"
import renderer from "react-test-renderer"
import Bio from "./Bio"

describe("Bio", () => {
it("renders correctly", () => {
const tree = renderer.create(<Bio />).toJSON()
expect(tree).toMatchSnapshot()
})
})




Testing page  wrapped inside component / shallow rendering test 

-- src/pages/page-2.js


import React from 'react'
import { Link } from 'gatsby'

import Layout from '../components/layout'
import SEO from '../components/seo'

const SecondPage = () => (
<Layout>
<SEO title="Page two" />
<h1>Hi from the second page</h1>
<p>Welcome to page 2</p>
<Link to="/">Go back to the homepage</Link>
</Layout>
)

export default SecondPage


-- test/dummyTest.test.js

import React from "react"
import ShallowRenderer from 'react-test-renderer/shallow'
import SecondPage from "../src/pages/page-2"

describe("Test second page render", () => {
it("renders correctly", () => {
const renderer = new ShallowRenderer()
const tree = renderer.render(<SecondPage />)
expect(tree).toMatchSnapshot()
})
})



Running tests


Add jest for the test in package.json file

"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"start": "npm run develop",
"format": "prettier --write \"src/**/*.js\"",
"test": "jest"
},



If you want you could also add a script that runs jest --watchAll to watch files and run tests when they are changed.


you can now run tests by typing npm run test


If you make changes that mean you need to update the snapshot, you can do this by running npm run test -- -u.

jest --coverage config can be used to see the whole coverage report.



Find more details here :  https://www.gatsbyjs.org/docs/unit-testing/


Happy Learning :-)






























Sunday, 25 June 2017

Self Development : Cockroach Theory- A beautiful speech by Sundar Pichai.

- No comments
In this post I am going to share A beautiful speech given by Sundar Pichai for self development. I want you to read this story and watch the video. This will help you to change your perspective to think about situations and events happening in life.




At a restaurant, a cockroach suddenly flew from somewhere and sat on a lady. She started screaming out of fear. With a panic stricken face and trembling voice, she started jumping, with both her hands desperately trying to get rid of the cockroach. 

Her reaction was contagious, as everyone in her group also got panicky. The lady finally managed to push the cockroach away but …it landed on another lady in the group. Now, it was the turn of the other lady in the group to continue the drama. 

The waiter rushed forward to their rescue. In the relay of throwing, the cockroach next fell upon the waiter.
The waiter stood firm, composed himself and observed the behavior of the cockroach on his shirt.
When he was confident enough, he grabbed it with his fingers and threw it out of the restaurant.

Sipping my coffee and watching the amusement, the antenna of my mind picked up a few thoughts and started wondering, was the cockroach responsible for their histrionic behavior?
If so, then why was the waiter not disturbed? He handled it near to perfection, without any chaos.
It is not the cockroach, but the inability of the ladies to handle the disturbance caused by the cockroach that disturbed the ladies. 

I realized that, it is not the shouting of my father or my boss or my wife that disturbs me, but it’s my inability to handle the disturbances caused by their shouting that disturbs me. It’s not the traffic jams on the road that disturbs me, but my inability to handle the disturbance caused by the traffic jam that disturbs me. 

More than the problem, it’s my reaction to the problem that creates chaos in my life.

Lessons learnt from the story: “Do not react in life. Always respond.“

The women reacted, whereas the waiter responded. 

Reactions are always instinctive whereas responses are always well thought of, just and right to save a situation from going out of hands, to avoid cracks in relationship, to avoid taking decisions in anger, anxiety, stress or hurry.

Happy Reading  :-)

Most inspirational speech by steve jobs

- No comments
In this post I am going to share Most inspirational speech given by steve jobs.

Steve Jobs was an American entrepreneur, businessman, inventor, and industrial designer. He was the co-founder, chairman, and chief executive officer (CEO) of Apple Inc.CEO and majority shareholder of Pixar, a member of The Walt Disney  Company's board of directors following its acquisition of Pixar, and founder, chairman, and CEO of NeXT. Jobs and Apple co-founder Steve Wozniak are widely recognized as pioneers of the microcomputer revolution of the 1970s and 1980s.(Source : wikipedia)



Read complete speech here : http://news.stanford.edu/2005/06/14/jobs-061505/




These quotes will help you to keep moving.

- No comments



Your whole life can never depend on one single event. Life always have more to offer than you think it would.

Life is like riding a bicycle. To keep your balance you must keep moving.

You can not stop a bird from landing on your head, but you can keep it away from building a nest.

Don't Take Anything Personally. Nothing others do is because of you. What others say and do is a projection of their own reality, their own dream. When you are immune to the opinions and actions of others, you won't be the victim of needless suffering. ~ Don Miguel Ruiz

You can spend minutes, hours, days, weeks, or even months over-analyzing a situation; trying to put the pieces together, justifying what could’ve, would’ve happened… or you can just leave the pieces on the floor and move on.

You will be thrown down again and again, will fail countless times, and you will be beaten to the point where every doubt and fear will creep up to fight you. But you have to just keep going.

Don't be afraid to shake the apple tree a bit to see what fruits remain after.


These quotes will help you to create your better version.

- No comments



Don't be worst company of yourself 

Whenever you find yourself wasting time, remember. There is someone out there who is equipping him/her at this very moment. The day you compete with him, you’ll lose.

Your problem is you have spent your whole life thinking there are rules. There aren’t. We used to be gorillas. All we had is what we could take and defend.

If you spend too much time thinking about a thing, you’ll never get it done. ~ Bruce Lee

Life can be hard. But remember, while the difficult moments may decrease happiness, they’re essential for building meaning. And that’s what matters in the long run."

You don't get frustrated because of events. You get frustrated because of your beliefs.

Act the way you’d like to be and soon you’ll be the way you’d like to act.

Anger is not a real emotion. It is fear clothed. Figure out what you are afraid of before you get angry.

God gives his hardest battles to his toughest soldiers." You are being redirected and made strong for a purpose in your life. Its not suffering, its training. Training for you to make it big.

Eat a frog everyday(do your worst task first thing in the morning). It would be actually difficult in the beginning. But as you do it, you will start feeling better and procrastinate less in life.  

And in the end, it’s not the years in your life that count. It’s the life in your years.