Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Last active December 1, 2022 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/d99f304a0964b6080da0e3124e7f675c to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/d99f304a0964b6080da0e3124e7f675c to your computer and use it in GitHub Desktop.
Sample Code for Merging data arrays from two sources into one object
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
'Helvetica Neue', sans-serif;
font-size: 20px;
}
header {
padding: 1rem;
}
h1 {
font-size: 3rem;
}
button {
font-size: 1rem;
padding: 0.5rem 2rem;
vertical-align: middle;
}
main {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
padding: 1rem;
}
main .current {
display: grid;
grid-template-columns: 1fr 1fr;
grid-auto-rows: 3rem;
gap: 1rem;
}
main .current p {
font-size: 1rem;
padding: 1rem 1rem;
line-height: 1rem;
background-color: cornflowerblue;
color: white;
}
import Ffetch from './fetch.js';
const cache = {};
let fetchCount = 0;
document.addEventListener('DOMContentLoaded', () => {
const btn = document.querySelector('header button');
btn.addEventListener('click', getData);
});
function getData(ev) {
let url = `https://www.example.com/cool/things/`;
Ffetch(url)
.then((response) => {
if (!response.ok) throw new Error('fake failure');
return response.json();
})
.then((data) => {
//data is an array of objects
console.log({ data });
//save each id and name inside our `cache` object
const container = document.querySelector('.current');
container.innerHTML = data
.map((person) => {
//check about saving in the cache
if (person.id in cache) {
//previously used id
console.log(person.id, 'exists in the cache');
//use the old name and ignore the new one
return `<p data-id="${person.id}">${person.id} : ${cache[person.id]}</p>`;
} else {
//new id... save it with the name
cache[person.id] = `${person.name} from fetch ${fetchCount}`;
return `<p data-id="${person.id}">${person.id} : ${person.name}</p>`;
}
})
.join('');
//now show the current cache
showCache();
})
.catch((err) => {
console.warn(err.message);
});
}
function showCache() {
let div = document.querySelector('.obj pre');
let str = JSON.stringify(cache, null, '\n\t');
div.innerHTML = `<p>${str}</p>`;
}
const theData = [];
const names = [
'Leonard',
'Sheldon',
'Raj',
'Howard',
'Bernadette',
'Amy',
'Penny',
'Emily',
'Ross',
'Rachel',
'Joey',
'Chandler',
'Phoebe',
'Monica',
'Jen',
'Maurice',
'Roy',
'Richmond',
'Douglas',
'Richard',
'Erlich',
'Monica',
'Jared',
'Gilfoyle',
'Dinesh',
'Jin Yang',
'Dolores',
'Bernard',
'William',
'Maeve',
'Teddy',
'Charlotte',
'Caleb',
'Clementine',
'Sam',
'Dean',
'Bobby',
'Lisa',
'Ben',
'Crowley',
'Castiel',
'Jack',
'Samuel',
'John',
'Mary',
'Ruby',
'Meg',
];
function buildData(tempNames) {
for (let i = 0; i < 16; i++) {
let id = Math.random().toString(16).substring(2, 4); //2 digit hex value
let index = Math.floor(Math.random() * tempNames.length);
let name = tempNames.splice(index, 1)[0];
theData.push({ id, name });
}
}
export default function Ffetch(url) {
console.log(`Fake fetching ${url}`);
theData.length = 0;
return new Promise((resolve, reject) => {
buildData(Array.from(names));
let json = new File([JSON.stringify(theData)], 'data.json', {
filetype: 'application/json',
});
let response = new Response(json, { status: 200, statusText: 'ok' });
resolve(response);
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script type="module" src="./app.js"></script>
<link rel="stylesheet" href="./app.css" />
</head>
<body>
<header>
<h1>Saving Data <button>Fetch Data</button></h1>
</header>
<main>
<h2>Current Fetch</h2>
<h2>Saved Object</h2>
<div class="current"></div>
<div class="obj"><pre></pre></div>
</main>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment