Tag: javascript

Comparison of external NodeJS http libraries by their size

I have used “cost of modules” to understand more about the package sizes and also added the GitHub stars to indicate the popularity of the subject (which can change of course),

  • Request [4.67 MB] * 16,946
  • SuperAgent [1.13 MB] * 11,380
  • Axios [0.36 MB] * 27,214
  • Got [0.16 MB] * 1,949
  • R2 [?] * 3,837 so far Got [0.16 MB]

cost-of-modules-request-libs

React notes for myself (and for anyone who is interested)

Use bind

Do not do this {() => foo()} while you can do {this.foo.bind(this, bar)} even better you can create a helper to pick up all handler methods and fix the context.

1.) Where is my dispatch

You can always pass down the dispatch method as a prop!
export function mapDispatchToProps(dispatch) {
  return {
 dispatch,
    onLoad: () => {
      dispatch(foo());
    }
  }
}

2.) Nesting

You can do nested elements like:
<Parent>
  {foo.map(item =>
    <Child />
  )}
</Parent>
and within the Parent
return (
<div className=”parent”>{children}</div>
)

 3.) Reducer and Reselect

In the reducer
const reducers = combineReducers({
  fooOne,
  fooTwo,
});
… in the selector (Reselect)
const makeSelectFoo = () => createSelector(
  selectFoo,
  (stateFoo) => stateFoo[‘fooOne’][‘bar’]
);

4.) Modifying a child (via cloneElement)

renderChildren() {
  return React.Children.map(this.props.children, child => {
    return React.cloneElement(child, {
      name: this.props.name
    })
  })
}

5.) Destructuring in pure component

const myComponent = ({propertyOne, propertyTwo}) => { //this is instead of (props) then props.propertyOne }

6.) Rest and Spread

const myComponent = ({onClick, ...otherProperties}) => {
//this is instead of (props) then props.propertyOne
<Foo {...otherProperties}>
 <Button onClick={onClick}>Click me</Button>
</Foo>
}
 

Android back button and cache

I was working on a weird functionality a counter for social media share. Basically after you have made the click it increases the counter by 1. The problem is that the sharing popup or window opens a new tab on Android. When you return to the original parent window it loses the dynamically update DOM and returns to the cached one (bfcache). I have tried to do some adjustments on focus return also attempted “visibilitychange” and unfortunately none of these worked out:

$(window).on('focus', () => {})
$(window).on('visibilitychange', () => {})

The only way I could solve this:

1.) On the click event I have increased the counter and also stored the new total in the hash:

window.location.hash = 'counter?='+newtotal;
then opening the new window (e.g. twitter share form)

2.) On load (return to the parent window) I have used the hash to retrieve the total and updated it back to the DOM.


	$(window).on('load', () => {
		if(window.location.hash) {
			var count = window.location.hash.split('=');
			if(count && count.length > 1) {
				change_total(count[1]);
			}
		}
	});

It is far from perfect but it works. You can read more on this topic here and here.

UPDATE ONE:

Android likes to cache even ajax queries regardless of that you returned to the windows and apparently everything has been re – rendered (re drawn from cache).
Something like this can be helpful as a cache buster:


$.get(uri + '?_=' + new Date().getTime())

Date object’s behaviour when using “yyyy-mm-dd” but omitting the “dd”

If you create Date object like this: new Date(‘1980-01-01’); you will get a valid date although if you try to give a string to the constructor like new Date(‘1980-01’) then it can be valid like the previous Date object.

How could this be?

The omitted day will be set as default ’01’ and your object will be Date(‘1980-01-01’); besides you only set ‘1980-01′. If you wrap this into a funcion that checks let’s say all your input fields’ values (let’s assume 1 input for day another one for month and the last one for year) then you can always check if these inputs are empty or not and if the day is an empty string then you can set it as NULL then you won’t get the day added as default ’01’ by the Date object’s constructor.

It will be new Date(‘1980-01-null’); and the result is an invalid Date object as expected.  Always encourage unit tests and you can easily avoid traps like the one above.

