Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arihantverma/6f540ef1ea4e7855d14573c9c3d6787b to your computer and use it in GitHub Desktop.
Save arihantverma/6f540ef1ea4e7855d14573c9c3d6787b to your computer and use it in GitHub Desktop.
/* Problem Name is &&& JS Object to String &&& PLEASE DO NOT REMOVE THIS LINE. */
/**
* Instructions to candidate:
*
* 1) Given the below code. Write a function (ES6 recommended) that loops through all the properties of the Employee and create a comma-seperated string with the values
* For e.g.
* {
* firstName: "X",
* lastName: "Y",
* project: {
* id: 1,
* name: "ABC"
* }
* }
* should be converted to a string like this "X, Y, 1, ABC, "
*
*
* NOTE: The function shouldn't convert the prototypically inherited properties For e.g. in this case "managerId"
*
*/
/**
* TODO: Write a function here called 'convertToString' that will return the expected result.
*/
function convertToString() {
}
// -----------------------------------
/**
* Returns true if all tests pass; otherwise, returns false.
*/
function doTestsPass(testCases)
{
// todo: add more test cases
return testCases.reduce((result, testCase) => {
const answer = convertToString(testCase.inputs);
console.info("expected: ", testCase.expected, ", answer: ", answer);
return result && (answer === testCase.expected);
}, true);
}
const testCases = [
{
expected: "Frank, Sinatra, 1, Trader Platform, ",
inputs: new Employee("Frank", "Sinatra", { id: 1, name: "Trader Platform"})
}
];
/**
* Main execution entry.
*/
if(doTestsPass(testCases))
{
console.log("All tests pass!");
}
else
{
console.log("There are test failures.");
}
@arihantverma
Copy link
Author

arihantverma commented Mar 17, 2021

Solution

repl code for the code below

/* Problem Name is &&& JS Object to String &&& PLEASE DO NOT REMOVE THIS LINE. */

/**
 * Instructions to candidate:
 *
 *  1) Given the below code. Write a function (ES6 recommended) that loops through all the properties of the Employee and create a comma-seperated string with the values
 *     For e.g.
 *     { 
 *        firstName: "X",
 *        lastName: "Y",
 *        project: {
 *           id: 1,
 *           name: "ABC"
 *         } 
 *     }
 *     should be converted to a string like this "X, Y, 1, ABC, "
 *
 *
 *  NOTE: The function shouldn't convert the prototypically inherited properties For e.g. in this case "managerId"
 *
 */
const Employee = function (fName, lName, project) {
  this.firstName = fName;
  this.lastName = lName;
  this.project = project;

  this.getFullName = function () {
  return this.lastName + ", " + this.firstName;
  }
};
Employee.prototype.managerId = 123;
Employee.prototype.sayHello = function () {
  console.log("Hello");
};
// ---------------------------------------------

// -------------- write your code here -----------------
function isNonNullable(val) {
  return (val !== null) && (val !== undefined)
}

function isPlainObject(val) {
  const typeIsOfTypeObject =  typeof val === 'object';
  const objectIsJavascriptObject = Object.prototype.toString.call(val) === '[object Object]';

  return typeIsOfTypeObject
    && objectIsJavascriptObject
    && isNonNullable(val);
}


function isFunc(val) {
  return Object.prototype.toString.call(val) === '[object Function]' && isNonNullable(val);
}

/**
 * TODO: Write a function here called 'convertToString' that will return the expected result.
 */
function convertToString(obj, i = 0) {
  function recursiveIterator(employeeObj, index = 0) {
     /* since we are using Object.keys, we automatically
      * take care of the `The function shouldn't convert the prototypically inherited properties For e.g. in this case "managerId"`
      * part in the question. Refer `Object.keys ` mdn docs for why that is
     */
      const keys = Object.keys(employeeObj);

      const retVal = keys.reduce((collector, key) => {
      const val = employeeObj[key];

      /**
       * if it's a function we don't want to do anything with it
       * so we just return the collector array
       */
      if (isFunc(val)) {
        return collector;
      }

      /**
       * if it's a plain javascript object, we need to recurse
       */
      if (isPlainObject(val)) {
        /**
         * the index is just a count of the number of times
         * `recursiveIterator` is called. It's just for debugging
         * purposes. As you can see that we aren't using it anywhere,
         * but just increasing it for every `recursiveIterator` call
         */
        const nextIndex = index ? ++index: 1;

        /**
         * if it's an object, we need to recurse
         * and we need to concat the return value
         * into our collector array. If you don't know
         * how recursion works, you would need to 
         * understand that a little better.
         */
        return collector.concat(recursiveIterator(val, nextIndex));
      }
    
      return collector.concat(val);
    }, [])

    return retVal;
  }

  const finalRetVal = recursiveIterator(obj, i);

  const finalString = finalRetVal.join(', ') + ', '; // just to make the tests work (🤷🏽‍♂️)
  
  return finalString;
}

// -------- END of code that needs to be written ---------------
/**
 * Returns true if all tests pass; otherwise, returns false.
 */
function doTestsPass(testCases)
{
  // todo: add more test cases
  return testCases.reduce((result, testCase) => {
    const answer = convertToString(testCase.inputs);
    console.info("expected: ", testCase.expected, ", answer: ", answer);
    return result && (answer === testCase.expected);
  }, true);
}


const testCases = [
  { 
  expected: "Frank, Sinatra, 1, Trader Platform, ",
  inputs: new Employee("Frank", "Sinatra", { id: 1, name: "Trader Platform"})
  }
];

/**
 * Main execution entry.
 */
if(doTestsPass(testCases))
{
  console.log("All tests pass!");
}
else
{
  console.log("There are test failures.");
}

@arihantverma
Copy link
Author

arihantverma commented Mar 17, 2021

If you read this and report any unhandled use case, or any error, please feel free to tell that in the comments, so that I can update the solution with it :)

If you find this solution helpful, kindly star the gist :)

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