Skip to content

Instantly share code, notes, and snippets.

@zempo
Created December 12, 2018 07:40
Show Gist options
  • Save zempo/127aa1c3abac10155280b98cd28390f3 to your computer and use it in GitHub Desktop.
Save zempo/127aa1c3abac10155280b98cd28390f3 to your computer and use it in GitHub Desktop.
find by id drill created by zempo1 - https://repl.it/@zempo1/find-by-id-drill
// you can pass in `scratchData` to test out `findByid`
// your function
const scratchData = [
{ id: 22, foo: 'bar' },
{ id: 28, foo: 'bizz' },
{ id: 19, foo: 'bazz' },
];
function findById(items, idNum) {
return items.find(item => item.id === idNum);
}
/* OR YOU COULD USE...
for (let i = 0; i < items.length; i++) {
if (items[i].id === idNum) {
return items[i];
}
}
*/
function testIt() {
const testData = [
{ id: 1, foo: 'bar' },
{ id: 2, foo: 'bizz' },
{ id: 3, bang: 'boo' },
];
const result = findById(testData, 3);
if (!(result && result !== null && typeof result === 'object')) {
console.error('`findById` must return an object');
return;
}
if (result.id !== 3) {
console.error(
'Asked for item with id of `3` but got back one with id of ' + result.id
);
return;
}
if (result.bang !== 'boo') {
console.error(
'Expected all key/value pairs from target object to be returned'
);
return;
}
console.log('SUCCESS: `findByid` is working');
}
testIt();
@zempo
Copy link
Author

zempo commented Dec 12, 2018

Starred for later study! JS | Checkpoint 12, find by id exercise

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