Skip to content

Instantly share code, notes, and snippets.

@LGitHub-sprout
Last active June 5, 2023 20:13
Show Gist options
  • Save LGitHub-sprout/2809ed472f83300ee3ed271353b66936 to your computer and use it in GitHub Desktop.
Save LGitHub-sprout/2809ed472f83300ee3ed271353b66936 to your computer and use it in GitHub Desktop.
filter, concat, recursion, tally, keyed object, lookup table, piping/pipeline, destructuring
// https://bholmes.dev/blog/another-way-to-understand-array-reduce/
// Return all the music descriptions containing 90 words or more using forEach.
// Then do the same thing w the reduce() method.
const musicData = [
{
name: 'Radiohead',
albums: [
{
title: 'The King of Limbs',
songs: [
{ title: 'Bloom', lengthInMins: 5 },
{ title: 'Morning Mr Magpie', lengthInMins: 4.5 },
{ title: 'Little by Little', lengthInMins: 4.5 },
{ title: 'Feral', lengthInMins: 3 },
{ title: 'Lotus Flower', lengthInMins: 5 },
{ title: 'Codex', lengthInMins: 4.8 },
{ title: 'Give Up the Ghost', lengthInMins: 4.8 },
{ title: 'Separator', lengthInMins: 5.4 },
],
description:
"The King of Limbs is the eighth studio album by English rock band Radiohead, produced by Nigel Godrich. It was self-released on 18 February 2011 as a download in MP3 and WAV formats, followed by physical CD and 12 inch vinyl releases on 28 March, a wider digital release via AWAL, and a special newspaper edition on 9 May 2011. The physical editions were released through the band's Ticker Tape imprint on XL in the United Kingdom, TBD in the United States, and Hostess Entertainment in Japan.",
},
{
title: 'OK Computer',
songs: [
{ title: 'Airbag', lengthInMins: 4.7 },
{ title: 'Paranoid Android', lengthInMins: 6.4 },
{ title: 'Subterranean Homesick Alien', lengthInMins: 6.5 },
{ title: 'Exit Music (For a Film)', lengthInMins: 6.5 },
{ title: 'Let Down', lengthInMins: 5 },
{ title: 'Karma Police', lengthInMins: 4.4 },
{ title: 'Fitter Happier', lengthInMins: 2 },
{ title: 'Electioneering', lengthInMins: 3.8 },
{ title: 'Climbing Up the Walls', lengthInMins: 4.7 },
{ title: 'No Surprises', lengthInMins: 3.8 },
{ title: 'Lucky', lengthInMins: 4.4 },
{ title: 'The Tourist', lengthInMins: 5.4 },
],
description:
"OK Computer is the third studio album by the English alternative rock band Radiohead, released on 16 June 1997 on Parlophone in the United Kingdom and 1 July 1997 by Capitol Records in the United States. It marks a deliberate attempt by the band to move away from the introspective guitar-oriented sound of their previous album The Bends. Its layered sound and wide range of influences set it apart from many of the Britpop and alternative rock bands popular at the time and laid the groundwork for Radiohead's later, more experimental work.",
},
],
},
{
name: 'Portishead',
albums: [
{
title: 'Dummy',
songs: [
{ title: 'Mysterons', lengthInMins: 5 },
{ title: 'Sour Times', lengthInMins: 4 },
{ title: 'Strangers', lengthInMins: 4 },
{ title: 'It Could Be Sweet', lengthInMins: 4 },
{ title: 'Wandering Star', lengthInMins: 4.8 },
{ title: "It's a Fire", lengthInMins: 3.8 },
{ title: 'Numb', lengthInMins: 3.8 },
{ title: 'Roads', lengthInMins: 5 },
{ title: 'Pedestal', lengthInMins: 3.6 },
{ title: 'Biscuit', lengthInMins: 5 },
{ title: 'Glory Box', lengthInMins: 5 },
],
description:
'Dummy is the debut album of the Bristol-based group Portishead. Released in August 22, 1994 on Go! Discs, the album earned critical acclaim, winning the 1995 Mercury Music Prize. It is often credited with popularizing the trip-hop genre and is frequently cited in lists of the best albums of the 1990s. Although it achieved modest chart success overseas, it peaked at #2 on the UK Album Chart and saw two of its three singles reach #13. The album was certified gold in 1997 and has sold two million copies in Europe. As of September 2011, the album was certified double-platinum in the United Kingdom and has sold as of September 2011 825,000 copies.',
},
{
title: 'Third',
songs: [
{ title: 'Silence', lengthInMins: 5 },
{ title: 'Hunter', lengthInMins: 4 },
{ title: 'Nylon Smile', lengthInMins: 3 },
{ title: 'The Rip', lengthInMins: 4.5 },
{ title: 'Plastic', lengthInMins: 3.5 },
{ title: 'We Carry On', lengthInMins: 6.5 },
{ title: 'Deep Water', lengthInMins: 1.5 },
{ title: 'Machine Gun', lengthInMins: 4.7 },
{ title: 'Small', lengthInMins: 6.7 },
{ title: 'Magic Doors', lengthInMins: 3.5 },
{ title: 'Threads', lengthInMins: 5.7 },
],
description:
"Third is the third studio album by English musical group Portishead, released on 27 April 2008, on Island Records in the United Kingdom, two days after on Mercury Records in the United States, and on 30 April 2008 on Universal Music Japan in Japan. It is their first release in 10 years, and their first studio album in eleven years. Third entered the UK Album Chart at #2, and became the band's first-ever American Top 10 album on the Billboard 200, reaching #7 in its entry week.",
},
],
},
];
// Return the longest album in nested array using reduce()
// Tried backticks to return album title but didn't work. Deleted it.
const longestAlbum = function (arr) {
return getMusicData = arr.reduce((longest, currVal) => {
currVal.albums.map((album) => {
let albumTotal = 0;
album.songs.forEach((song) => {
albumTotal += song.lengthInMins;
});
longest = longest > albumTotal ? longest : albumTotal;
});
// return typeof longest; // number so not sure why need to wrap in Number()
return Number(longest.toFixed(2));
}, 0);
};
console.log('longestAlbum', longestAlbum(musicData)); // 57.6
// Return an array of song length totals in one function using loops.
// Then get the longest album of the group.
const getAlbumLengths = function (arr) {
let totalsArr = [];
for (let i = 0; i < arr.length; i++) {
for (album of arr[i].albums) {
let total = Number(0);
for (song of album.songs) {
total += song.lengthInMins;
}
totalsArr.push(total.toFixed(2));
}
}
// totalsArr.push('100'); // test longestAlbum func: ['37.00', '57.60', '48.00', '48.60', '100']
return totalsArr;
// return Math.max(...totalsArr).toFixed(2);
};
console.log(getAlbumLengths(musicData)); // ['37.00', '57.60', '48.00', '48.60']
// getAlbumLengths(musicData).forEach(e => console.log(typeof e)); // string
const longestAlbum = Math.max(...getAlbumLengths(musicData));
console.log(longestAlbum); // 57.6 number
// Return the album from the musicData array w longest number of minutes using loops.
// Then do same thing using reduce()
const longestAlbum = function (arr) {
let longest = 0;
let albumInfo = '';
const getMusicData = arr.forEach((band) => {
band.albums.forEach((album) => {
let albumTotal = 0;
album.songs.forEach((song) => {
albumTotal += song.lengthInMins;
});
longest = longest > albumTotal ? longest : albumTotal;
});
});
return `The longest album is ${longest.toFixed(2)} minutes.`;
};
console.log(longestAlbum(musicData)); // The longest album is 57.60 minutes.
// https://bholmes.dev/blog/another-way-to-understand-array-reduce/
const songs = [
['Rap Snitches Knishes', 'Beef Rap', 'Gumbo'],
['Accordion', 'Meat Grinder', 'Figaro'],
['Fazers', 'Anti-Matter', 'Krazy World']
];
// Using only loop(s), return ONE ARRAY with all the names of the songs from 'songs' nested array above.
// Then make the song titles all caps.
// Then redo it using reduce() method including all caps.
const getSongs = () => {
let ucSongs = []; // like accumulator in reduce()?
// return 'poop' // works outside loop
songs.forEach((songGroup) => {
// return 'poop' + songGroup; // forEach return value is 'undefined' aka doesn't return anything
// console.log(songGroup)
// Use ucSongs array accumulator
// songGroup.forEach(songTitle => ucSongs.push(songTitle)); // works
// for (songTitle of songGroup) return songTitle; // nope
for (songTitle of songGroup) {
// return 'poop' + songTitle; // doesn't return anything
// console.log(songTitle); // ea song title
ucSongs.push(songTitle) // also works
}
});
return ucSongs; // one array of all song titles
};
console.log(getSongs()); // empty array or 'poop' w/out 'accumulator' variable
// reduce() with loop
const ucSongs = songs.reduce((acc, currentVal, item, arr) => {
// console.log(typeof acc, Array.isArray(acc)) // true
// console.log('acc', acc) // empty arr, then 'undefined'
// console.log('currentVal', currentVal, Array.isArray(currentVal)) // ea array, true
for (let song of currentVal) {
// console.log(song)
acc.push(song) // return acc.push(song) causes error
}
// currentVal.forEach((song) => {
// // console.log(acc) // [] after 1st iteration, 'undefined' thereafter
// // console.log(typeof song, song); // string
// // acc.pop(song) // cannot read properties of undefined
// acc.pop(song)
// });
return acc.map(song => song.toUpperCase()); // Remember to call func or console.log it!
}, []);
// console.log('ucSongs', ucSongs);
// reduce and concat() didn't do uppercase
const flattenArray = function (arr) {
return flatArr = arr.reduce((acc, currVal) => {
// return acc.concat(currVal); // only flattens 1 level deep
// recursive flattens all levels
return acc.concat(Array.isArray(currVal) ? flattenArray(currVal) : currVal);
}, []);
};
console.log(flattenArray(songs)); // ['Rap Snitches Knishes', 'Beef Rap', 'Gumbo', 'Accordion', 'Meat Grinder', 'Figaro', 'Fazers', 'Anti-Matter', 'Krazy World']
// reduce() with map()
const ucSongs2 = songs.reduce((acc, currentVal) => {
console.log('acc', acc); // initial value on 1st iteration, ie. empty array
return [...acc, ...currentVal].map(songTitle => songTitle.toUpperCase());
}, []);
// const ucSongs2 = songs.reduce((songs, albumSongs) => {
// return [...songs, ...albumSongs].map(song => song.toUpperCase());
// }, [])
console.log('ucSongs2', ucSongs2);
// https://bholmes.dev/blog/another-way-to-understand-array-reduce/
// Total length of all songs w nested looping with reduce() and forEach()
const sumAllSongs = function (arr) {
const songLen = arr.reduce((totalLen, currVal) => {
// console.table(currVal.albums);
currVal.albums.forEach(album => album.songs.map(song => totalLen += song.lengthInMins));
return totalLen;
}, 0);
return songLen.toFixed(2);
};
console.log(sumAllSongs(musicData)); // 191.20
// Total length of all songs w nested looping (without reduce)
musicData.forEach((band) => {
band.albums.forEach((song) => {
// console.log(song.title, song.songs)
});
});
let songLen = Number(0);
let totalLen;
const songTotals = musicData.forEach((album) => {
album.albums.forEach((song) => {
// use reduce here instead of another forEach
song.songs.forEach((length) => {
// += Addition Assignment
songLen += length.lengthInMins; // 191.19999999999996
// https://bobbyhadz.com/blog/javascript-round-number-to-two-decimal-places
totalLen = +songLen.toFixed(2); // 191.2
// totalLen = Number(songLen.toFixed(2)); // 191.2 Same as unary
// totalLen = parseFloat(songLen.toFixed(2)); // 191.2 drops trailing zero
});
});
});
// console.log('totalLen', totalLen, 'songLen', songLen); // totalLen 191.2 songLen 191.19999999999996
// Write a function that returns the musicData array descriptions that are longer than 90 words.
// Uses loops and filter() broken into (I think) functional programming parts.
const getAlbumDescriptions = function (arr) {
const descriptions = [];
for (let i = 0; i < arr.length; i++) {
arr[i].albums.forEach(album => descriptions.push(album.description.split(' ')));
};
return descriptions;
};
// console.log(getAlbumDescriptions(musicData)); // [Array(87), Array(92), Array(113), Array(87)]
const longerthan90 = function (arr) {
const longest = arr.filter((desc) => {
return desc.length > 90;
});
return longest; // 2 arrays
return longest.join(' '); // 2 strings
};
// console.log(longerthan90(getAlbumDescriptions(musicData))); //  [Array(92), Array(113)]
// Now using reduce() and map()
const longerThan90 = function (arr) {
return descriptions = arr.reduce((longest, currVal) => {
currVal.albums.map(album => {
let desc = album.description.split(' '); // 4 lengths of ea array of descriptions
if (desc.length > 90) longest.push(desc); // .join(' ')); // use joing to return strings
});
return longest;
}, []); // maybe try returning strings also?
};
console.log(longerThan90(musicData)); // ) [Array(92), Array(113)]
// https://dev.to/babak/why-you-should-use-reduce-instead-of-loops----part-i-5dfa
// Reducing w/out using reduce() method.
// Write a function that returns the length of the longest word in a string.
const longString = 'It\'s supercalifragilisticexpialidocious. Even though the sound of it is something quite atrocious.';
const getLongestWord = (str) => {
const words = str.split(' ');
let longestWord = 0;
for (const word of words) {
longestWord = Math.max(longestWord, word.length)
}
return longestWord;
};
// console.log(getLongestWord(longString)); // 35
// Custom reduce() with callback
function lestersReduce(
initialValue, // passes initialValue as arg but can pass 'null' as param (see below)
reducer, // reducer is callback (sumArr())
data,
) {
let acc = initialValue;
let count = 0;
for ( const item of data ) {
acc = reducer( acc, item, count++ );
}
// acc is the returned value from reducer() - sumArr() in this case.
return acc;
};
// callback
const sumArr = (acc, currNum) => {
let total = 0;
return total = acc + currNum;
};
// What happens if I don't pass an initial value?
const totalArrNums = (arr) => lestersReduce(
// Breaks w/out initial value unless passing null.
// 0,
null, // can use null for initialValue as param to bypass
sumArr,
arr,
);
console.log('Passing null', totalArrNums(data)); // 21
const getLongest = (longestLength, word) => {
return Math.max(longestLength, word.length);
};
const longestWordLength = str => lestersReduce(
0,
getLongest,
str.split(' '), // str.split(/\W+/g) author's code
);
console.log('longestWordLength ', longestWordLength(longString)); // 35
// https://medium.com/swlh/ways-to-use-the-reduce-method-in-javascript-f3d0f309c9e0
// Reverse a string using reduce
const lestersReverse = function (arr) {
return reverse = arr.split('').reduce((acc, currVal) => {
// adds currVal BEFORE ea add'l currVal
return currVal += acc; // returns: C .. oC .. roC .. rroC .. erroC .. cerroC .. tcerroC -> DUH
return acc += currVal; // returns correctly: 'Correct'
}, '');
// return reverse;
};
console.log(lestersReverse(data4)); // 'tcerroC'
// https://www.freecodecamp.org/news/reduce-f47a7da511a9/
const array1 = [1, 2, 3, 4];
// let initialValue = 100;
// const sumArr = array1.reduce(
// // (accumulator, currentVal) => accumulator + currentVal) // ES6 - no curly braces
// (accumulator, currentVal, currentIndex, array) => {
// // console.log(currentIndex, array) // yes, access to these
// return (initialValue += currentVal) / 2; // modify total accumulator (55)
// return accumulator + currentVal; // need return if using curly braces
// },
// // 0, // initial value param as number
// initialValue / 2, // divide initialValue THEN add total accumulator (60)
// );
// console.log('sumArr', sumArr, 'initialValue', initialValue);
// Flattening an array of arrays w reduce method
// https://www.freecodecamp.org/news/reduce-f47a7da511a9/
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatten = function (arr) {
return flat = arr.reduce((acc, currVal, index, origArr) => {
return acc.concat(currVal);
}, []);
};
console.log(flatten(data)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Another flatten — recursive this time
// https://medium.com/swlh/ways-to-use-the-reduce-method-in-javascript-f3d0f309c9e0
const data5 = [2, 1, [3, 10, [12, [12, [12, [12, [12, [12]]]]]]]];
const flatten = function (arr) {
return flatArr = arr.reduce((acc, currVal, index, origArr) => {
return acc.concat(Array.isArray(currVal) ? flatten(currVal) : currVal);
// return acc.concat(currVal);
return acc;
}, []);
};
console.log(flatten(data5)); // [2, 1, 3, 10, 12, 12, 12, 12, 12, 12]
// https://www.freecodecamp.org/news/reduce-f47a7da511a9/
// Creating a tally using reduce() method (using a loop is in looping.js gist).
const tally = function (arr) {
const result = arr.reduce((acc, currVal, index, origArr) => {
// console.log('currVal', currVal); // property values, e.g., 'banana', 'cherry' etc
// if the object acc does NOT contain key w current fruit
acc[currVal] = !acc[currVal] || 0 ? acc[currVal] = 1 : acc[currVal] += 1;
// if (!acc[currVal]) {
// // create key/value {banana: 1, cherry: 1, ...}
// acc[currVal] = 1; // happens 5 times, once for ea key that's DOESN'T exit
// } else {
// // else incremement VALUE for each successive (existing) occuring KEY
// acc[currVal] += 1;
// }
// acc[index] = currVal; // {0: 'banana', 1: 'cherry', 2: 'orange', 3: 'apple', 4: 'cherry', 5: 'orange', 6: 'apple', 7: 'banana', 8: 'cherry', 9: 'orange', 10: 'fig'}
return acc; // acc is an object, not an array.
}, {} ); // initial value is object
return result;
};
console.log(tally(fruitBasket)); // {banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1}
// https://www.freecodecamp.org/news/reduce-f47a7da511a9/
const euros = [29.76, 41.85, 46.5];
// console.log((29.76 + 41.85 + 46.5) / 2); // 59.055
// Find the average of the numbers in the euros array.
const calcAverage = function (arr) {
const average = arr.reduce((acc, currVal) => {
return acc += currVal;
});
return average / arr.length;
};
console.log(calcAverage(euros)); // 39.37
// Halve ea number before adding together
// Couldn't figure way to do w/out another loop unfortunately.
const divideThenAdd = function (arr) {
const divide = arr.reduce((acc, currVal) => {
// reduce an array of amounts into another array where every amount is doubled
acc.push(currVal / 2)
return acc;
}, []);
let total = 0;
divide.forEach(e => total += e);
return total;
};
console.log(divideThenAdd(euros)); // 59.055
// https://www.freecodecamp.org/news/reduce-f47a7da511a9/
const data3 = [
{a: 'happy', b: 'robin', c: ['blue','green']},
{a: 'tired', b: 'panther', c: ['green','black','orange','blue']},
{a: 'sad', b: 'goldfish', c: ['green','red']}
];
// Flattening an array w more complicated nested data.
// Get all colors; then get unique (only 1 of ea) colors.
// https://blog.greenroots.info/5-ways-to-merge-arrays-in-javascript-and-their-differences
// More like using function composition. Does one thing: gets colors from array.
const getColors = function (arr) { // only returns
// saves acc array as colors
const colors = arr.reduce((acc, currVal) => {
acc.push(...currVal.c); // 3 arrays flattened into one using spread
return acc; // DONT FORGET TO RETURN ACC!!
}, []);
// console.log('this is the colors variable: ', colors)
return colors;
};
console.log(getColors(data3)); // ['blue', 'green', 'green', 'black', 'orange', 'blue', 'green', 'red']
// Does one thing: removes duplicates from array.
const removeDupelicates = function (arr) {
let unique = [];
// const filterDupes = [...getColors(arr)].map((e) => !unique.includes(e) ? unique.push(e) : unique);
const filterDupes = [...getColors(arr)].map((e) => {
// Ternary replaces if/else below
!unique.includes(e) ? unique.push(e) : unique;
}
// if (!unique.includes(e)) {
// unique.push(e)
// } else {
// return;
// }
);
return unique;
};
console.log(removeDupelicates(data3)); // ['blue', 'green', 'black', 'orange', 'red']
const getColors = function (arr) {
return arr.reduce((acc, currVal, index, array) => {
// Only way I know atp is to use loop since 'c' is an array
// for..of also works & prolly regular 'for' loop (didn't try for..in)
array[index].c.forEach((e) => { // also works
// currVal.c.forEach((e) => { // also works
acc.push(e);
});
// https://www.shiksha.com/online-courses/articles/remove-duplicates-javascript-array/
// if the index of 'e' (ea color) exists, filter it out
return acc.filter((e, index) => acc.indexOf(e) === index); // filter duplicates
return acc; // unfiltered: (8) ['blue', 'green', 'green', 'black', 'orange', 'blue', 'green', 'red']
}, []);
};
console.log(getColors(data3)); // filtered: (5) ['blue', 'green', 'black', 'orange', 'red']
const getColors = function (arr) {
let unique = [];
for (let i = 0; i < arr.length; i++) {
if (unique.indexOf(arr[i]['c']) === -1) {
// Spread syntax makes flattening array of arrays easy.
// W/out spread it's still nested arrays instead of one array of values.
unique.push(...arr[i]['c']); // spread merges into one array.
}
}
// Using spread, flattens the 3 arrays into 1
// console.log(unique); // ['blue', 'green', 'green', 'black', 'orange', 'blue', 'green', 'red']
// If any existing item indices are DUPLICATED then filter (remove) them.
return unique.filter((e, index) => unique.indexOf(e) === index);
};
console.log(getColors(data3)); // ['blue', 'green', 'black', 'orange', 'red']
// filter() to remove duplicated items
const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig'];
const filterBasket = function (arr) {
// using indexOf()
// return arr.filter((item, index, origArr) => arr.indexOf(item) === index);
// using includes() requires pushing to an array, as far as I know.
let basket = [];
return arr.filter((item, index, origArr) => {
if (!basket.includes(item)) {
basket.push(item)
} else {
return;
}
return basket;
});
};
console.log(filterBasket(fruitBasket));
// Piping w reduce()
// https://www.freecodecamp.org/news/reduce-f47a7da511a9
function increment(input) { return input + 1 };
function double(input) { return input * 2 };
function decrement(input) { return input - 1 };
// Pipeline: a list of functions that transform some initial value into a final value.
// let pipeline = [increment, double, decrement];
let pipeline = [double, double, double];
// reduce over the pipeline of functions: initial value is what's transformed.
const pipeResult = pipeline.reduce(function (total, func) {
return func(total) // total is 'input' that's run through ea named function in array.
}, 6);
console.log(pipeResult);
// Sum the array and return the total divided by 2
// reduce() inline callback function
const sum = function (arr) {
return [...arr].reduce((acc, currVal, index, array) => {
// total the items of the array
acc += currVal;
// ternary replaces if/else below
return acc = index === array.length - 1 ? acc / 2 : acc;
// if (index === array.length - 1) { // if it's the end of the array, return acc / 2
// return acc / 2;
// } else {
// return acc; // acc is NaN until returned here.
// }
});
};
console.log(sum(nums)); // 10.5
// Return an array of doubled even numbers using reduce()
// Remember that acc is the array (initial value) and currVal starts a index 0
const array1 = [1, 2, 3, 4, 5, 6];
console.log(array1)
const double = function (arr) {
return arr = arr.reduce((acc, currVal, index, origArr) => {
if (currVal % 2 === 0) acc.push(currVal * 2);
return acc;
}, []);
};
console.log('double returns an array', double(array1)); // [4, 8, 12]
// https://javascript.info/array-methods#create-keyed-object-from-array
// so far... not getting first key of ea object 5/31/2023
// keyed object aka lookup table
const usersArr = [
{id: 'john', name: "John Smith", age: 20},
{id: 'ann', name: "Ann Smith", age: 24},
{id: 'pete', name: "Pete Peterson", age: 31},
];
const usersById = function (arr) {
const user = arr.reduce((acc, currVal, i, origArr) => {
// console.log(currVal); // 3 objects
for (key in currVal) {
// console.log(key); // id name age
acc[i] = currVal;
// console.log(key); // id name age
// acc[key] = currVal.name;
// acc[key] = currVal.age;
}
acc['id'] = currVal.id;
return acc;
// return acc = currVal;
// return acc = origArr[i];
}, {});
return user;
};
console.table(usersById(usersArr));
// console.log('orig array', usersArr)
// fun fun function recursion part 7 of functional programming JS
// https://www.youtube.com/watch?v=k7-N8R0-KY4&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84&index=8
// recursion: when a function calls itself until it doesn't
let countDown = (num) => {
if (num < 0) return 'poop';
console.log(num); // how else would I return num besides logging?
countDown(num - 1); // also --num
// return num; // 10 - ends looping
};
// countDown(10);
// console.log(countDown(10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment