Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active December 1, 2023 03:22
Show Gist options
  • Save abhisekp/79d7371be042133998988e9c9759ea1a to your computer and use it in GitHub Desktop.
Save abhisekp/79d7371be042133998988e9c9759ea1a to your computer and use it in GitHub Desktop.
Understanding Functional Programming

Imperative vs Declarative

Imperative as opposed to Declarative is a style of writing in which you tell the computer how to do the things step by step which is not easy to reason about from a logic perspective.

In Declarative style you write code which gives the overall meaning of the code i.e. you tell the computer what to do.

e.g.
Declarative
Bring me a cup of tea

Imperative

  1. Go to kitchen
  2. Prepare the tea
  3. Put Water + Milk
  4. Boil
  5. Put tea leaves
  6. Serve tea

Well, imperative is messy ;)

Lets find the sum of numbers in an array

var numList = [1, 3, 4, 5, 0, 8]  

var total = numList.reduce(function (sum, currNum) {  
  // add the sum and currNum which will get assigned to sum  
  return sum + currNum  
}, 0) // initialize sum = 0  

basically, reduce reduces an array to a single value
the value can be any JS datatype
in this case, I used reduce to reduce the numList array to a single number
and that function receives at least 2 parameters
a result variable
and the current element variable
in this case sum is the result variable and
currNum is the current element of the array variable

Internally, reduce method called that function with 2 arguments

1st argument is the result variable whc stores the result of the function which gets returned from the reduce method
and 2nd argument is the current element of the array.

the initializing value gets assigned to the result variable initially
and then i can simply work on the result variable
otherwise, if i don't pass the initializing value to reduce method, then the result takes the 1st element of the array as its initial value

now the question arises, what is the use of initializing value?
well, what if the array is simply empty and we try to use reduce on an empty array

clearly, the 1st element of the array is undefined and if we try to do something with the result variable, then compiler will throw an error

also there are other uses of initializing value whc one mite need

basically, mathematical guys and gals call it as a fold function
which folds an array to a single value ... imagine a folding card .... ;)

well, there are two ways one can fold ... obviously the usual case is fold from left to right. So it's called just reduce
But there maybe cases of folding from right to left.. so there is also a Array#reduceRight method :D
http://devdocs.io#q=js+Array+reduceRight

reduce and reduceRight methods were not in JS when it was originally created in 1995.
They were introduced later bcoz well, people demanded such a function.... and many other functions are being added every year...

last year they added a very useful Array#find function whc u can use for Profile Lookup challenge :D

Write a split function which takes a string and splits it into two parts.

splitIn2(String) => [String, String]

It takes a string value and splits it into two equal halves and stores the string in an array. If odd number of characters are in the string, the initial half must contain one character more than the later half.

Test Cases:-

splitIn2('') => ['', '']
splitIn2('I') => ['I', '']
splitIn2('apple') => ['app', 'le']
splitIn2('pen') => ['pe', 'n']
splitIn2('game') => ['ga', 'me']
splitIn2('I am happy') => ['I am ', 'happy']

Check out https://jsbin.com/visucu/1/edit?js,output

Imperative Solution

// INCORRECT SOLUTION

var splittedIn2 = []

var string1 = '' // store first half
var string2 = '' // store later half
var current = ''

for (var i = 0; i < string.length; ++i) {
	if (i === Math.ceil(string.length / 2)) {
		string1 = current
		current = ''
	}
	
	current += string[i]
}

string2 = current

splittedIn2.push(string1, string2)
console.log(splittedIn2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment