-
-
Save junaidulqayyumqureshi/1f5a1fca2c7db1957d5bd70c20c66e6a to your computer and use it in GitHub Desktop.
Code snippets which I use more often in projects |
Object.create()
const mainObj = {
objA: function() {
console.log('An object')
},
objB: function() {
console.log('Another object')
}
};
let objUser = Object.create(mainObj);
Now objUser
has all the properties of mainObj
. Whenever a new property is introduced in mainObj
, it will automatically be available to objUser
It is similar to polymorphism in OOP. How? Let me explain!
Consider mainObj
a class and n number of objects can be created with mainObj
and all the objects will have all the properties of that class, mainObj
. Though it is not a class, but still we can consider it a one.
Issue
function aFunction(name) {
let baby = Object.create(aFunction.prototype);
baby.name = name;
baby.calculateAge = function(dob){
return a*b;
};
return baby;
}
let abdullah = aFunction('abdullah');
There is a function aFunction which needs to have another function called calculateAge.
What happens is that every time you call aFunctin(name), it will create a new function calculateAge() in the memory, every time it is called.
So, to optimize this, prototyping is introduced. WHY? because prototype is an object which will only be created once whether there are hundreds of aFucntion objects exists or just one, prototype property will only be issued once so calculateAge() function can be assigned to prototype property of the function and utilize whenever needed. See examples below
Javascript Prototyping
A protoype is a property/attribute which every function has, and points to an object.
Taking above example into consideration:
we can create a new function called aFunction
function aFunction(name) {
let baby = Object.create(aFunction.prototype);
baby.name = name;
return baby;
}
aFunction.prototype.calculateAge = function() {
return a*b;
}
aFunction.prototype.eats = function() {
console.log(`${this.name} eats`);
}
aFunction.prototype.sleeps = function(mins) {
console.log(`${this.name} sleeps for ${mins} minutes`);
}
aFunction.prototype.laughs = function() {
console.log(`${this.name} laughs`);
}
const abdullah = aFunction('abdullah');
const ayesha = aFunction('ayesha');
Protypal Inheritance
function aFunction(name) {
this.name = name
}
function bFunction(newName) {
aFunction.call(this, newName)
//aFunction.call is equivalent to parent::__construct() in php
}
Inheritance
bFunction.prototype = Object.create(aFunction.prototype)
Where Object.create is necessary so that it replicates it, instead of reference. Because if referenced. change to bFunction.prototype will also reflect in aFunction.prototype and vice-versa
Above code will inherit all the properties from aFunction prototype to bFunction prototype
New keyword
Above example can be enhanced and reduced to little lines of code by following tweaks:
function aFunction(name) {
this.name = name;
}
aFunction.prototype.eats = function() {
console.log(`${this.name} eats`);
}
aFunction.prototype.sleeps = function(mins) {
console.log(`${this.name} sleeps for ${mins} minutes`);
}
aFunction.prototype.laughs = function() {
console.log(`${this.name} laughs`);
}
const abdullah = new aFunction('abdullah');
const ayesha = new aFunction('ayesha');
The New keyword, will automatically understand, that it has to initialize an object with Object.create method self assigns all the properties like prototypes and returns it without us writing a return statement
ES6 Class syntax
We can write the above example in proper OOP fashion without oop involved, thanks to ES6 syntax.
class aFunction {
constructor(name) {
this.name = name;
}
eats = function() {
console.log(`${this.name} eats`);
}
sleeps = function(mins) {
console.log(`${this.name} sleeps for ${mins} minutes`);
}
laughs = function() {
console.log(`${this.name} laughs`);
}
}
const abdullah = new aFunction('abdullah');
const ayesha = new aFunction('ayesha');
Now we are thinking that where is prototype keyword is gone?
Well not really gone, if you console.log the aFunction which is now a class, due to new keyword, you will still see the function attributes i.e. prototypes and all
The new keyword transformed it into a class but it isn't really a class as you see in Object Oriented Programming. This is just a syntax you created with the help of ES6.
Take an example of an array. You init an array by:
let arr = [];
You initialized an array, but where did all the functions come from? like where is splice, slice, pop, push etc
. It is there but is sugar-coated with []
these brackets and behind this, the initialization was:
let arr = new Array()
which is similar to your new aFunction()
Event Delegation
<ul id="list">
<li>
Apple
</li>
<li>Banana</li>
<li>
<a>
Kharbuza
</a>
</li>
</ul>
<script type="text/javascript">
const fruitsList = document.getElementById('list');
fruitsList.addEventListener("click", function(e) {
let target = e.target;
if (target.matches('li')) {
console.log('li');
}
})
</script>
Angular
Decimal Pipe
{{ sale | number : '1.0-0' }}
for 27,120,254
{{ sale | number : '1.0-2' }}
for 27,120,254.25
Check Server CPU information
CPUs = Threads per core X cores per socket X sockets
lscpu | grep -E '^Thread|^Core|^Socket|^CPU\('
Using NodeJS
require("os").cpus().length
Unique Items
[...new Set( [1,1,2,3,4,4] )
Laravel Backup
Choose version first from
Source
For laravel v5
composer require "spatie/laravel-backup:^5.0.0"
For Laravel v6
composer require spatie/laravel-backup
For config files
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"
For backup
php artisan backup:run
OR
php artisan backup:run --only-db
Email Backup
Non-Spatie Backup
Copy following content in a app > Console > Commands > DBBackup.php
<?php
namespace App\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
class DBBackup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:backup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create Database Backup';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$filename = "backup-" . Carbon::now()->format('Y-m-d') . ".gz";
$command = "mysqldump --user=" . env('DB_USERNAME') . " --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . " | gzip > " . storage_path() . "/app/backup/" . $filename;
$returnVar = null;
$output = null;
exec($command, $output, $returnVar);
}
}
Run php artisan db:backup
PHP Script Execution Time
$time_start = microtime(true);
//sample script
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;
Last DAY PHP => Previous Day PHP
date('Y-m-d', strtotime('-1 day', strtotime("2020-01-01")))
Clone array but without reference JS
arr2 = JSON.parse(JSON.stringify(arr1))
Loop through a JSON Object Keys
for (var key of Object.keys(p)) {
console.log(key + " -> " + p[key])
}
Check storage of a directory
sudo du -sh /var
Image Magic OR Imagick
INSERT INTO SELECT STATEMENT
INSERT into tableA (id, colA, colB, ...) (SELECT id, colA, colB, ...)
ZIP Archive Linux
zip -r myfiles.zip mydir
Bubble Sort
$arr = [7,3,1,4,2];
$toGo = true;
while($toGo){
$swap = false;
for ($i=0; $i < sizeof($arr); $i++) {
if($i == sizeof($arr)-1)
continue;
if($arr[$i] > $arr[$i+1]){
$swap = true;
[$arr[$i], $arr[$i+1]] = [$arr[$i+1], $arr[$i]];
}
}
if(!$swap)
$toGo = false;
}
echo "<pre>"; print_r($arr);
PHP ARRAY FUNCTIONS (Fat Arrow)
array_map(fn($tag) => new Tag($tag), $tags)
array_filter($stock, fn($item) => $item['qty'] > 0)
array_reduce($team, fn($carry, $person) => $carry + $person['points'], 0);
Laravel Service Containers
For example:
You have a class App\Billing\Stripe which requires some additional values in it's constructor i.e. Secret Key
Now you can bind App with the class and inject the dependency in it's constructor like it is done in the Screenshot above.
You won't need to reinitialize the class ever again in the project as you have already done this and now you can call the binding by App::make('classname')
or resolve('classname')
and you will have the ready instance without passing anything in the constructor
MYSQL STORE PRODCEDURE
DELIMITER $$
CREATE PROCEDURE `insert_into_order_contents_tables`(
IN `pref_id` INT,
IN `item_quantity_booker` VARCHAR(100)
)
BEGIN
insert into order_contents (
pref_id,
item_quantity_booker
) values (
pref_id,
item_quantity_booker
);
END$$
DELIMITER ;
POSTGRESQL DB Export Windows Command Line
Open Powershell.
Go to Postgres bin folder. For example: cd "C:\Program Files\PostgreSQL\9.6\bin"
Enter the command to dump your database. For example: ./pg_dump.exe -U postgres -d my_database_name -f D:\Backup\<backup-file-name>.sql.
Type password for your postgres user.
CORS ISSUE
The CORS issue should be fixed in the backend. Temporary workaround uses this option.
Go to C:\Program Files\Google\Chrome\Application
Open command prompt
Execute the command chrome.exe --disable-web-security --user-data-dir="c:/ChromeDevSession"
Transfer data from one server to another
Copy files from one SSH to another SSH server
scp /path/to/file username@a:/path/to/destination
Step 1:
Zip the product
zip -r product.zip /var/www/product
Step 2:
Take db dump on host server
mysqldump -u root -p spencer > /var/www/exported.sql
Step 3:
Transfer it to new server
scp /var/www/spencer.zip root@{ipaddresss}:/var/www/product-destination-on-remote-server
Import Export MySQL DB Command Line
Export Dump.sql WITH/WITHOUT SCHEMA
mysqldump -u root -p DB_NAME > /var/www/exported.sql
mysqldump -u root -p --no-data DB_NAME > /var/www/exported.sql
Import Dump.sql
mysql -u root -p database_name < file.sql
Find string/substring linux
grep -rnw '/var/www/project' -e 'stringtosearch'
NodeJS Worker Threads
main.js
const { Worker } = require('worker_threads');
const worker = new Worker('./wthread.js');
worker.on('message', (msg) => {
console.log(`Msg: ${JSON.stringify(msg)}`);
});
// worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
throw new Error(`stopped with ${code} exit code`)
})
wthread.js
const { workerData, parentPort } = require('worker_threads')
parentPort.postMessage({ "StartedAt": workerData })
------ Code Logic ------
parentPort.postMessage({ result: result })
Array Reduce
obj.reduce((acc, x) => acc + x.qty, 0)
WHERE ,0 means from which value it should start, so we said, add everything into 0 means 0+27+37+5 etc
What it will do is, it will add all the values from amount column from a JSON object
Loop through a JQuery Datatable
Check Angular Version of any website
getAllAngularRootElements()[0].attributes["ng-version"]