Skip to content

Instantly share code, notes, and snippets.

@kironroy
Created July 4, 2023 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kironroy/bab201e78dc957bda080c658d490e73a to your computer and use it in GitHub Desktop.
Save kironroy/bab201e78dc957bda080c658d490e73a to your computer and use it in GitHub Desktop.
Array practice
'use strict';
// Data
// forEach
const info1 = {
owner: 'Sita Troy',
movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
interestRate: 1.2, // %
pin: 1111,
};
const info2 = {
owner: 'Rita Roy',
movements: [5020, 3400, -150, -790, -3210, -1000, 8500, -30],
interestRate: 1.5,
pin: 2222,
};
const info3 = {
owner: 'Zelda Garfield Fitzgerald',
movements: [200, -200, 340, -300, -20, 50, 400, -460],
interestRate: 0.7,
pin: 3333,
};
const info4 = {
owner: 'Rusty Shackleton',
movements: [630, 1000, 700, 50, 90],
interestRate: 1,
pin: 4444,
};
const info = [info1, info2, info3, info4];
// 1. sum up money movements
const fakeBankDepositSum = info
.flatMap(acc => acc.movements)
.filter(mov => mov > 0)
.reduce((sum, cur) => sum + cur, 0);
console.log(fakeBankDepositSum);
// 2. count how many deposits => 1000
const fakeNumDeposits1000 = info
.flatMap(acc => acc.movements)
.reduce((count, cur) => (cur >= 1000 ? ++count : count), 0);
// .filter(mov => mov >= 1000).length;
console.log(fakeNumDeposits1000);
// 3. advanced reduce method, create an object
// deposits and withdrawals
const { deposits, withdrawals } = info
.flatMap(acc => acc.movements)
.reduce(
(sums, cur) => {
sums[cur > 0 ? 'deposits' : 'withdrawals'] += cur;
return sums;
},
{ deposits: 0, withdrawals: 0 }
);
console.log(deposits, withdrawals);
// 4. convert string to Title Case: This is a Nice Title
const convertTitleCase = function (title) {
const capitalize = str => str[0].toUpperCase() + str.slice(1);
const doNotConvert = [
'a',
'an',
'and',
'the',
'but',
'or',
'on',
'in',
'with',
'is',
];
const titleCase = title
.toLowerCase()
.split(' ')
.map(word => (doNotConvert.includes(word) ? word : capitalize(word)))
.join(' ');
return capitalize(titleCase);
};
console.log(convertTitleCase('this is a nice title'));
console.log(convertTitleCase('this is a LONG title but n ot too long'));
console.log(convertTitleCase('and here is another title with an EXAMPLE'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment