Logical Approach to Common Problems — Part 2

📄 Table of contents

➤ Misc

  • sum of numbers using ‘for’ loop vs ‘recursion’
  • increment the counter on each load
  • Chaining in JS (as in jQuery)
  • get all possible sub-strings of a given string
  • Find a value in an array of objects in JS
  • sum of no.s using Recursion vs traditional approach

The first approach utilizes a for-loop which again is not entirely functional so it is replaced with the recursive function addRecursively(). Like the for-loop which operates on an array, the recursive function takes in an array of numbers and begins adding the first to the subsequent one. It also establishes a base case of returning 0 if all the numbers have been added, which is checked by assessing if the array of numbers length is 0.

a programming paradigm is how code is implemented and executed,, and in the case of OOP, it is via the use of classes and objects.

the functional programming paradigm approach is the ability for functions to be versatile, and JavaScript accomplishes that by making functions first-class members. This means that functions can be used as data, and passed around within a program, such as when stored within variables, data structures like array or objects, passed as arguments to other functions, or returned from function calls. It is one that is gaining popularity, as it is seen extensively within React and other libraries.

approach is the ability for functions to be versatile, and JavaScript accomplishes that by making functions first-class members. This means that functions can be used as data, and passed around within a program, such as when stored within variables, data structures like array or objects, passed as arguments to other functions, or returned from function calls.

In conclusion, these key concepts, the immutability of data, pure functions, higher-order functions, recursion, and composition, create the foundation for functional programming.

pure functions which state that functions should compute a return value based solely on the arguments it receives and should not cause side effects.

// functional approach
const log = message => console.log(message);

Taking a look back at the first example, the log() function is not a pure function. It causes the side effect of logging to the console while returning a value, undefined, that is not computed by its “message” argument. And because pure functions return values are based on their arguments, they are predictable and easy to implement tests for.

const increaseByOne = num => num + 1;const num = 1
const newNum = increaseByOne(num) // => 2
console.log(num) // => 1

Functions that accept functions as arguments or return functions are known as higher-order functions and are another key concept of functional programming.

const sum = (a,b) => a + b
const average = (fn, ...nums) => nums.reduce(fn) / nums.length;
const numsAvg = average(sum, 1, 2, 3) // => 2

In this example, two pure functions are defined sum() and average(), which take in some arguments, and do not mutate the arguments but compute a return value based on them. The average() function is a higher-order function that takes in a function, sum(), as an argument and computes a return value by passing it into another higher-order function, reduce(), as the reducer. Next, an arbitrary amount of numbers are passed to the rest parameter and aggregated into a “nums” array. Finally, the array of numbers are reduced and divided by the total amount of numbers passed into the average() function to return the average.

Q. increment the counter on each page load

this can be solved using the concept of HTML5 localStorage.

This is a very simple example showing a counter that will increment by one every time you reload a a page. As the counter is saved in your own browser and it is associated with the site you visited, this number will be independent of what other people see, or what you’ll see if you visit the same page using a different device or even a different browser on the same device.

for more read @ https://code-maven.com/on-load-counter-with-javascript-and-local-storage

◉ Chaining in JS (as in jQuery)

◉ Get all possible substrings of a given string

all possible substrings of a given string

◉ Find a value in an array of objects in JS

◉ sum of no.s using Recursion

var array_sum = function(arr) {
if (arr.length === 1) {
return arr[0];
}
return arr.pop() + array_sum(arr);

};
console.log(array_sum([1,2,3,4,5,6])); # 21
Sum using Recursion

Don’t Use If-Else and Switch in JavaScript, Use Object Literals

There are times when you might need to do some more complex logic inside your conditions. To achieve this, you can pass a function as the value to your object keys and execute the response:

We are selecting the calculation we want to do and executing the response, passing the two numbers. You can use optional chaining (the ?. in the last line of code) to only execute the response if it is defined. Otherwise, fall through to the default return string.

for more @https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0

◉ “this” keyword in js

The JavaScript this keyword refers to the object it belongs to.

It has different values depending on where it is used:

  • In a method, this refers to the owner object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

Note that I’m calling the walk method in this case, which is inside of the object.

  • But when we apply some slight changes, different results were obtained. We added another const named as newWalk which gives reference to the walk method in the user object. For simplicity, we can say newWalk is a function that calls the walk method in the user object.
  • This time we if we call the newWalk method by giving a reference to another method (walk) then most likely you will obtain undefined on the console. (Note that in my case we obtained a window object as I’m running this code in a React Project with Strict Mode disabled).

4. Binding this

In JavaScript, we can use the bind method to fix the problem that we discussed in the above section, as we aren’t able to access the user object in both cases. Using the bind method you can simply bind an object to a function.

For example,

  • In the previous example where we aren’t able to access the user object using the this keyword, using the bind method you can solve all of that issues quickly.
  • We just have to pass .bind(an object that you want to give reference) to your function & we longer have to work with an undefined or window object, because the this keyword now always give reference the user object

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store