The gist can be found here: https://gist.github.com/joshycube/2a35aa15ebdd34f0f45368750acf7d69

 

Line of business and new technology

If you are a developer who deals with code then you are either amongst those lucky people working for Google labs or you are very likely to deal with legacy line of business code on a daily basis. Despite the fancy tech talk after your sucessful fizz-buzz bullshit where the guys wanted you to write technical test too top on an in depth conversation around React and some recent Redux stuff which includes immutability and React Router, Context, Relay – they can be a little bit surprised when you are throwing them the question on your second day – why the heck are we using 5 years old JS code with jQuery? The answer is probably they have been told to maintain legacy nightmare for now and also to going away from this code soon. You are trapped. Why??! Consider this from a business point of view. If your company selling clothes online and you convert their already working Backbone code (the whole framework is a huge anti pattern OMG BTW) in to fancy immutable React Redux unicorn – how much money they can save? Probably nothing much or if slightly more than nothing – is nothing to do with your code re write. However you can always improve things, make them faster etc.

What (business) people are paying for?

UX with A/B testing

If you can manage to create user experience – user journey that increases conversion and revenue then you are in a good position to do slight improvements and proving them by numbers. Going step by step and backed by statistics.

Devops optimizations

If you can find patterns in the daily usage of resources or you can optimize the daily workflow then you are saving money to your company and I can not see the point not to do so unless a very political environment that is too slow to move (e.g. from self hosted to AWS).

Code quality and integrity

Unit tests. Easy to sell. Do it. Code reviews, Git worflow or pull request – try it – nothing to lose here.

What business usually does not buy

Complete rewrite

Rewriting ugly code just for the sake of it. Even when technology is emerging – you have to make a very strong point to convince an organization that commited spend money wisely on a complete code refactoring. Unless the code was that much bad and unmaintanable or resources had become recently too expensive and difficult to find (let’s say that is a C++ legacy system) then you probably can not do it. Fancy a complete NodeJS microservice backed React stack? The good news is that you very likely to find a team, bad news is not going to be that much cheaper due to the high demanding and bids of full stack front end engineers.

What start ups usually buy

Are you fancy of a recent Angular or React stuff? – But be careful here

Start ups are mostly the only places on Earth where someone willing to pay you for applying recent technologies. But be careful here. If you are one those early employees you migh have chance to put down your two cents next to a technology although things are moving so fast that you could easily see you code either getting rid of in a short term or being claimed unefficient due to lack of time to reasoning around the correct usage and patterns of too young tools. If you are coming on board little bit later then you can see proud and huge code base of React missing the immutability or complete Redux – one of those things that without React is not that big deal or something else that is not even published yet but tomorrow potentially will change the way how we modern engineers approach things. Just think about your React-Flux code 6 months ago… would you write a completely different stuff today possibly with Redux? What about tomorrow Elm or some RxJS? Right now IMO generators and yield together rocks when it comes to NodeJS control flow but I might change my mind about it tomorrow if something else comes up. Business does prefer stability and predictable stuff. The code should stay in place for a while despite technology changes rapidly. That is one of the reasons why employers should hire the right engineers.

It is sad but most of us (90%) can only reason around new tech in spare time or sometimes even during working day if we are enough lucky to work for a company that knows something about the 20%-80% time usage. That leaves us with some side projects and being strong advocate of code quality/test, agile and business side – customer experience and product/service driven mindset – to make/save money to our companies even through an ugly legacy code.

Dear recruiters (good ones) should understand that and cut away the bullshit. No need for marketing buzz here. Do not put React-Redux and AngularJS, Backbone in to the same advert or do not put anything like that at all. Do not ask people to know everything that is recent. A framework can be picked up in 3-4 weeks but someone who really does a quality job both on coding and consulting side is hard to find. Do not scare them with bullshit. Put some expectations on someone to be a good fit and positive personality who knows about unit testing, code management, common challenges and may be ES6 advantages when destructuring an object/array is important.