Skip to content

Instantly share code, notes, and snippets.

@TessMyers
Last active October 5, 2023 16:36
Show Gist options
  • Save TessMyers/a252520dd9a8fe68f8e5 to your computer and use it in GitHub Desktop.
Save TessMyers/a252520dd9a8fe68f8e5 to your computer and use it in GitHub Desktop.
Simple exercises using .map and .reduce
// Simple problems to solve using the native .reduce and .map array methods. Each of these problems can be solved in many
// different ways, but try to solve them using the requested higher order function.
// MAP
// Write a function capitalize that takes a string and uses .map to return the same string in all caps.
// ex. capitalize('whoop') // => 'WHOOP'
// ex. capitalize('oh hey gurl') // => "OH HEY GURL"
var capitalize = function(string){
// code code code!
}
// Now write a new function called swapCase that takes a string of words and uses .map and your newly written capitalize()
// function to return a string where every other word is in all caps.
// Hint: look up Array.prototype.map on MDN and see what arguments the .map callback can take.
// ex: swapCase('hey gurl, lets javascript together sometime') // => "HEY gurl, LETS javascript TOGETHER sometime"
var swapCase = function(string){
// Codeeeee
}
// Write a function shiftLetters that takes a string and uses .map to return an encoded string with each letter shifted down the
// alphabet by one. Hint: Use Look up the JS functions String.fromCharCode() and String.CharCodeAt() and see if you can use
// Ascii code to acomplish this.
// ex. shiftLetters('hello') // => 'ifmmp'
// ex. (shiftLetters('abcxyz') // => "bcdyz{"
var shiftLetters = function(string){
// code!
}
// REDUCE
// Write a function that takes a string and returns an object representing the character
// count for each letter. Use .reduce to build this object.
// ex. countLetters('abbcccddddeeeee') // => {a:1, b:2, c:3, d:4, e:5}
var countLetters = function(string){
// your code here
};
// Write a function that takes a string and a target, and returns true or false if the target is present in the string. Use
// .reduce to acomplish this.
// ex. isPresent('abcd', 'b') // => true
// ex. isPresent('efghi', 'a') // => false
var isPresent = function(string, target) {
// GO GO GADGET CODE!
}
// PARTY WITH MAP AND REDUCE *AT THE SAME TIME*
// Write a function decode that will take a string of number sets and decode it using the following rules:
// When each digit of each set of numbers is added together, the resulting sum is the ascii code for a single letter.
// Convert each set of numbers into a letter and discover the secret message!
// Try using map and reduce together to accomplish this task.
// ex. decode("361581732726247521644353 4161492813593986955 84654117917337166147521") // => "abc"
// ex. decode("584131398786538461382741 444521974525439455955 71415168525426614834414214 353238892594759181769 48955328774167683152 77672648114592331981342373 5136831421236 83269359618185726749 2554892676446686256 959958531366848121621517 4275965243664397923577 616142753591841179359 121266483532393851149467 17949678591875681")
// => "secret-message"
var decode = function(string){
// CODE PARTY
}
// Once you successfully write a decoding function, use it to decode this secret message!
"444689936146563731 2452966188592191874 52634311978613959924676311 4874232339 491973615889195397613151 64491375479568464397 2799868298847212752434 9464245911 84529438455334236247245 8131257451645317232949247 26471594451453281675411332 6631592725297745964837 616698332453173937881461 3311783543427862468268 385418321228899775431 4659867 73395213225525916984356 833792195426925124155181841 123388893 6941777837193213644325351 11353488912476869536954 61173937137292328237388335 5344692 452956158 31937616696951768494 584842118999165552436 8832121577139589884 15282516522883423742885 14713349724 6919979438697694 2252585676244745856486 5617683424485959291 547443594 2678324174797795449925 43753791352187862731151912 6875665565836721939262 35482977 84421878934473534291995 798457553821668942312 11114498238219156246883553 3599955 8831995953696776 8138759916933117676486 2388776737768787 37232647683297835458183 11318659392964788174775 683293746169875551252354 741545327395636643318531 38447974824822841161273 88768222547689886222 6345677462396774359 4942661761 1354569165 2553653936124138282 851786784517417366411515 42279319649497959785 5523951771 45941761289678527316294 37776454913244819275691 436669892715419465494342 682264111527 734681268219555989841131 882641896825571288724 382545666 12133138432672285179566156291 83644842221351483476411355532 9589336353993598224 184537669759184472427331 41851326945453796784 525783591 173773335961894524914465 47516715963756294236321 7296569497726217615 79487235 4931878519724923131437 31214731844284735237658435 1378458823933518466122 1241955123792435126557994 347427652476673662454 55596877477154112241923 9789414554758712319821 86228624276917113671233411 89659521 1352796469161477381192 69483824148396716861472 4766533634762298963245 5155973593459278561 1784478259974148659431 29583142566714785218623 244371427148584159487652 871836193187759591363 247956"
@maxnathaniel
Copy link

Thanks for the exercise!

Spotted a typo as I did the exercise.

String.CharCodeAt() should be String.charCodeAt()

@PrimarchAlpharius
Copy link

Pretty cool, thanks.

@yelyel
Copy link

yelyel commented Apr 11, 2018

Nice exercise, but are the solutions anywhere ?? (for us dummies to compare ?? ) thx

@zllec
Copy link

zllec commented Jul 11, 2018

First Solution
const capitalize = (string) => { return string.split(" ").map(word => { return word.split("").map(letter => { return letter.toUpperCase(); }).join('') }).join(' ') }

@zllec
Copy link

zllec commented Jul 11, 2018

Second Solution

`
const capitalize = (string) => {
return string.split(" ").map(word => {
return word.split("").map(letter => {
return letter.toUpperCase();
}).join('')
}).join(' ')
}

const swapCase = (string) => {
return string.split(" ").map((word, index) => {
return (index % 2 === 0) ? capitalize(word) : word
}).join(' ');
}

console.log(swapCase("In arithmetic, the division of two integers produces a quotient and a remainder."))
`

@zllec
Copy link

zllec commented Jul 11, 2018

Third Solution

const shiftLetters = (string) => { return string.split(" ").map(word => { return word.split("").map(letter => { return String.fromCharCode((letter.charCodeAt() + 1)) }).join('') }).join(' ') }

@zllec
Copy link

zllec commented Jul 11, 2018

Fourth Solution

const countLetters = (string) => {
return string.split("").reduce((accumulator, currentValue) => {
accumulator.hasOwnProperty(currentValue) ?
accumulator[currentValue]++ :
accumulator[currentValue] = 1
return accumulator
}, {})
}

@zllec
Copy link

zllec commented Jul 11, 2018

Fifth Solution

const isPresent = (string, target) => {
return string.split("").reduce((accumulator, currentValue) => {
if(currentValue === target) accumulator = true;
return accumulator;
}, false)
}

@zllec
Copy link

zllec commented Jul 11, 2018

Sixth Solution

const decode = (string) => {
return string.split(" ").map(word => {
return String.fromCharCode(word.split("").reduce((accumulator, currentValue) => {
return parseInt(accumulator) + parseInt(currentValue)
}))
}).join("")
};

@gibbok
Copy link

gibbok commented Aug 6, 2018

Thanks for the exercise it was quite fun.

Here my solution using TS:

Edit js-just-for-fun

const capitalize = (input: string) =>
  [...input].map(x => x.toUpperCase()).join("");

const swapCase = (input: string) =>
  input
    .split(" ")
    .map((x: string, idx: number) => (idx % 2 ? x : capitalize(x)))
    .join(" ");

const shiftLetters = (input: string) =>
  [...input].map(x => String.fromCharCode(x.charCodeAt(0) + 1));

const countLetters = (input: string) =>
  [...input].reduce(
    (acc, value, idx) => ({
      ...acc,
      [value]: !acc[value] ? 1 : ++acc[value]
    }),
    {}
  );

const isTargetPresent = (input: string, target: string) => {
  let comparison = "";
  return [...input].reduce((acc: string, value: string) => {
    comparison += value;
    return acc || comparison.indexOf(target) >= 0;
  }, false);
};

const decode = (input: string) =>
  input
    .split(" ")
    .map(x =>
      [...x].reduce(
        (acc: string, value: string) => parseInt(acc, 10) + parseInt(value, 10),
        0
      )
    )
    .map(y => String.fromCharCode(y))
    .join("");

@OUARRICH
Copy link

OUARRICH commented Sep 5, 2018

Fourth solution

function countLetters(str){
return [...str].reduce((a, v) =>Object.assign(a, {
...({[v]: !a[v] ? 1 : ++a[v]})
}), {} );
}

@Anujarya300
Copy link

Anujarya300 commented Jun 3, 2019

Thanks for this exercise.

Tried writing encode function i.e reverse of decode function in the last example:

e.g: encode("you are smart") => "064095490071848045762859073 744067793885130624380862 193034471710168073137292065377 4287111134 990415245117124919089312 9656315037193799451209532 13592479950137225292671 2893073 91606385891690926616176 477918547632644853961 8211331027647299939236 27365212114319204217111206379514911 959207228164967054448581"

function encodeSentance(str){
	return [...str].map(x => encodeLetter(x)).join(" ");
}
/*
* Forever loop through with generating a random number from 0 to 9 each time util 
* the sum of generated numbers = ascii value of input char string 
*/
function encodeLetter(s){
	let ascii = s.charCodeAt(0);
	let values = [];
	let sum = 0;
	while(true){		
		let r = Math.floor(Math.random()*10);
		if(sum === ascii){
			break;
                 }
		if(sum + r > ascii){
			values.push(ascii - sum);
			break;
                 }
		sum += r;
		values.push(r);
         }
	return values.join("");
}

Example: encode("ninja") => 
"3509330101148693211418527362345 373306679246639729152032 74428217132667261078619541 9967085653368937831 2816561796661151553445"

@Saurabgami977
Copy link

//First answer

function capitalize(string){
let caps = string.map(word => word.toUpperCase())
return caps;
}
console.log(capitalize(['whoop', 'yellow']));

@Saurabgami977
Copy link

// Second Answer

let swapCase = function(string){
let array = string.split( ' ');
const newArr = array
.map((word, index)=> index%2 === 0 ? word.toUpperCase() : word);

return newArr

}
console.log(swapCase('hey girl, lets javascript together sometime.'))

@randomuseraccount
Copy link

Thanks for this exercise!
Here are my solutions:

    getCharArrayFromString = (string) => {
        const charArray = [];
        for(let i = 0; i < string.length; i++) {
            charArray.push(string.charAt(i));
        }
        return charArray;
    };

    mapCapitalize = (string) => {
        return this.getCharArrayFromString(string).map(c => c.toLocaleUpperCase()).join('').toString();
    };

    swapCase = (string) => {
        const stringArr = string.split(" "),
        res = [];

        stringArr.forEach((str, index) => {
            if(index % 2 > 0) {
                res.push(str);
            } else {
                res.push(this.mapCapitalize(str));
            }
        });
        return res.join(" ");
    };

    shiftLetters = (string, charCodeAt = "charCodeAt") => {
        const charArray = [];
        for(let i = 0; i < string.length; i++) {
            charArray.push(string[charCodeAt](i) + 1);
        }
        return String.fromCharCode(...charArray);
    };

    countLetters = (string) => {
        const charArray = this.getCharArrayFromString(string);
        return charArray.reduce((acc, currVal) => {
            if(acc[currVal] !== undefined) {
                acc[currVal] += 1;
            } else {
                acc[currVal] = 1;
            }
            return acc;
        }, {});
    };

    isPresent = (string, target) => {
        const charArray = this.getCharArrayFromString(string);
        return charArray.reduce((acc, currVal) => {
            if(currVal === target) {
                acc = acc || true;
            }
            return acc;
        }, false)
    };

    decode = (string) => {
        const summableDigitsArray = string.split(" "),
            summedArray = summableDigitsArray.map(summableDigit => {
           return this.getCharArrayFromString(summableDigit).reduce((acc, currVal) => {
               return acc += parseInt(currVal, 10);
           }, 0);
        });
        return String.fromCharCode(...summedArray);
    };

Regards.

@teifler
Copy link

teifler commented Dec 27, 2021

first

var capitalize = function(string){
// code code code!
return string.split(" ").map(word => word.toUpperCase()).join(' ')
}
console.log(capitalize('oh hey gurl')) // => "OH HEY GURL"

@teifler
Copy link

teifler commented Dec 27, 2021

Second:

var swapCase = function(string){return string.split(" ").map((word, index) => (index %2 == 0) ? word.toUpperCase() : word).join(" ");
}

@teifler
Copy link

teifler commented Dec 27, 2021

Third:
var shiftLetters = function(string){
return string.split('').map(letter => {
let charCode = letter.charCodeAt(0)
charCode += 1;
letter = String.fromCharCode(charCode)
return letter
}).join('')
}

console.log(shiftLetters('abcxyz')) // => "bcdyz{"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment