Karim Aya

Karim Aya

1560303996

Write javascript code with high performance

I like programming puzzles. I also like to go fast. We’re going to take some LeetCode problems and solve them a few times, first improving runtime complexity in broad strokes and then looking for minor optimizations. We’re after these wonderful words:

faster than 100.00% of JavaScript online submissions

The environment we’re targetting is nodejs 10.15.0 with --harmony(source). The online judge system uses relatively small inputs for test cases as far as I can tell.

First problem

771. Jewels and Stones ~ You’re given strings <em>J</em> representing the types of stones that are jewels, and <em>S</em> representing the stones you have. Each character in <em>S</em> is a type of stone you have. You want to know how many of the stones you have are also jewels.

A naive solution here is to loop through our stones, looping through the jewels for every stone. We’ll be using standard for loops in this article as they are generally the fastest way of iterating data in JavaScript.

var numJewelsInStones = function(J, S) {
    let myJewels = 0;
    // Jewels
    for (var i = 0; i < J.length; i++) {
        // Stones
        for (var j = 0; j < S.length; j++) { // Nested!
            if (J[i] === S[j]) {
                myJewels++;
            }
        }
    }
    return myJewels;
};

The runtime is quadratic, O(N^2). Their online judge won’t actually accept this solution! We get a big fat Time Limit Exceeded. Lesson? Nested for-loops should be avoided where possible.

Let’s grab a Set to get rid of one of the loops. Reducing our runtime down to linear, O(N). Looking up a Set in JavaScript is constant time, O(1).

var numJewelsInStones = function(J, S) {
    const jewels = new Set(J); // Set accepts an iterable object
    let myJewels = 0;
    for (var i = 0; i < S.length; i++) {
        if (jewels.has(S[i])) {
            myJewels++;
        }
    }
    return myJewels;
};

For this effort, we’re rewarded with faster than 97.84%. I’m happy with this code. It’s efficient and readable. If I needed drastically better performance, I might reach for a different technology than JavaScript. We have to walk the length of both strings at least once and there’s no getting around that. We can’t beat O(N) but we can make optimizations.

The stones and jewels are defined as letters. So a-z and A-Z. This means there are just 52 different buckets our values can fall into! We can use a boolean array instead of a Set. To convert an alphabetical letter into a number, we’ll use its ASCII code point via charCodeAt. We’ll set an index to true to represent a jewel.

However, there aren’t boolean arrays in JavaScript. We could use a standard array and initialize it to length 52. Or we could use Int8Array and allow the compiler to make additional optimizations. The typed array was ~6% faster when benchmarked with a range 0-52 of random characters entered as Jand S.

Did you spot that our length is wrong? This is something I forgot as I was testing. There are seven characters between z and A on the ASCII code chart so the length required is actually 59.

var numJewelsInStones = function(J, S) {
    const jewels = new Int8Array(59);
    for (var i = 0; i < J.length; i++) {
        jewels[J.charCodeAt(i)-65] = 1;
    }
    let myJewels = 0;
    for (var i = 0; i < S.length; i++) {
        if (jewels[S.charCodeAt(i)-65] === 1) {
            myJewels++;
        }
    }
    return myJewels;
};

Et voila, our 100% fastest submission. In my tests, this was actually twice as faster as the Set version. Other optimizations I skipped testing were caching lengths, using a while loop instead of a for loop, and placing the incrementor before the number (++myJewels vs myJewels++).

Second problem

345. Reverse Vowels of a String ~ Write a function that takes a string as input and reverse only the vowels of a string.

A naive solution for this might be to loop through the array twice, replacing on the second loop. Let’s try that out first.

var reverseVowels = function(s) {
    const vowels = new Set(['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']);
    const reversed = [];
    let vowelsFound = [];
    // Find any vowels
    for (var i = 0; i < s.length; i++) {
        if (vowels.has(s[i])) {
            vowelsFound.push(s[i]);
        }   
    }
    // Build the final string
    for (var i = 0; i < s.length; i++) {
        if (vowels.has(s[i])) {
            reversed.push(vowelsFound.pop());
        } else {
            reversed.push(s[i]);
        }
    }
    return reversed.join('');
};

This nets us faster than 97.00%. The runtime is linear, O(2N) -> O(N), and it reads well but I can’t help but think we’re looping the string one more time than we have to. Let’s try a two-pointer approach. Walking in, step-by-step, from the front and back at the same time, swapping any vowels we see. If there’s a middle vowel we just leave it.

var reverseVowels = function(s) {
    const vowels = new Set(['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']);
    s = s.split('');
    let front = 0;
    let back = s.length - 1;
    while (front < back) {
        if (!vowels.has(s[front])) {
            front++;
            continue;
        }
        if (!vowels.has(s[back])) {
            back--;
            continue;
        }
        let temp = s[front];
        s[front] = s[back];
        s[back] = temp;
        front++;
        back--;
    }
    return s.join('');
};

We’ve reduced a full iteration! This gets us faster than 98.89% and it’s at this point that we need to remember that LeetCode’s benchmarks aren’t conclusive nor are they consistent. It’s not feasible for them to run a large number of iterations with a mixture of test cases. If you’re practicing your puzzle solving, stop at 97% and up. But that’s not the point of this article, and, reader, I’m going to get that 100% for you.

First I threw out the Set. The number of vowels is constant and we don’t need all that hashing going on. I tried a switch statement but then found a chained if statement was faster. I discovered that in-lining this logic was faster than a function. I then reduced this down to an expression. What I’m trying to say is: the code coming up is gross. It’s close-down-your-IDE-and-talk-a-walk gross. But … it’s faster than 100.00%.

var reverseVowels = function(s) {
    s = s.split('');
    let front = 0;
    let back = s.length - 1;
    while (front < back) {
        if (s[front] !== 'a' &&
            s[front] !== 'e' &&
            s[front] !== 'i' &&
            s[front] !== 'o' &&
            s[front] !== 'u' &&
            s[front] !== 'A' &&
            s[front] !== 'E' &&
            s[front] !== 'I' &&
            s[front] !== 'O' &&
            s[front] !== 'U') {
            front++;
            continue;
        }
        if (s[back] !== 'a' &&
            s[back] !== 'e' &&
            s[back] !== 'i' &&
            s[back] !== 'o' &&
            s[back] !== 'u' &&
            s[back] !== 'A' &&
            s[back] !== 'E' &&
            s[back] !== 'I' &&
            s[back] !== 'O' &&
            s[back] !== 'U') {
            back--;
            continue;
        }
        let temp = s[front];
        s[front++] = s[back];
        s[back--] = temp;
    }
    return s.join('');
};

(I’m sorry).

Third problem

509. Fibonacci Number ~ Calculate the nth Fibonacci number.

This is a common puzzle and it was the hardest to improve the runtime for because there are so few moving parts in the final solution. I’m sure some RNG was involved with LeetCode’s grading too. Let’s get the naive solution out of the way. The Fibonacci sequence is often used to teach recursion. However, the algorithm that is used has a runtime of O(2^n) (very slow).

I actually crashed a browser tab by trying to calculate the 50th term with this function.

var fib = function(N) {
    if (N < 2) {
        return N;
    }
    return fib(N - 1) + fib(N - 2);
}

We get faster than 36.63% for this answer. Ouch. In production, this is the kind of puzzle that can be solved by memoization (caching some of the work for later). This is the best solution because we only calculate up to the values that we need in linear time O(N) and then running the algorithm again for a term under that limit is constant time O(1).

const memo = [0, 1];
var fib = function(N) {
    if (memo[N] !== undefined) {
        return memo[N];
    }
    const result = fib(N - 1) + fib(N - 2);
    memo[N] = result;
    return result
};

faster than 94.25%. LeetCode doesn’t store data between each run-through of our code so we’ll have to try something different. We’ve interested in calculating one number of the sequence just once. I think we can throw away that array. Let’s look at the iterative solution.

var fib = function(N) {
    if (N < 2) {
        return N;
    }
    let a = 1;
    let b = 1;
    for (let i = 3; i <= N; ++i) {
        a = a + b;
        b = a - b;
    }
    return a;
};

If this looks a little different to other iterative versions you might have seen, it’s because I avoided the third temporary variable that we have to use in JavaScript to swap values (there are other methods as well but they’re too slow). I did some benchmarks and I found using arithmetic instead wasfaster than 100.00%.

#javascript

What is GEEK

Buddha Community

Write javascript code with high performance

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Giles  Goodwin

Giles Goodwin

1603857900

4 Ways You Can Get Rid of Dirty Side Effects for Cleaner Code in JavaScript

According to an analysis, a developer creates 70 bugs per 1000 lines of code on average. As a result, he spends 75% of his time on debugging. So sad!

Bugs are born in many ways. Creating side effects is one of them.

Some people say side effects are evil, some say they’re not.

I’m in the first group. Side effects should be considered evil. And we should aim for side effects free code.

Here are 4ways you can use to achieve the goal.

1. use strict;

Just add use strict; to the beginning of your files. This special string will turn your code validation on and prevent you from using variables without declaring them first.

#functional-programming #javascript-tips #clean-code #coding #javascript-development #javascript

Armando  Bruen

Armando Bruen

1593621572

Who Else Wants to Write Clean JavaScript Code?

Your college: “Who’s the author of this code?”

Expectation: “It’s me!” You answer proudly because that code is beautiful like a princess.

Reality: “Nah, it’s not me!” You lie because that code is ugly like a beast.

Now, if you want to make the expectation become the reality, keep reading.

1. Use meaningful Variable Names

Use meaningful names, which you know exactly what it is at first glance.

// Don't
let xyz = validate(‘amyjandrews’);

// Do
let isUsernameValid = validate(‘amyjandrews’);

It makes sense to name a collection type as plural. Thus, don’t forget the s:

// Don't
let number = [3, 5, 2, 1, 6];

// Do
let numbers = [3, 5, 2, 1, 6];

Functions do things. So, a function’s name should be a verb.

// Don't
function usernameValidation(username) {}

// Do
function validateUsername(username) {}

Start with is for boolean type:

let isValidName = validateName(‘amyjandrews’);

Don’t use constants directly because as time pass you will be like, “What the hell is this?” It’d better to name constants before using them:

// Don't
let area = 5 * 5 * 3.14;

// Do
const PI = 3.14;
let area = 5 * 5 * PI;

For callback functions, don’t be lazy to just name parameters as one character like h, j, d (maybe even you, the father of those name, don’t know what they mean). Long story short, if the parameter is a person, pass person; if it’s a book, pass book:

// Don't
let books = [‘Learn JavaScript’, ‘Coding for Beginners’, ‘CSS the Good Parts’];

books.forEach(function(b) {
  // …
});
// Do
let books = [‘Learn JavaScript’, ‘Coding for Beginners’, ‘CSS the Good Parts’];
books.filter(function(book) {
  // …
});

#coding #javascript-tips #programming #javascript #javascript-development

13 Useful JavaScript Developer Tools for Writing High-Quality Code

Today I’m going to show you 13 well-know and popular tools to write better and cleaner JavaScript code.

These are tools that I’m using right now on my JavaScript developer journey.

So if you want to improve the quality of your projects, this list is for you.

1. npm

NPM is a package manager for Nodejs with hundreds of thousands of packages, and you can use it for front-end development too.

The main purpose of using NPM is automating dependency and package management. If you use a library by importing it directly without using NPM, you will do it every time you want to update the library. It’s a heavy time-consuming as your project grows. Instead of spending time on invaluable tasks, install NPM once and it will take care of all of them for you.

2. JSFiddle

When I come up with a new idea for my projects, I’ll test it out on JSFiddle to see how everything goes. For a quick test before adding things to the real project, JSFiddle is the perfect solution.

More JavaScript online editors:

25 JavaScript Playgrounds For Testing New Ideas

For testing your new ideas or even develop an entire product.

medium.com

3. Chrome DevTools

I don’t need to talk much about this tool. With its help, you can inspect almost everything of your project so that you can debug and know what’s wrong on a certain page.

More about Chrome DevTools:

13 Super Useful Chrome DevTools Tips to Speed Up Your Developing Workflow

A great set of tools for web development.

medium.com

#javascript #javascript-tips #web-development #coding #programming