Skip to content

Instantly share code, notes, and snippets.

@thurt
Created February 8, 2019 20:22
Show Gist options
  • Save thurt/a7a00ac0604d6553ed3496ee5ef4105d to your computer and use it in GitHub Desktop.
Save thurt/a7a00ac0604d6553ed3496ee5ef4105d to your computer and use it in GitHub Desktop.
function zipObject(keys, values) {
// often simple edge cases are taken care of at the top so they aren't hidden inside the middle of the function
if (keys === undefined && values === undefined) {
return {}; // for test 3
}
// category of problem: convert [] -> {}
// simple strategy for conversion problems is to create a blank object at the beginning, build it up in the middle, return it at the end
// create blank starter obj
const obj = {}
// build up the obj
if (values !== undefined) {
// for test 1
keys.forEach((key, i) => { // second parameter, i, is rarely used, but is useful in this problem to pick the value
// need to assign this key to a new property on obj dynamically by adding the property with square brackets
obj[key] = values[i];
})
} else if (typeof keys[0] === 'string') {
// for test 4
keys.forEach(key => {
// key is actually the property name
// value is always undefined
obj[key] = undefined;
})
} else {
// for test 2
keys.forEach(key => {
// key is actually an array
// key[0] is actually the property name
// key[1] is actually the value
obj[key[0]] = key[1];
})
}
// return the obj
return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment