Functional Programming basics with example

let data1 = 'This is a fairly short string.'
let data2 = [ 1,2,3,4,2,4,2,3,4,5,2,5,1,3 ]
function dataToFrequency(data){
switch(typeof data){
case 'string':
return arrayToFrequency(stringToArray(data))
break;
case 'object':
return arrayToFrequency(data)
break;
default:
console.log('Error: New data type in dataToArray()')
}
}
function stringToArray(string){
return string.split(' ')
}
function arrayToFrequency(array){
let frequency = {}
array.forEach(character => {
frequency[character]
? frequency[character] += 1
: frequency[character] = 1
})
return frequency
}
function dataToFrequency(data){
let cleanData = dataToArray(data)
return arrayToFrequency(cleanData)
}
function dataToArray(data){
switch(typeof data){
case 'string':
data = stringToArray(data)
break;
case 'object':
break;
default:
console.log('Error: New data type in dataToArray()')
}
return data
}
function stringToArray(string){
return string.split(' ')
}
function arrayToFrequency(array){
let frequency = {}
array.forEach(character => {
frequency[character]
? frequency[character] += 1
: frequency[character] = 1
})
return frequency
}

--

--

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