js-higher-order-functions
https://deevyne-dev.hashnode.dev/a-deep-dive-into-javascripts-higher-order-functions-map-foreach-filter-and-reduce
// π normal loop
const num = [ 10 , 20 , 30 ] ;
const num5 : number [ ] = [ ] ;
for ( let i = 0 ; i < num . length ; i ++ ) {
num5 . push ( num [ i ] * 5 ) ;
}
// π₯ map()
const num2 = [ 10 , 20 , 30 ] ;
const num6 = num2 . map ( ( x ) => x * 5 ) ;
// β
μ λ°°μ΄ μμ± X. κΈ°μ‘΄ λ°°μ΄μ modify ν¨.
const users = [
{ id : 1 , name : 'Alice' } ,
{ id : 2 , name : 'Bob' } ,
{ id : 3 , name : 'Charlie' } ,
] ;
// Using forEach to log personalized greetings
users . forEach ( ( user ) => {
console . log ( `Hello, ${ user . name } ! Your user ID is ${ user . id } .` ) ;
} ) ;
//Hello, Alice! Your user ID is 1.
//Hello, Bob! Your user ID is 2.
//Hello, Charlie! Your user ID is 3.
type BankAccount = {
accountType : string ;
balance : number ;
name : string ;
} ;
const bankAccounts = [
{ accountType : 'savings' , balance : 5000 , name : 'John James' } ,
{ accountType : 'current' , balance : 10000 , name : 'Micheal Obi' } ,
{ accountType : 'savings' , balance : 7500 , name : 'Bola Ade' } ,
{ accountType : 'current' , balance : 12000 , name : 'Emmanuel John' } ,
{ accountType : 'savings' , balance : 9000 , name : 'Faithfulness Alamu' } ,
] ;
// π Using for loop
const savingsAccountsForLoop : BankAccount [ ] = [ ] ;
for ( let i = 0 ; i < bankAccounts . length ; i ++ ) {
if ( bankAccounts [ i ] . accountType === 'savings' ) {
savingsAccountsForLoop . push ( bankAccounts [ i ] ) ;
}
}
console . log ( savingsAccountsForLoop ) ;
/*
[
{ accountType: 'savings', balance: 5000, name: 'John James' },
{ accountType: 'savings', balance: 7500, name: 'Bola Ade' },
{ accountType: 'savings', balance: 9000, name: 'Faithfulness Alamu'},
]
*/
// π₯ Using filter
const savingsAccountsFilter = bankAccounts . filter (
( account ) => account . accountType === 'savings'
) ;
console . log ( savingsAccountsFilter ) ;
/*
[
{ accountType: 'savings', balance: 5000, name: 'John James' },
{ accountType: 'savings', balance: 7500, name: 'Bola Ade' },
{ accountType: 'savings', balance: 9000, name: 'Faithfulness Alamu'},
]
*/
// λ°°μ΄μ μμλ€μ μΆμ νλ©΄μ νλλ‘ μΆμ½ (μλ₯Όλ€μ΄ μμλ€μ λͺ¨λ ν©νλΌ)
// π normal for loop:
const numbers = [ 10 , 29 , 11 , 43 , 37 ] ;
let total = 0 ;
for ( let i = 0 ; i < numbers . length ; i ++ ) {
total = total + numbers [ i ] ;
}
console . log ( total ) ; // prints 130
// π₯ reduce
const numbers2 = [ 10 , 29 , 11 , 43 , 37 ] ;
const total2 = numbers . reduce ( ( acc , curr ) => {
return acc + curr ;
} , 0 ) ;
console . log ( total2 ) ;
//Prints 130
//####### Note ###########
//the zero is the initial value
//if it changes to 20 we will have 150 as our answer meaning
// that we will add 20 + 10 + +29 + 11 + 43 +37