CoDEVIANT #6 (3/26/19)

list([ {name: ‘Bart’}, {name: ‘Lisa’}, {name: ‘Maggie’} ])// returns ‘Bart, Lisa & Maggie’list([ {name: ‘Bart’}, {name: ‘Lisa’} ])// returns ‘Bart & Lisa’list([ {name: ‘Bart’} ])// returns ‘Bart’list([])// returns ‘’
  • We need to create some conditional logic here to evaluate the length
  • Of the names array, so we can have a better idea of what kind of punctuation marks to put between the names.
  • If there is more than one name, the last element should be preceded by ‘& ‘
  • If there are more than two names, the rule above applies, but all the others should be preceded by ‘, ‘
  • If there is just one name than it should just the one name returned
  • If there are no names, then we should return an empty ‘’.
function list(names){let nameArray = [];   names.forEach(function(object){      nameArray.push(object.name);   })console.log(nameArray);console.log(nameArray.length);   switch(nameArray.length) {      case 0:         return ‘’;      break;      case 1:         return nameArray[0];      break;      case 2:         return `${nameArray[0]} & ${nameArray[1]}`      default:         let last = nameArray.pop();console.log(nameArray);         let string = nameArray.join(‘, ‘);console.log(last);console.log(nameArray.concat(last));        return(string + ` & ${last}`);        break;   }
}
let namesArray = [];
example:let names = [{name: ‘Bart’},{name: ‘Lisa’},{name: ‘Maggie’}];names.forEach(function(object){namesArray.push(object.name);//first time it will be names[0] which equals -> {name: ‘Bart’}, and then cause ‘Bart’ to be sent to namesArray//namesArray at this point is [‘Bart’]//second time it will be names[1] which equals -> {name: ‘Lisa’}, and then cause ‘Lisa’ to join ‘Bart’ in the //namesArray array//namesArray at this point is [‘Bart’, ‘Lisa’]//third time it will be names[2] which equals -> {name: ‘Maggie’}, and then cause ‘Maggie’ to join her siblings //in the namesArray array//namesArray at this point is [‘Bart’, ‘Lisa’, ‘Maggie’]});//Then because we have no other array elements in names then we stop.
No…not THAT kind of hash.
  • If there is more than one name, the last element should be preceded by ‘& ‘
  • If there are more than two names, the rule above applies, but all the others should be preceded by ‘, ‘
  • If there is just one name than it should just the one name returned
  • If there are no names, then we should return an empty ‘’.
switch(nameArray.length) {//fun stuff coming!}
switch(nameArray.length) {   case 0:      return ‘’;   break;   default:   break;}
switch(nameArray.length) {   case 0:     return ‘’;   break;   case 1:      return nameArray[0];    break;   default:   break;}
  • If there is more than one name, the last element should be preceded by ‘& ‘
switch(nameArray.length) {   case 0:      return ‘’;   break;   case 1:      return nameArray[0];   break;   case 2:      return `${nameArray[0]} & ${nameArray[1]}`;   break;   default:   break;}
` `
`${ <stuff you’re passing in> }`
var food = ‘chicken’;console.log(‘I can eat’ + food); // logs “I can eat chicken”
var food = ‘chicken’;console.log(`I can eat ${food}`); // logs “I can eat chicken”
var a = 5;var b = 10;console.log(‘Fifteen is ‘ + (a + b) + ‘ and\nnot ‘ + (2 * a + b) + ‘.’);// “Fifteen is 15 and// not 20.”
var a = 5;var b = 10;console.log(`Fifteen is ${a + b} andnot ${2 * a + b}.`);// “Fifteen is 15 and// not 20.”
switch(nameArray.length) {   case 0:      return ‘’;   break;   case 1:      return nameArray[0];   break;   case 2:      return `${nameArray[0]} & ${nameArray[1]}`;   break;   default:      let last = nameArray.pop();      console.log(nameArray);      let string = nameArray.join(‘, ‘);      console.log(last);      console.log(nameArray.concat(last));      return(string + ` & ${last}`);   break;}
  • I use the array-method of .pop( ) to turn the last element of the array nameArray into a variable called last
  • I create a variable called string to equal the result of the use of the array-method .join( ) on nameArray, with the array-method argument being ‘, ‘ which turns the array nameArray into a string with each of it’s elements separated by a comma & a space. Because a comma and a space are what I passed into the array-method .join( ) when it was used on nameArray ;)
  • Then I return the string + the result of using template literals to put “& “ and the value of the variable we created called last.
function list(names){let nameArray = [];   names.forEach(function(object){      nameArray.push(object.name);   })   switch(nameArray.length) {      case 0:         return ‘’;      break;      case 1:          return nameArray[0];      break;      case 2:          return `${nameArray[0]} & ${nameArray[1]}`      default:          let last = nameArray.pop();          let string = nameArray.join(‘, ‘);          return(string + ` & ${last}`);      break;   }}
function list(names){   return names.reduce(function(prev, current, index, array){      if (index === 0){          return current.name;      } else if (index === array.length — 1){          return prev + ‘ & ‘ + current.name;      } else {          return prev + ‘, ‘ + current.name;      }   }, ‘’);}
  • We use the .reduce( ) method on the names array that is passed in as an argument.
  • Remember from previous entries in the series, that .reduce( ) mashes the values of an array to a single value.
  • .reduce( ) takes two arguments, the first of which is a callback function with a max of 4 sub arguments
  • * initialValue -> prev (the previously returned value of the function)
  • * currentValue -> current (the current value being focused on)
  • * index -> index (the array index of the current element)
  • * arr -> array (the array the current element belongs to)
  • .reduce( )’s 2nd argument is a value to be passed to the function as the initial value.
  • In this case: “ “
function list(names){   return names.reduce(function(prev, current, index, array){      if (index === 0){         return current.name;      } else if (index === array.length — 1){         return prev + ‘ & ‘ + current.name;      } else {         return prev + ‘, ‘ + current.name;      }   }, ‘’);}
  • .pop( )
  • .push( )
  • .join( )
Pop & Lock!
  • Assume it will start with date represented as long number
  • Followed by an underscore
  • Youll have then a filename with an extension
  • it will always have an extra extension at the end

Inputs:

1231231223123131_FILE_NAME.EXTENSION.OTHEREXTENSION1_This_is_an_otherExample.mpg.OTHEREXTENSIONadasdassdassds341231231223123131_myFile.tar.gz2

Outputs

FILE_NAME.EXTENSIONThis_is_an_otherExample.mpgmyFile.tar
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-0123456789
class FileNameExtractor {   static extractFileName (dirtyFileName) {      let firstUnderScorePosition = dirtyFileName.indexOf(‘_’)   dirtyFileName = dirtyFileName.slice(firstUnderScorePosition + 1);      let fileArray = dirtyFileName.split(‘.’)      return `${fileArray[0]}.${fileArray[1]}`;   }}
class FileNameExtractor {   static extractFileName (dirtyFileName) {   return ’the answer’;   }}
  • I needed to find the first occurrence of an underscore, because the long date would be immediately before it and we don’t want that in our final result
let firstUnderScorePosition = dirtyFileName.indexOf(‘_’)
  • Then I wanted to slice out the underscore and everything above it by making the argument equal itself but with the date and the first underscore removed
dirtyFileName = dirtyFileName.slice(firstUnderScorePosition + 1);
  • Then I wanted to create an array called fileArray and make it equal to dirtyFileName having .split( ) used on it but with a period as the argument so that we would wind up with the chunks we wanted, sans period
let fileArray = dirtyFileName.split(‘.’)//If dirtyFileName at this point equals ‘FILE_NAME.EXTENSION.OTHEREXTENSION’//this results in [ ‘FILE_NAME’, ‘EXTENSION’, ‘OTHEREXTENSION’ ]
  • Now I only want the first two with a period between them, so I return the elements at indices 0 & 1 with a period between them like so:
return `${fileArray[0]}.${fileArray[1]}`;
class FileNameExtractor {static extractFileName = dirty => dirty.match(/^\d+_([^.]+\.[^.]+)/)[1];}
class FileNameExtractor {   static extractFileName (dirtyFileName) {   var numSlice = dirtyFileName.indexOf(‘_’)   var extSlice = dirtyFileName.lastIndexOf(‘.’)   dirtyFileName = dirtyFileName.slice(numSlice+1, extSlice)   return dirtyFileName   }}
  • Just like I did, we find the index of the first ‘_’
  • But in a smarter way, they chose to find the last index of ‘.’
  • Then they made dirtyFileName equal itself going through the slicing procedure where they cut from just after the first ‘_’ to right before the last ‘.’
  • And then they profit.
G’night, nerds.

--

--

--

is a web developer, opera singer, actor, and lover of cats. (adrian-rosales.tech)

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

5 for test

The Rise of JAMstack 🚀

React Fundamentals Week One

Publish Angular Library created with Nx to NPM

7 JavaScript One-Liners That Are Insanely Useful

JavaScript one liners

Basic Concept of React.js

Single Page Applications vs ReactJS

A cosy little story of someone’s dream, one app and React Native (part 1)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrian Rosales

Adrian Rosales

is a web developer, opera singer, actor, and lover of cats. (adrian-rosales.tech)

More from Medium

Intercode: An Introduction

The Test Driven Development: The Good, The Bad, and The Inevitable

As a data science enthusiast, I am excited to share my real-time project experience in the Boot…

Kruskal Algorithm