makaravind / ALBTY

Get awesome developer news, updates and everything else by native GitHub notifications 📢
MIT License
32 stars 3 forks source link

Daily Mini Treats 🍬 🍭 #1

Open makaravind opened 6 years ago

makaravind commented 6 years ago

Subscribe to this issue and get byte sized treats daily. Hope you get ALBTY 🍬 🍭

makaravind commented 6 years ago

Yipeee! First Post! 💫 💥

1_javascript

2_javascript

makaravind commented 6 years ago

code snippet of immutable version of Array.prototype.push in javascript 3_javascript

makaravind commented 6 years ago
Approximations for GZipped versions of famous UI frameworks and libraries 👀🎯
Name Size
Preact 7.2.0 4kb
React 0.14.5 + React DOM 40K
React 0.14.5 + React DOM + Redux 42K
React 15.3.0 + React DOM 43K
React 16.2.0 + React DOM 31.8K
Angular 2 + Rx 143K
Angular 1.4.5 51K
Ember 2.2.0 111K
Ember 1.13.8 123K
Angular 2 111K
Vue 2.4.2 20.9K
Inferno 1.2.2 20K
Aurelia 1.0.2 63K

Also, take a look at this awesome tool https://cost-of-modules.herokuapp.com created by @pastelsky

makaravind commented 6 years ago

Immutable functions: Returns a brand-new array instead of modifying the input array or object 🍬 4_javascript

makaravind commented 6 years ago

A quick reminder for all react developers! ⚡️❄️ 5_0_javascript

makaravind commented 6 years ago

Definitely adaptation for ReactJs is growing exponentially ( _not literally_ ) ! 📢🌝

8_frameworks

source

makaravind commented 6 years ago

One of the many new APIs in ECMA15 is proxy,Which allows metaprogramming. Here is an example how you can validate the properties of an object by creating its proxy object.

9_javascript_proxy

makaravind commented 6 years ago

Here is how you can validate the properties being added to an object using proxy Proxy set trap can be used to check the value being added to the object and can be modified before actually being part of the object. 😎 💥 💥

10_javascript_proxy

makaravind commented 6 years ago

Fonts are awesome! It is always overwhelming to choose from a plethora of options. But not anymore

Here is, fontjoy automatically generates amazing font pairing in one click. sweet! ⚡️ worth checking out! 🔮🎄🎅

capture

makaravind commented 6 years ago

Checking the type of the property being added to the object, and throwing an error otherwise using ES6 Proxy API. Extremly useful for validating the contents of API response. 👊 ✊ ✌️

11_javascript_proxy

makaravind commented 6 years ago

Another great application of ES6 proxy 🎊 You can update the properties of an object based on the properties being set. set, get are called as traps. 12_js_proxy

makaravind commented 6 years ago

Randomly generate dice object property faceValue on get using MetaProramming in javascript.

13_js_proxy

makaravind commented 6 years ago

Formatting the properties before 'actually' setting the object property-value using Proxy API in ES6

14_js_proxy

makaravind commented 6 years ago

Regex is awesome! But Javascript Regex API _exec, match, search_ methods all seem to be same but has subtle changes.

This will help you understand the difference: 💯

15_js_regex

makaravind commented 6 years ago

Latest Update 😆 😁 😉 😜

Microsoft has reportedly acquired GitHub, and could announce the deal as early as Monday.

Microsoft has been rapidly investing in open source technology since Satya Nadella took over the CEO role. Microsoft has open sourced PowerShell, Visual Studio Code, and the Microsoft Edge JavaScript engine. Microsoft also partnered with Canonical to bring Ubuntu to Windows 10, and acquired Xamarin to assist with mobile app development.

16_0_js_reduce

Javascript Reduce API 💛

16_1_js_reduce

Reduce API is often used in situations where you would combine operations like MAP-JOIN, MAP-FILTER etc

makaravind commented 6 years ago

Javascript Reduce API 💛 Balanced parenthesis checker using javascript reduce 😆

17_js_reduce

makaravind commented 6 years ago

How To Better Code By John Papa 💛

18_refactor

This was discussed in ng-conf-2018. For complete talk, check out here

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

creating custom scripts

Additionally, arbitrary scripts can be executed by running npm run-script . Pre and post commands with matching names will be run for those as well (e.g. premyscript, myscript, postmyscript). Scripts from dependencies can be run with npm explore -- npm run

19_npm

more examples and usecases in next posts 🎅 🎄

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

npm supports the "scripts" property of the package.json file, for the following scripts There’s quite a few hooks that npm knows about out of the box, and hence will run for you, if they are defined: 😍

