Blog Day 23: A new type of Combinations, Array Built-in Higher Order Function

Inseo Park·2021년 7월 30일
0

Path to Data Scientist

목록 보기
22/58
post-thumbnail

TIL (Today I Learned)

A new type of Combinations

A combination can be a mixture of different smaller individual events.

Ex. A diner introduced a menu

  • Sandwich
  • Drink
  • Side

Assume you go there everyday, how long will it take for you to try out every possible item in the menu. To solve this you need to know what is included in their lunch deal. Each menu consists of:

Sandwich (Panini, Vege Wrap, Feliz) + Side (Fries & Onion Rings) + Drinks (Water or Cola)

** Think about the different parts of the menu as seperate positions [sandwich, side, drink]

If we start by choosing sandwich first, we have 3 options.
For each of them we can pick one of 2 sides. (Fries or Rings) & a drink (Cola or Water)
Any combinations of a sandwich & side we have 2 ways of completing a menu.

	3 * 2 * 2 = 12 different lunch menus
    

Online Marketing Example:
You need to try out several versions of an online ad before you decide which one is the best. Imagine you are using Facebook. The ad consists of 4 parts:

	Facebookad = {Post Description: 3, Thumbnail: 5, Heading: 3, Button: 2};
    ** This is important because this shows how many different possibilities there are.
    

Determine the appropriate amount of time it would take for such a task to be completed.

When the components are simply too many, we can remove several of the options to tremendously decreas the workload.

Calculating the total number of combinations is by multiplying the number of options available for each individual event

	a * b * c
    

Array Built-in Higher-Order Function

Achievement Goals

  1. Understand Array Built-tin Higher-Order Function
  2. From the knowledge of filter, understand and self-learn the following:
    forEach, find, filter, map, reduce, sort, some, every;
  3. Understand abstraction
  4. Understand the advantage higher-order function has due to abstraction.
  5. Be able to write a program using higher-order function.

Built-in Higher-Order Function

There are many built-in higher-order function in Javascript.
Array related methods are some of the main ones.

filter (method)
A method for array, filter is used to filter out a value in an array that matches an argument.

  • In an array with number type values, filter out even numbers or filter out values less than 18.

  • In an array with string type values, filter out array.length <= 10 or filter out 'korea'.

    	let arr = [1, 2, 3, 4]'
      	let output = arr.filter(evenNumbers)
     	console.log(output); // --> [2, 4]
      
      	arr = ['hello', 'code', 'states', 'happy', 'hacking'];
    	output = arr.filter(length is less than or equal 5)
    	console.log(output); // ->> ['hello', 'code', 'happy'];

The argument that is filtered out her is the method's parameter and it is a function.
filter() method is a higher-order function because it receives a function as a parameter.

	 let arr = [1, 2, 3];
         arr.filter = function (arr, func) {
         const newArr = [];
         for (let i = 0; i < arr.length; i++) {
         // The callback function that is the filter's parameter retrieves all values in arr
         // only if the callback fucntion is ture, newArr.push works
         
         if (func(arr[i]) === true) {
         newArr.push(this[i]);
         }
    }
   return newArr;
   // only return values that match the argument: callback function is true.
   

The callback function is a parameter to the filter method. Then the callback function sues the retrieved array's values to return result.

	function expression
        const isEven = function(num) {
        return num % 2 === 0;
        };
        
        let arr = [1, 2, 3, 4];
        let output = arr.filter(isEven);
        console.log(output); // --> [2, 4]
        
        const isLteFive = function (str) {
        // Lte = less than equal
        return str.length <= 5;
        };
        
        arr = ['hello', 'code', 'states', 'happy', 'hacking'];
        // output = arr.filter (length lte 5)
        let output = arr.filter(isLteFive);
        console.log(output); // --> ['hello', 'code', 'happy']
        

Understanding higher-order function: map

map returns value after processing all values by the same specific action.
The specific action is made by the programmer & has to be a function.
It does not fix the original array, which means it is immutable.
Depending on the action, the return value changes.

	let arr = [1, 2, 3];
    let result =
    arr.map(function(ele) {
    return ele * 2
    });
    result;
    
  1. Value = all the value of the array

  2. Argument:

  3. Return Value

    Problem:
    In the 27 chapters of a book, all informations about it is stored in an array. Make an array only consisting the subtitles of all chapters.

  4. Value = Information about chapters 1~27

  5. Argument = Find the subtitle of one chapter

  6. Return value = Array with subtitles of chapter 1~27

    ** map is used to initiate mapping to another data

    	const cartoons = [
       	  { 
             id: 1,
             bookType: 'cartoon',
             title: '식객',
             subtitle: '어머니의 쌀',
             createdAt: '2003-09-09',
             genre: '요리',
             artist: '허영만',
             averageScore: 9.66,
             },
             {
             id: 2,
             //...
             }.
             //...
         ];
         
         	const findSubtitle = function (cartoon) {
           return cartoon.subtitle;
           }; // a function that returns a subtitle of a chapter
           
           const subtitles = cartoons.map(findSubtitle);
           

Understand higher-order function: filter

filter() returns an array after filterying out the values
The argument is a function
It is immutable.

let arr = [1, 2, 3]
let result = arr.filter(function(elc) {
	return elc % 2 === 0
    });
    result;
    [1, 3];
    

a. When each values of a array
b. is true
c. filter it out

Problem
Return only chapters that are published in 2003.

Pseudocode
a. Values: Information about chapters 1~27
b. Argument: the chapter published in 2003
c. return: chapters published in 2003

	// filter method is used to initiate filtering
    const cartoons = [
    {
    id: 1, 
    bookType: 'cartoon',
    title: '식객',
    subtitle: '어머니의 쌀',
    createdAt: '2003-09-09',
    genre: '요리',
    artist: '허영만',
    averageScore: 9.66,
    },
     {
     id: 2,
     //...
     }.
     //...
 ];
 
 const isCreatedAt2003 = function (cartoon) {
   const fullYear = new Date(cartoon.createdAt).getFullyear()
   return fullYear === 2003;
   };
   const filtered(cartoon) = cartoons.filter(isCreatedAt2003);
   

Understand reduce higher-order function

reduce makes a single value from an array of values.
First, you can set a initial value, if not the first value of the array will be the initial value.
The initial becomes the accumulator and the current value is given to sum it up and stores the result into the return value.

let arr = [1, 2, 3];
let result = arr.reduce(function (acc, cur, idx) {
acc + cur;
return acc;
});
result
// --> 6

** when initial is given

let arr = [1, 2, 3];
let result = arr.reduce (
function (acc, cur, idx) {
acc + cur;
return acc;
} , 1);
result;
// --> 7

a. .reduce(sum, 1)
b. .reduce(connectText, 'b')
c. .reduce(theBiggest)
d. .reduce(theSmallest)
e. .reduce(classByType, {})

Problem
Reduce all teh averageScore and return a average of all scores.

Pseudocode
1. Value: Information of chapters 1~27
2. Argument: add all the scores to the accumulated score
3. Type: number type
4. Return Value: find the answer for score divide length of data

const cartoons = [
{
id: 1, 
bookType: 'cartoon',
title: '식객',
subtitle: '어머니의 쌀',
createdAt: '2003-09-09',
genre: '요리',
artist: '허영만',
averageScore: 9.66,
},
 {
 id: 2,
 //...
 }.
 //...

];

const scoreReducer = function (sum, cartoon) {
return sum + cartoon.averageScore;
}; // Add all the scores to the accumulated score.

let initiaValue = 0;
const cartoonsAvgScore = cartoons.reduce(scoreReducer, initialValue) / cartoons.length;

Array into a String

Pseudocode
1. Value = user information
2. Argument = concat a user's name with a ,(comma)
3. Type = String
4. Return Value = All user's name seperated by a comma.

function joinName(resultStr, user) {
    resultStr = resultStr + user.name + ',';
    return resultStr;
    }
    
    let users = [
    {name: 'Tim', age: 40},
    {name: 'Satya', age: 30},
    {name: 'Sundar', age: 50}
    ];
    users.reduce(joinName, '');
    

Array into an Object

Pseudocode
1. Value = User Information
2. Argument = Take the user's name a first letter as a key and user information as the value
3. Type = Addressbook Object
4. Return Value = An addressbook that is divided by alphabet letters

function makeAddressBook(addressBook, user) {
  let firstLetter = user.name[0];
  if (firstLetter in addressBook) {
    addressBook[firstLetter].push(user);
    } else {
    addressBook[firstLetter] = [];
    addressBook[firstLetter].push(user);
    }
    return addressBook;
    }
    let users = [
    {name: 'Tim', age: 40},
    {name: 'Satya', age: 30},
    {name: 'Sundar', age: 50}
    ];
    
    users.reduce(makeAddressBook, {});
    

2. 3 Things to be Thankful for

  1. Thank God that I finished my roles today and having a good feast with my colleagues.
  2. Thankful for Iris being safe and having a good day.
  3. Thankful for having a great day.

3. Ideas and things to think about

  1. Always remember people are important but God is more, just thank God.
profile
my journey to become a data scientist.

0개의 댓글