Open makaravind opened 6 years ago
Yipeee! First Post! 💫 💥
code snippet of immutable version of Array.prototype.push in javascript
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
Immutable functions: Returns a brand-new array instead of modifying the input array or object 🍬
A quick reminder for all react developers! ⚡️❄️
Definitely adaptation for ReactJs is growing exponentially ( _not literally_ ) !
📢🌝
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.
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. 😎 💥 💥
Here is, fontjoy automatically generates amazing font pairing in one click. sweet! ⚡️ worth checking out! 🔮🎄🎅
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. 👊 ✊ ✌️
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
.
Randomly generate dice object property faceValue on get using MetaProramming in javascript.
Formatting the properties before 'actually' setting the object property-value using Proxy API in ES6
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: 💯
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.
Reduce API is often used in situations where you would combine operations like MAP-JOIN, MAP-FILTER etc
Javascript Reduce API 💛 Balanced parenthesis checker using javascript reduce 😆
This was discussed in ng-conf-2018. For complete talk, check out here
Additionally, arbitrary scripts can be executed by running npm run-script
more examples and usecases in next posts 🎅 🎄
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 🎅 🎄
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.
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 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
24
"build-js": "browserify -t reactify app/js/main.js | uglifyjs -mc > static/bundle.js"
26
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]
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
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
By the way, This is not a bad part of javascript, Browser is to be blamed! 💯
29
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
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.
30
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)
const isBrowserTabFocused = () => !document.hidden;
31
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.
*/
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!😇
*/
var list = new ArrayList<String>();
33
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
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
Promise.all([
asyncFunc1(),
asyncFunc2(),
])
.then(([result1, result2]) => {
···
})
.catch(err => {
// Receives first rejection among the Promises
···
});
35
User-Agent: Mozilla/\
(\ ) > \ (\ ) \
Mozilla/5.0 is the general token that says the browser is Mozilla compatible, and is common to almost every browser today.
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 😇
36
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:
\
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
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: 😎
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".
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".
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
Assuming that you already have tried and tested your project locally
39
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
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
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
function logThings(a, b, c) {
console.log(a, b, b);
}
const afterOneSecond = 1000;
setTimeout(logThings, afterOneSecond, 'arg1', 'arg2', 'arg3');
42
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
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
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.
44
Caching’s Ugly Secret: It Gets Stale
45
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.
Check the disable cache option in chrome network tab.
47
$ git branch
Lists all local branches in the current repository
48
$ git rm --cached \<file>
Removes the file from version control but preserves the file locally
why use git rm not rm (bash) ?
49
Subscribe to this issue and get byte sized treats daily. Hope you get ALBTY 🍬 🍭