command description
prepublish publish postpublish Run BEFORE/AFTER the package is published
preinstall install postinstall Run BEFORE/AFTER the package is installed
preuninstall uninstall postuninstall Run BEFORE/AFTER the package is uninstalled.
pretest test posttest Run by the npm test command.
prestart start poststart Run by the npm start command.

For all of these there’s respectively pre and post hook. This comes very handy to manage the life cycle of your application.

more examples and use cases in next posts 🎅 🎄

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

npm supports the "scripts" property of the package.json file

All scripts under scripts can be executed with npm run-script [script name]. Like this, to run our test command: npm run-script test

There are two scripts that npm supports out of the box; test and start. When I write supports it’s more like; there’s very convenient, well-known short cuts for them.

20_npm

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

If you haven’t seen it && is a simple way of running a few commands in a row. "pretest": "rm -r ./logs/ && mkdir logs"

21_npm

21

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

npm supports the "scripts" property of the package.json file. arbitrary scripts can be executed by running npm run-script

"scripts": { "lint": "jslint '*.js'" }

jslint is only required for the development environment. And now everyone has to have it installed globally? No. This is a development time dependency for my package. It only needs to be installed if you’re going to run npm run jslint.

This is what devDependencies 😳 in the package.json is for. You can install and save the dependency like this npm install jslint --save-dev.

22

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

22_npm

24

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

Piping result into the next command

"build-js": "browserify -t reactify app/js/main.js | uglifyjs -mc > static/bundle.js"

  1. By using the | you can take the result of one task and pass it on to the next.
  2. The output of the browserify command is a bundled file with all the code from all the required modules into one file (the -t reactify is simply packing up .jsx React stuff).

26

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

Different Ways Of Installing A Package Using npm install

Install a package

npm install (with no args, in package dir)

npm install [<@scope>/][name]

npm install [<@scope>/][name]@[tag]

npm install [<@scope>/][name]@[version]

npm install [<@scope>/][name]@[version range]

npm install [git-host]:[git-user]/[repo-name]

npm install [git repo url]

npm install [tarball file]

npm install [tarball url]

npm install [folder]

alias: npm i common options: [-P|--save-prod|-D|--save-dev|-O|--save-optional] [-E|--save-exact] [-B|--save-bundle] [--no-save] [--dry-run]

Valid Package is:

a) A folder containing a program described by a package.json file b) A gzipped tarball containing (a) c) A url that resolves to (b) d) A [name]@[version] that is published on the registry (see npm-registry) with (c) e) A [name]@[tag] (see npm-dist-tag) that points to (d) f) A [name] that has a "latest" tag satisfying (e) g) A [git remote url] that resolves to (a)

27

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

While installing a npm package you can decide its scope. For example, You might not need any linting packages like EsLint to be installed in production server as it's sole purpose is for developers.

Here are the various flags available for the same use case :

-P, --save-prod: Package will appear in your dependencies. This is the default unless -D or -O are present.

-D, --save-dev: Package will appear in your devDependencies.

-O, --save-optional: Package will appear in your optionalDependencies.

--save: Package will apperar in dependencies.

--no-save: Prevents saving to dependencies.

28

makaravind commented 6 years ago

JS-WAT ? ⚡️⚡️😳

carbon 1

By the way, This is not a bad part of javascript, Browser is to be blamed! 💯

29

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

While setting up your code in production:

With the --production flag (or when the NODE_ENV environment variable is set to production), npm will not install modules listed in devDependencies.

npm install --production

NOTE: The --production flag has no particular meaning when adding a dependency to a project. source

30

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

Limitation Of NPM install Algorithm

note: This is something that a developer might never think of. But it's always good to know the limitations of any system.

consider that A, A, B, B are packages and their dependencies.

A -> B -> A' -> B' -> A -> B -> A' -> B' -> A -> ...

where A is some version of a package, and A' is a different version of the same package. Because B depends on a different version of A than the one that is already in the tree, it must install a separate copy. The same is true of A', which must install B'. Because B' depends on the original version of A, which has been overridden, the cycle falls into infinite regress.

To avoid this situation, npm flat-out refuses to install any name@version that is already present anywhere in the tree of package folder ancestors.

here is the source

30

makaravind commented 6 years ago

Javascript Gym ⚡️⚡️

Use Intl.NumberFormat to enable country / currency sensitive formatting.

 const toCurrency = (n, curr, LanguageFormat = undefined) =>
   Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);

Examples :

  toCurrency(123456.789, 'EUR'); // €123,456.79  | currency: Euro | currencyLangFormat: Local
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79  | currency: US Dollar | currencyLangFormat: English (United States)

Check if browser is tab of the page is focused.

 const isBrowserTabFocused = () => !document.hidden;

31

makaravind commented 6 years ago

Javascript Gym ⚡️⚡️

1. Scroll to functionality using native window.scrollTo browser API

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
}; 

/*
Get distance from top using document.documentElement.scrollTop or document.body.scrollTop. 
Scroll by a fraction of the distance from the top. Use window.requestAnimationFrame() to animate the scrolling.
*/

2. Detects wether the website is being opened in a mobile device or a desktop/laptop.

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

/*
  navigator.userAgent is the same value that is sent as request header 'user-agent';
  More on HTTP headers, soon!😇
*/
makaravind commented 6 years ago

Java Jazz ⚡️⚡️

Java 10 introduced the language feature of Local-Variable Type Inference.

var list = new ArrayList<String>();
  1. The compiler will infer that list is of type ArrayList.
  2. Using var can help you reduce some of the verbosity, especially with regard to generics and cases where generics are already present in the initialization of the variable or implied in its name.

GuideLines to use Var efficiently

33

makaravind commented 6 years ago

Java Jazz⚡️⚡️

possibly in Java 11 there will be addition of raw string literals to the language.

In a raw string, every character in the string is read as is.

String html = "<html>\n" +
              "  <body>\n" +
              "    <p>Hello World.</p>\n" +
              "  </body>\n" +
              "</html>\n";

Using a raw string literal, it can be written like this instead:

String html = `<html>
                 <body>
                   <p>Hello World.</p>
                 </body>
               </html>
              `;

34

makaravind commented 6 years ago

Java Jazz⚡️⚡️

Switch Expressions (proposal)

If you’ve ever written switch statements that simply set a variable based on what you’re switching over, With switch expressions, you can simplify that to:

int val = switch (str) {
  case "foo": break 1;
  case "bar": break 2;
  case "baz": break 3;
  default: break -1;
}

break will also take the resulting value of the switch expressions, similar to how return works for method return values. a shorthand notation, similar to the lambda syntax, is proposed:

int val = switch (str) {
  case "foo" -> 1;
  case "bar" -> 2;
  case "baz" -> 3;
  default -> -1;
}

There is already an implementation of switch expressions in the amber repository, so it’s just a matter of time until it will be finalized, fully tested, code reviewed, and approved, before it can be targeted and added to a JDK release. This could be as early as Java 11.

34

makaravind commented 6 years ago

Javascript Gym ⚡️⚡️

Promise.all()

 Promise.all([
    asyncFunc1(),
    asyncFunc2(),
])
.then(([result1, result2]) => {
    ···
})
.catch(err => {
    // Receives first rejection among the Promises
    ···
});

35

makaravind commented 6 years ago

Fun With HTTP Header ⚡️⚡️

User-Agent

Common format for web browsers:

User-Agent: Mozilla/\ (\) > \ (\) \

Major browsers' UA(user-agent) strings 👍

  1. Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
  2. Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0

Mozilla/5.0 is the general token that says the browser is Mozilla compatible, and is common to almost every browser today.

But, Crawler and bot UA strings looks different 👌

  1. Googlebot/2.1 (+http://www.google.com/bot.html)

It is quite straight forward to go ahead and use ✊ UA for capturing more information of the user. but, There is a catch here 😲. Genereally it is a bad practice to do UA sniffing as UA can be changed or modified.

Summary: UA detection Checklist Zen 😇

  1. Do not detect user agent strings
  2. Use responsive design for your new mobile sites (media queries)
  3. If you are using a specific feature, use feature detections to enhance, not block
  4. And if finally you are using UA detection, just go with the most simple and generic strings. Always provide a working fallback whatever the solutions you chose are.

MDN docs

36

makaravind commented 6 years ago

Fun With HTTP Headers ⚡️⚡️

Last-Modified / If-Modified-Since

Pre-Conditional Headers

A conditional GET is an HTTP GET request that may return an HTTP 304 response (instead of HTTP 200). An HTTP 304 response indicates that the resource has not been modified since the previous GET. and so the resource is not returned to the client in such a response.

HTTP Date format: \, \ \ \ \:\:\ GMT

This combination of headers is extremely useful for cache or concurrency controlling. Usage of this headers combo is very neatly explained in this illustration. Illustation here

36

makaravind commented 6 years ago

Fun With HTTP Headers ⚡️⚡️

Content-disposition /Content-type

carbon 2

Adding Content-disposition header forces the browser to download the file. In case if it is removed the file will be shown inline i.e the content is shown on the browser window.

note: Content-disposition is always used along with Content-type

Here are few possible combinations of these 2 headers: 😎

1 🙊

Content-Type: application/octet-stream Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

2 🙈

Content-Type: image/png Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

3 💥

Content-Type: image/png Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Despite being pretty useful, Content-disposition has got it's issues. Check this out Issues

makaravind commented 6 years ago

NPM_SCRIPTS TREAT ⚡️⚡️

How To Publish NPM Module

Assuming that you already have tried and tested your project locally

  1. Create account NPM account
  2. Package.json, Make sure you have removed private=true field from package.json
  3. Make sure name field shoud be unique across all npm packages note: Uppercase characters are disallowed in new package names
  4. Terminal, run npm adduser
  5. Enter your details
  6. Check is you are logged in using npm whoami
  7. For further sanity checks, create a npm-script prepublish to lint/ test etc
  8. Run npm publish
  9. If everything is fine, package will be published and you will receive a success 👍 message on your mail 📫

    39

makaravind commented 6 years ago

Javascript Gym ⚡️⚡️

shiny new finialized feature of ECMA2018 release.

Object Rest/ Spread

 const DEFAULTS = {foo: 'a', bar: 'b'};
const userData = {foo: 1};

const data = {...DEFAULTS, ...userData}; // final, {foo: 1, bar: 'b'}
const _data = Object.assign({}, DEFAULTS, userData); // gives same result

In this snippet, the default object will be overridden by user data. Observe that the order in which object are spread matters

Discussed in detail in the blog

40

makaravind commented 6 years ago

Javascript Gym ⚡️⚡️

shiny new finialized feature of ECMA2018 release

Promise.prototype.finally

 let connection;
db.open()
.then(conn => {
connection = conn;
return connection.select({ name: ‘Jane’ });
})
.then(result => {
// Process result
// Use `connection` to make more queries
})
···
.catch(error => {
// handle errors
})
.finally(() => {
connection.close();
});

The most common use case is similar to the most common use case of the synchronous finally clause: cleaning up after you are done with a resource. That should always happen, regardless of whether everything went smoothly or there was an error.

Discussed in detail in the blog

41

makaravind commented 6 years ago

Node Stuff ⚡️⚡️

promisify callbacks in node 8+

const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);

async function callStat() {
  const stats = await stat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}

promisify() assumes that original is a function taking a callback as its final argument in all cases. If original is not a function, promisify() will throw an error.

If original is a function but its last argument is not an error-first callback, it will still be passed an error-first callback as its last argument.

42

makaravind commented 6 years ago

Javascript Gym ⚡️⚡️

You can pass arguments to setTimeout or setInterval's callbacks

  function logThings(a, b, c) {
    console.log(a, b, b);
  }

  const afterOneSecond = 1000;
  setTimeout(logThings, afterOneSecond, 'arg1', 'arg2', 'arg3');

42

makaravind commented 6 years ago

Cache Buster ⚡️⚡️

What is server-side caching?

43

In the image above, A caching proxy is a server that stores the static files that are used to respond to common requests. A caching proxy will intercept common requests and quickly deliver a response. It prevents those requests from stressing your main web servers.

The caching proxy will have different files that have been cached at different times, and it needs to decide whether it should still serve these files. This will depend on your caching policy.

Whole bunch of these situated across the world forms, what's called as CDN

Some common CDN providers include Rackspace, Akamai, and Amazon Web Services.

source

> #43

makaravind commented 6 years ago

Cache Buster ⚡️⚡️

Client-Side Caching - browser

People across the country (or the world) can get responses quickly through CDN. There’s just one issue — they have no way to store it. Your customers still need to request for the resources incase of refresh.

The solution? Client-Side Caching

44

Separate location for storing static assets since it is on the client-side, or on the same computer as the browser.

This is great for sites like Facebook or Amazon that you might frequently visit. It’s great for their server costs too, since they can reduce the number of requests they need to handle.

How does your browser know when to request new files from the server? Otherwise, you would never experience updated versions of these local files. Well, just like milk producers put a date on their milk packaging, servers will add some sort of identifier within the HTTP response header.

source

44

makaravind commented 6 years ago

Cache Buster ⚡️⚡️

"Site Performace Is A Feature", One way is setting up caching

Caching’s Ugly Secret: It Gets Stale

Popular Methods

  1. Last-Modified Illustation here
  2. ETag
  3. Expires
  4. Max-Age

source

45

makaravind commented 6 years ago

Cache Buster ⚡️⚡️

A great tool to find more about your app including cache content information

redbot.org

46

makaravind commented 6 years ago

Cache Buster ⚡️⚡️

That Tip

If you are a web develper, the worst thing that could happen is wasting your whole day refreshing your browser wanting to see the changes. I understand

This little tip can save your precious time and money. Yeah you can buy me a coffee sometime.

47

Check the disable cache option in chrome network tab.

47

makaravind commented 6 years ago

Git VCS ⚡️⚡️

That Tip

$ git branch

Lists all local branches in the current repository

48

makaravind commented 6 years ago

Git VCS ⚡️⚡️

That Tip

$ git rm --cached \<file>

Removes the file from version control but preserves the file locally

why use git rm not rm (bash) ?

49