Wednesday, December 16, 2020

15 ‘Hacks’ In JavaScript

 15 ‘Hacks’ In JavaScript

Enjoy working with these simple wow JavaScript hacks.


Learning JavaScript language is easy but using it to develop an interactive web interface requires specific tricks and techniques. Thus, to facilitate you to use this programming language easily, I had brought a list of wow hacks that will help you optimize the performance, speed and save time while development of the website.


1) Async/ await with destructing:

It’s simply wonderful how the Array Destructing can offer so many functions. If you wish to make a complex flow much simpler, just combine array destruction with async/await and see what it does!

Use this:

const [user, account] = await Promise.all([
fetch('/user'),
fetch('/account')
])

2) Use ‘!!’ Operator to convert to boolean:

This (!!) is known as the double negation operator in the JavaScript language. The programmers can use it to find out whether a variable exists or has a valid value to be considered as true value or not. Thus, use a simple ‘!!variable’. This can convert the data automatically to a boolean which will come back as false if it showcases any of these values: 0,””, null, NaN, or undefined. In an otherwise case, it will come back as true. The hack is as follows:

function Account(cash) {this.cash =cashthis.hasMoney = !!cash;}var account   =  new Account(100.50);console.log(account.cash); // 100.50console.log(account.hasMoney); // truevar emptyAccount = new Account(0);console.log(emptyAccount.cash); // 0console.log(emptyaccount.hasMoney); // fasle

In the above-mentioned case, if the value of account.cash is greater than zero, the account.hasMoney will be considered true. Try it out yourself and see how well it works!

3) Swap variables:

You can make this happens by using the array destruction to swap the values. Use this code to do it:

let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world
// Yes, it's magic

4) Use the + operator to convert to numbers:

At number four, we have a very simple yet magical hack that works with string numbers. If not, then it will return as NaN that indicates being not a number.

function toNumber( strNumber) {return +strNumber;}console.log(toNumber( “1234”)); // 1234console.log(toNumber(“ABC”)); // NaN

You can use this magical hack with dates too. For the dates, it goes as follows:

console.log(+new Date( )) // 1461288164385

5) Short-circuit conditionals:

Are you willing to shorten the code? Using shortcuts can save time and speed up the operation. Thus, if you see such a code somewhere

If(connected){Login()}

You can combine the variables and a function with the help of && (AND operator) to shorten the code. The above code will look as below:

connected &&login();

Another code can also be used:

User&&user.login();

6) Debugging hack:

If you use console.log to debug, you’ll be amazed by this hack. Here you go:

console.log({ a, b, c })// outputs this nice object:
// {
// a: 5,
// b: 6,
// c: 7
// }

7) How to detect properties in an object with a hack?

The answer to this very question is given below. It is used to check if an attribute exists or not. It helps by preventing to run undefined functions or attributes.

An example will help you understand in a better way. Say you need a code that is compatible with the old internet explorer 6 version and you want to use document.querySelector() to get some of the elements by their ids. But, in the latest browser this function does not exist and so you can use the ‘in’ operator to check the earlier existence of the function.

if (‘querySelector’ in document) {document.querySelector(“#id”);} else {Document.get Element ById(“id”);}

This states that if there is no ‘querySelector’ function in the document object, the document.getElementById function will be used as a fallback.

8) One-liners:

The Syntax is quite compact for the array operations

// Find max value
const max = (arr) => Math.max(...arr);
max([123, 321, 32]) // outputs: 321
// Sum array
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10

9) Array concatenation:

Use the concat in place of the spread operator:

one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']
// Old way #1
const result = one.concat(two, three)
// Old way #2
const result = [].concat(one, two, three)
// New
const result = [...one, ...two, ...three]

10) Array filter usage:

If you are looking for a hack to save time and omit the multiple lines of code, then array filter code is the one for you! Use this to filter out the desired elements from the array pool. With this process, you’ll create an array full of all array elements that pass a test. For the non-required elements, you can create a callback function.

For example:

schema = ["hi","ihaveboyfriend",null, null, "goodbye"]schema = schema.filter(function(n) {            return n        });Output:   ["hi","ihaveboyfriend", "goodbye"]

11) Get your floating number ensuring good performance:

The micro-optimization in the code is what boosts the performance and helps eliminate decimals using “~~” instead of math.ceil, math.floor, and math.round.

Thus, replace math.round(math.random*100)

with ~~ (math.random*100)

12) Array elements are deleted using splice:

How does this help? Well, to tell you the truth, it is the best JS code used for speed optimization. It saves the some of the “null/ undefined space” in the code. If you use delete instead of the splice, the object property would be deleted without the arrays reindex or length update.

The sample for you:

myArray = ["a", "b", "c", "d"] myArray.splice(0, 2) ["a", "b"] Result: myArray ["c", "d"]

13) Get the last item in the array:

If you want to cut the arrays, you can set the begin and end arguments like Array.prototupe.slice(begin, end). Not setting the end argument means that the function will automatically go for the max value for the array. This function also accepts the negative values. If you set a negative number as begin an argument, you will obtain the last element from the array.

It is as follows:

var array=  [1, 2, 3, 4, 5, 6];console.log(array. Slice(-1)); // [6]console.log(array. Slice(-2)); // [5, 6]console.log(array. Slice(-3)); // [4, 5, 6]

14) Named parameters:

The developers can use this code hack to make the function and function calls more readable with the help of destructuring. The hack is as follows:

const getStuffNotBad = (id, force, verbose) => {
...do stuff
}
const getStuffAwesome = ({ id, name, force, verbose }) => {
...do stuff
}// Somewhere else in the codebase... WTF is true, true?
getStuffNotBad(150, true, true)// Somewhere else in the codebase... I ? JS!!!
getStuffAwesome({ id: 150, force: true, verbose: true })

15) Cloning:

Enjoy the ease of cloning arrays and objects with ease. Just keep in mind that it produces a shallow clone.

const obj = { ...oldObj }
const arr = [ ...oldArr ]

Conclusion:

With this, your stock of having cool and simple hacks for the JavaScript programming is now full. You can place these codes and functions in various places and enjoy the benefit of enhanced performance and good speed.


Reference

Saturday, December 5, 2020

Reset VBA Password

 Reset VBA Password

1) Rename XLSM to Zip extension.

2) Don't extract this zip, but Open the file with 7-Zip

3) Copy file from xl -> vbaProject.bin (you can drag and drop from 7-Zip).

4) Don't clse zip application

5) open vbaProject.bin with HexEditor and find for "DPB=" and replace it with "DPx", save the file and move back to xl folder in the zip file.

6) Rename zip with XLSM now, and open the file.


if prompted to "Continue Loading Project", click Yes. If prompted with errors, click OK.Press Alt+ F11 to open the VBA editor.

While press it will show error “Unexpected error (40230)”, just click OK (6 or 7 times) until it goes away.

Then it will open Automatically

Then set a new password and save the file...

Monday, November 30, 2020

Email with Attachment using Excel VBA

One of my friend ask me, is it possible to send multiple emails with attachments using Excel VBA. I said YES, everything is possible. Below is just small code that can help you to do it.


Happy Coding :)

Thursday, November 26, 2020

Datatables - Keeping selected page number after callback

I save the DataTable state in the local storage to avoid passing the page number all over my app. This is how I do it:
This is very useful when you go to another page and you want to go back (using the back button) to the last selected page.
reference

Tuesday, October 6, 2020

Sort JSON Array with Value

Example:Sort JSON Array

Thursday, September 10, 2020

Selecting distinct values from a JSON

 

eData is the JSON array

var items = eData.map((d)=> {return d.year})

var uniq = items.filter(GetUnique)


function GetUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

Thursday, August 6, 2020

Replacing SharePoint Designer with VS Code

“Replacing SharePoint Designer with VS Code”

- install VS Code
- Add extension SPGO to your VS Code
- Execute following 2 thing
------ Connect to workspace
Press F1 : write > SPGO Configuration Workspace
put the URL and some relevant default inputs

-- new SPGO.json file will be created something like:

{
  "sourceDirectory": "src",
  "sharePointSiteUrl": "https://domain.sharepoint.com/itBudget",
  "workspaceRoot": "f:\\SPApps\\itBudget",
  "publishWorkspaceOptions": {
    "destinationFolder": "/",
    "globPattern": "f:\\SPApps\\itBudget\\src\\**\\*.*",
    "localRoot": "f:\\SPApps\\itBudget\\src"
  },
  "publishingScope": "SaveOnly",
  "authenticationType": "Digest",
  "remoteFolders": ["/SiteAssets/Custom/js", "/Pages", "/SitePages"]
}

Press F1 again: write > SPGO Populate local workspace
enter : registered EMail and Password.

Source found at following URLs

Wednesday, August 5, 2020

Unable to open SharePoint Designer Site



Unable to open SharePoint Designer Site

Remove all the content from following folders to avoid issue
  • %APPDATA%\Roaming\Microsoft\Web Server Extensions\Cache
  • %APPDATA%\Microsoft\Web Server Extensions\Cache
  • %APPDATA%\Microsoft\SharePoint Designer\ProxyAssemblyCache
  • %USERPROFILE%\AppData\Local\Microsoft\WebsiteCache
  • %APPDATA%\Microsoft\SharePoint Designer

Monday, July 27, 2020

Create QR-Code with VBA

Function to add QR-Code as image in your file.


Function Insert_QR(codetext As String)
	Dim URL As String, MyCell As Range

	Set MyCell = Application.Caller
	URL = "https://chart.googleapis.com/chart?chs=125x125&cht=qr&chl=" & codetext
	On Error Resume Next
	  ActiveSheet.Pictures("My_QR_" & MyCell.Address(False, False)).Delete 'delete if there is prevoius one
	On Error GoTo 0
	ActiveSheet.Pictures.Insert(URL).Select
	With Selection.ShapeRange(1)
	 .PictureFormat.CropLeft = 10
	 .PictureFormat.CropRight = 10
	 .PictureFormat.CropTop = 10
	 .PictureFormat.CropBottom = 10
	 .Name = "My_QR_" & MyCell.Address(False, False)
	 .Left = MyCell.Left + 25
	 .Top = MyCell.Top + 5
	End With
	Insert_QR = "" ' or some text to be displayed behind code
End Function


Excel To PDF with VBA

 

Sub ConvertExcelToPDF()
'Export Single Sheets
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="TrainingDeo",      OpenAfterPublish:=True

'Export Multiple Sheets
Sheets(Array("RemovingDuplicates", "HideUnhide", "ExportToPDF")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="TrainingDemo2", OpenAfterPublish:=True

Sheets("ExportToPDF").Select
Range("A1").Select
End Sub


Reference Code at YouTube

Friday, July 24, 2020

SQL Query to find all tables in a Database containing specified column name

Following query will help to find field name available in any of the table in a database.

SELECT * from INFORMATION_SCHEMA.COLUMNS 
where COLUMN_NAME like '%ColumnName%' 
order by TABLE_NAME



SQL Server:

SELECT Table_Name, Column_Name 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'YOUR_DATABASE'
AND COLUMN_NAME LIKE '%YOUR_COLUMN%'


Oracle:

SELECT owner, table_name, column_name 
FROM all_tab_columns 
WHERE column_name LIKE '%YOUR_COLUMN_NAME%'

AND OWNER IN ('YOUR_SCHEMA_NAME');

Thursday, July 16, 2020

Sort JSON object Array

Sort JSON object Array



Friday, June 19, 2020

Convert Dropdown to Textbox with JQuery

Here is the simple way to convert dropdown to text.


Thursday, May 28, 2020

Extract only text content from HTML in Javascript

1. Create a temporary DOM element and retrieve the text


2. using jQuery

Friday, February 28, 2020

JQuery to create Download Link

Simple way to download file without navigating.

Monday, February 17, 2020

Convert CSV data to JSON

CSV Data


Output as JSON

JSON Group by count, output to key value pair json result

Following is the JSON and need to manipulate it in format to groupBy.


Thursday, January 30, 2020

Google Chrome Keyboard Shortcuts


Window and Tab Shortcuts
Ctrl+NOpen a new window
Ctrl+Shft+NOpen a new window in incognito mode
Press Ctrl, and click a linkOpen link in a new tab
Press Shft, and click a linkOpen link in a new window
Alt+F4Close current window
Ctrl+TOpen a new tab
Ctrl+Shft+TReopen the last tab you've closed. Google Chrome remembers the last 10 tabs you've closed.
Drag link to tabOpen link in specified tab
Drag link to space between tabsOpen link in a new tab in the specified position on the tab strip
Ctrl+1 through Ctrl+8Switch to the tab at the specified position number. The number you press represents a position on the tab strip.
Ctrl+9Switch to the last tab
Ctrl+Tab or Ctrl+PgDownSwitch to the next tab
Ctrl+Shft+Tab or Ctrl+PgUpSwitch to the previous tab
Ctrl+W or Ctrl+F4Close current tab or pop-up
Alt+HomeOpen your homepage
Ctrl+O, then select fileOpen a file from your computer in Google Chrome
Address Bar Shortcuts
Type a search termPerform a search using your default search engine
Type the part of the web address that's between 'www.' and '.com', then press Ctrl+EnterAdd www.and .com to your input in the address bar and open the web address
Type a search engine keyword or URL, press Tab, then type a search termPerform a search using the search engine associated with the keyword or the URL. Google Chrome prompts you to press Tab if it recognizes the search engine you're trying to use.
F6 or Ctrl+L or Alt+DHighlight content in the web address area
Type a web address, then press Alt+EnterOpen your web address in a new tab
Shortcuts to open Google Chrome features
Ctrl+BToggle bookmarks bar on and off
Ctrl+HView the History page
Ctrl+JView the Downloads page
Shft+EscapeView the Task manager
Webpage shortcuts
Ctrl+PPrint your current page
F5Reload current page
EscStop page loading
Ctrl+F5 or Shft+F5Reload current page, ignoring cached content
Press Alt, and click a linkDownload link
Ctrl+FOpen find-in-page box
Ctrl+G or F3Find next match for your input in the find-in-page box
Ctrl+Shft+G or Shft+F3Find previous match for your input in the find-in-page box
Ctrl+UView source
Drag link to bookmarks barBookmark the link
Ctrl+DBookmark your current webpage
Ctrl++Make text larger
Ctrl+-Make text smaller
Ctrl+0Return to normal text size
Text shortcuts
Highlight content, then press Ctrl+CCopy content to the clipboard
Place your cursor in a text field, then press Ctrl+V or Shft+InsertPaste current content from the clipboard
Place your cursor in a text field, then press Ctrl+Shft+VPaste current content from the clipboard without formatting
Highlight content in a text field, then press Ctrl+X or Shft+DeleteDelete the content and copy it to the clipboard
More shortcuts
Backspace, or press Alt and the left arrow togetherGo to the previous page in your browsing history for the tab
Shft+Backspace, or press Alt and the right arrow togetherGo to the next page in your browsing history for the tab
Ctrl+K or Ctrl+EPlaces a '?' in the address bar. Type a search term after the '?' to perform a search using your default search engine.
Place your cursor in the address bar, then press Ctrl and the left arrow togetherJump to the previous word in the address bar
Place your cursor in the address bar, then press Ctrl and the right arrow togetherJump to the next word in the address bar
Place your cursor in the address bar, then press Ctrl+BackspaceDelete the previous word in the address bar
Space barScroll down the web page
HomeGo to the top of the page
EndGo to the bottom of the page

Reference