Skip to content

Instantly share code, notes, and snippets.

@Wolfy64
Created June 16, 2018 01:02
Show Gist options
  • Save Wolfy64/2ec44953b2df3a21dc0f98b59bba3cfc to your computer and use it in GitHub Desktop.
Save Wolfy64/2ec44953b2df3a21dc0f98b59bba3cfc to your computer and use it in GitHub Desktop.
JavaScript - Recursion - entries: Object
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript - Recursion - entries()</title>
<style>
#myContainer {
max-width: 300px;
margin: 6px auto;
padding: 3px 0;
background-color: #ddd;
border: 1px solid #000;
text-align: center;
font-size: 16px;
font-family: 'Helvetica';
}
</style>
</head>
<body>
<div id="myContainer">
<div id="myDivElement"></div>
</div>
<script>
const myDiv = document.getElementById('myDivElement');
const myCollection = {
myObject: {
myZero: 0,
myOne: 1,
myTwo: 2,
myThree: 3
}
};
const myFunction = () => {
let myMappedObject = Object.entries(myCollection.myObject)
.map(myCurrentItem => {
const myKey = myCurrentItem[0];
const myNumberValue = myCurrentItem[1];
const myCurrentItems = (myQuantity, myArray = []) => {
if (myQuantity === 0) { return myArray; }
myArray.push(
`<div>key\=${myKey + myQuantity}\, type\=${myNumberValue}</div>`);
return myCurrentItems(myQuantity - 1, myArray
);
};
return myCurrentItems(myNumberValue);// the initial recursion invoker.
}).reduce((myReduceArray, myElement) => (
myReduceArray.concat(myElement)), []);
if (myMappedObject.length === 0) { return '<div>Error</div>';
} else { return `<div>${myMappedObject.join(' ')}</div>`; }
};
myDiv.innerHTML += myFunction();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment