Logical Approach to Common Problems — Part 2

📄 Table of contents

➤ Misc

➤ Strings

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬

◉ 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

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.

◉ sum of (numbers) when you don’t know how many numbers are there in advance…rest operator.

const sum = (...args)=>{
return args.reduce((a, b) => a+b);
// args.length will return '4' here;
}
console.log(sum(2,3,4,6));
# 15

(…) Rest parameter syntax

function numbers(x,y, ...z){
console.log(x,y,z);
}
numbers(1,2,3,4,5,6);
# Output:
1
2
[3,4,5,6]

(…) Spread parameter syntax

function getSum(x, y, z){
console.log(x+y+z);
}
let arr = [10,20,30];
getSum(...arr);

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)

Logic:

  1. create an object literal
  2. attach methods to object literal
  3. update this.result in each function and return this

Getting key with the highest value from object

var obj = {a: 1, b: 2, undefined: 1};Object.keys(obj).reduce(function(a, b){
return obj[a] > obj[b] ? a : b
});

◉ find the most frequent item in an array

Write a JavaScript program to find the most frequent item of an array. Search should be case insensitive.input: [1, 'T', 'a', 'T', 2, 3, 'T', 3, 't', 2, 't', 9, 3];
output: t = 5

◉ Count the occurrence of each character in a string

source: https://stackoverflow.com/questions/19480916/count-number-of-occurrences-for-each-char-in-a-string

var str = "count number of each char in this string";var obj = {};// Misc vars
var ch, index, len, count;
for (index = 0, len = str.length; index < len; ++index) {
ch = str.charAt(index);
count = obj[ch];
console.log("count =>"+ count); // "count =>undefined"
obj[ch] = count ? count + 1 : 1;
}
for (ch in obj) {
console.log(ch + " ==>: " + obj[ch]);
}

Note: The charAt() method of the String class returns the char value at the specified index. The indexOf(int ch, int fromIndex) method of the String class returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

◉ reverse a “string” using inbuilt methods

function reverseString(str) {
return str.split("").reverse().join("");
}
reverseString("hello");

split() => split a string into an array of substrings, & returns a new array.

reverse()=> is ONLY applicable on Arrays ( & not String).

join() => join the elements of an array into a string:

◉ reverse an INTEGER using inbuilt methods

The first thing I’d do is to convert the number to a string by calling the inbuilt JavaScript .toString() in-built method.

let myNumber = 23;
let myChar = myNumber.toString().split('').reverse().join('');
console.log(myChar) // returns 32;
console.log(typeof(myChar)) // returns string

So we have successfully reversed the number but the output is still a string and not a number, meaning we cannot perform mathematical operations on our result. To change this back to a number, we would simply wrap this into the JavaScript parseInt() method.

const myNewNumber = parseInt(myChar);console.log(myNewNumber); // returns 32
console.log(typeof(myNewNumber)) // returns number

◉ 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(10)(2)(3)(4)()

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-c54578566ba0Add a method to Array object in Javascript

var arr = [2,3,4,5];arr.getSum = function() { 
var sum= 0;
for(var i=0; i< arr.length; i++){
sum = sum + arr[i];
};
console.log(sum);
}
arr.getSum();Attach a function to array in js?
let tempArray = [6, 2, 3, 4, 5];
let averageValues = tempArray.average();
console.log(averageValues); // should return average of tempArray

--

--

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