Skip to content

Instantly share code, notes, and snippets.

@franvarney
Created November 14, 2017 19:34
Show Gist options
  • Save franvarney/8db8cf7fb454d2c4d6ded2a4126a75f2 to your computer and use it in GitHub Desktop.
Save franvarney/8db8cf7fb454d2c4d6ded2a4126a75f2 to your computer and use it in GitHub Desktop.
function getInput() {
return [
['name', 'tags'],
['john',' hungry,likes_pizza'],
['maggie', 'thirsty, productmanager,likes_pizza'],
['sally', 'hungry,thirsty, somethingelse'],
['tim', 'productmanager']
];
}
// Option 1
function parseInput(input) {
const headers = input.shift();
return input.reduce((obj, item) => {
obj[item[0]] = item[1].replace(/ /g, '').split(',');
return obj;
}, {});
}
function getHungryEngineers(parsed) {
const results = [];
Object.keys(parsed).forEach((key) => {
if (parsed[key].includes('hungry')) {
results.push({ name: key });
}
});
return results;
}
// console.log(parseInput(getInput()));
/* {
john: [ 'hungry', 'likes_pizza' ],
maggie: [ 'thirsty', 'productmanager', 'likes_pizza' ],
sally: [ 'hungry', 'thirsty', 'somethingelse' ],
tim: [ 'productmanager' ]
} */
console.log(1, getHungryEngineers(parseInput(getInput())));
/* [
{ name: 'john' },
{ name: 'sally' }
] */
// Option 2
function getHungryEngineers2(input) {
const results = [];
for (let i = 1; i < input.length; ++i) {
if (input[i][1].includes('hungry')) {
results.push({ name: input[i][0] });
}
}
return results;
}
console.log(2, getHungryEngineers2(getInput()));
// Option 3
function parseInput2(input) {
return {
getNames: function () {
const names = [];
for (let i = 1; i < input.length; ++i) {
names.push(input[i][0]);
}
return names;
},
getTags: function () {
const tags = {};
for (let j = 1; j < input.length; ++j) {
let tagSet = input[j][1].replace(/ /g, '').split(',');
tagSet.forEach((tag) => {
if (!tags.hasOwnProperty(tag)) tags[tag] = [j];
else tags[tag].push(j);
});
}
return tags;
}
};
}
function getEngineersByTags(input, searchTags) {
const results = [];
const names = input.getNames();
const tags = input.getTags();
const ids = [];
searchTags.forEach((tag) => {
if (tags.hasOwnProperty(tag)) {
ids.push(...tags[tag]);
}
});
ids.filter((id, index, arr) => arr.indexOf(id) === index)
.forEach((id) => results.push({ name: names[id] }));
return results;
}
console.log(3, getEngineersByTags(parseInput2(getInput()), ['hungry', 'thirsty']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment