Wednesday, May 5, 2021

Export HTML table to Excel file

<!-- https://github.com/linways/table-to-excel -->

<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>


function exportReportToExcel(c) {

  let table = $("#feedbackExport2Excel"); // you can use document.getElementById('tableId') as well by providing id to the table tag

  let fileName = "Feedback";

  TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag

    name: `${fileName}.xlsx`, // fileName you could use any name

    sheet: {

      name: 'Sheet 1' // sheetName

    }

  });

}//exportReportToExcel


Wednesday, February 3, 2021

Simple way to find Index value from JSON Array

Simple way to find Index value from JSON Array 


var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];

var index = data.findIndex(obj => obj.name=="allInterests");

console.log(index);

Tuesday, February 2, 2021

Add days to a Date using JavaScript

Many times I have face this issue, and hope you too.. this is simple 3 line of code will help and fix this problem.


let days =7 ; // we are going to add 7 days to a date

let cdt = new Date('2021-01-10'); // your date value

let tdt = cdt.setTime(cdt.getTime() + (days * 24 * 60 * 60 * 1000)); // calculation for adding 7 days and adding to time

let targetDT = new Date(tdt).format("yyyy-MM-dd"); // converting back from time to date 

// Output for targetDT will be "2021-01-17"


// With function...

function addDays(theDate, days) {
    return new Date(theDate.getTime() + days*24*60*60*1000);
}

var newDate = addDays(new Date(), 5);


Hope this will help you...

Thursday, January 28, 2021

JavaScript to get index from a JSON object with value

 In modern browsers you can use findIndex:

But this function is not supported by even not so old versions of a few browser as well as in IE (EDGE supports it). So below is a workaround using javascript: You can use either Array.forEach or Array.find or Array.filter

This method takes little more overhead as it loops through the whole object to search for the match. So, for lengthy JSON data, this method is not suggested(even though it gets the work done).

Tuesday, January 5, 2021

Displaying a number in Indian format using JavaScript

Indian money format function

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...