Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active February 1, 2017 22:16
Show Gist options
  • Save abhisekp/7af3c084978f99cf824e to your computer and use it in GitHub Desktop.
Save abhisekp/7af3c084978f99cf824e to your computer and use it in GitHub Desktop.
Bonfire - Where art thou Solutions - FreeCodeCamp

Many of the solutions available around the internet for Bonfire: Where art thou are quite not right even if they pass the tests in FreeCodeCamp (FCC) because they don't adhere to the instructions completely.

  • Disclaimer: Please don't look into the solutions if you've not solved it yourself.

Bonfire Instruction:-

Make a function that looks through a list (first argument) and returns an array of all objects that have equivalent property values (second argument).


Here are two solutions that exactly adhere to the instructions given in the Bonfire Challenge.

Solution 1:-

function where(collection, source) {
  // "What's in a name? that which we call a rose
  // By any other name would smell as sweet.”
  // -- by William Shakespeare, Romeo and Juliet
  var srcKeys = Object.keys(source);
  
  // filter the collection
  return collection.filter(function (obj) {
    // return a Boolean value for filter callback using reduce method
    return srcKeys.reduce(function (res, key) {
      // reduce to Boolean value to be returned by reduce method
      return obj.hasOwnProperty(key) && obj[key] === source[key];
    }, false);
  });
}

// should output: [ { first: 'Tybalt', last: 'Capulet' } ]
console.log(where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' }));

// should output: [ { a: 5, b: 10 } ] 
console.log(where([{ 'a': 5 }, { 'a': 5 }, { 'a': 5, 'b': 10 }], { 'a': 5, 'b': 10 }));

Solution 2:-

function where(collection, source) {
  // "What's in a name? that which we call a rose
  // By any other name would smell as sweet.”
  // -- by William Shakespeare, Romeo and Juliet
  var srcKeys = Object.keys(source);
  
  // filter the collection
  return collection.filter(function (obj) {
    for(var i = 0; i < srcKeys.length; i++) {
      // check if obj in collection doesn't have the key
      // or if it does have the key,
      // then check if the property value doesn't match the value in source
      if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
        return false;
      }
    }
    return true;
  });
}

// should output: [ { first: 'Tybalt', last: 'Capulet' } ]
console.log(where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' }));

// should output: [ { a: 5, b: 10 } ] 
console.log(where([{ 'a': 5 }, { 'a': 5 }, { 'a': 5, 'b': 10 }], { 'a': 5, 'b': 10 }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment