Skip to content

Instantly share code, notes, and snippets.

@ziyoshams
Last active August 27, 2018 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziyoshams/3155af4af75fd599b3635b9fccb9893e to your computer and use it in GitHub Desktop.
Save ziyoshams/3155af4af75fd599b3635b9fccb9893e to your computer and use it in GitHub Desktop.

ANSWERS

Pascals Triangle

Click here to run the code.

const pascalsTriangle = (level) => {
  if(level > 25 || level < 2) throw new Error('Chose a number between 2 and 25');
  
  let initialArray = [1];
  console.log(initialArray.join(' '));

  for (let i = 1; i < level; i++) {
    let tempArr = [initialArray[0]];
    for (let j = 0; j < initialArray.length - 1; j++) {
      let sum = initialArray[j] + initialArray[j + 1]
      tempArr.push(sum);
    }
    // copy over the last element
    let lastElement = initialArray[initialArray.length - 1];
    tempArr.push(lastElement);
    let stringified = tempArr.join(' ');
    console.log(stringified);

    // copy computed values for the next iteration
    initialArray = tempArr.slice();
  }
}

pascalsTriangle(4)

Students and Departments

SELECT
  departments.DEPT_NAME,
  COUNT(students.STUDENT_ID)
FROM
  departments 
  INNER JOIN students 
  ON departments.DEPT_ID = students.DEPT_ID
GROUP BY
  departments.DEPT_NAME
ORDER BY 
  COUNT(students.student_id) DESC,
  departments.DEPT_NAME ASC

Question 3

Will they return the same thing?

  function foo1() {
    return {
      bar: 'Hello'
    };
  }

  function foo2() {
    return 
    {
      bar: 'Hello'
    };
  }

Answer:
No, they do not return the same thing. foo1() return Object and foo2() return undefined. The reason is that by rules and specs of Javascript interpreter if there is nothing after return statement the semicolon is added by interpreter. Here foo2 function technically would run return; which exits the function. In contrast, foo1 would run return { bar: 'Hello' } ;.

Question 4

What does the function __construct do in PHP?

Answer: __construct is a function that gets called when an object gets instantiated. It helps to initialize an object by adding parameters before it is used.

Question 5

Which Javascript framework do you think is the best? Why? Compare at least 2.

Answer: This would be a very heated topic among developers. Everyone has their opinions on this subject and I am no exception here. I think React is the best framework. Let me tell you my story. I head about Angular before I knew React existed. Once I tried to learn it but it was so hard for me that I thought I would never get it. The syntax is so different and it introduces a lot of new concepts. Around the same time that I wanted to learn Angular, there was a lot of hate and dispute about transition between Angular 1 and Angular 2. That turned me off for a while thinking what if I learn something that could be dramatically changed next year and I have to relearn everything. On top of that I hated Typescript. Maybe it was because Microsoft developed it. Let's get into technicality. React has amazing tutorials and documentation. Out of the box you don't need to know a lot of things to get started and appreciate what that framework has to offer. I fell in love with React just because it was simple to implement and I could use it right away. I admit Angular is more powerful and has a lot to offer. But React gives me modularity so I could chose my own libraries such as Redux or MobX. I won't get stuck to one ecosystem that Angular provides. The biggest charm of React is React Native. How amazing could it be if you could develop mobile applications with the same syntax. In conclusion I would say I chose React beacause it offered to open more doors like mobile app development. In the end of the day I am a developer. What differentiates a good developer from a great one?The ability to adopt a new technology. I am very open to learning new technologies and tools that make our lives easier. Learning Angular is in my radar.

Question 6

What is a media query? How is this useful?

Answer: Media queries are used to match characteristics of a device such as screen size. They are crucial part of responsive design since we live in the age of technology where internet connected devices come in various screen sizes. Media queries allow us to modularize our styles and images for specific screen sizes and resolutions. It increases usability and experiece of the site.

Question 7

Describe z-index

Answer: z-index property exists only in positioned elements. A lot of the time our elements overlap and cover each other. In this case z-index takes care of in which order our elements should be shown. Besides that there are a lot of use cases for UX to hide or prioritize certain elements.

Question 8

What does * { box-sizing: border-box; } do? What are its advantages?

Answer: When we add any height or width to an element by default CSS box model sets those parameters to a content of that box. For example, if we give an element a width of 100px and height of 100px, then these parameters are aplied only to box content. That means that if we add a border of 5px and padding of 10px the total height of 130px and width of 130px will be rendered to the screen. In other words it will add these numbers to the height and width of the element. That required tidious manual calculations which can lead to many more layout breakages. Here comes border-box to rescue. It allows us to force the height and width of the element to stay the same. No matter if we add more padding or border it will be calculated by browser and rendered the same height and width we set for the element. The final answer to the question is that * { box-sizing: border-box; } applies border-box property to all elements in the DOM.

Question 9

The 'C' in CSS stands for Cascading. How is priority determined in assigning styles (a few examples)? How can you use this system to your advantage?

Answer: Specificity is one of the hardest part of learning CSS. There are a lot of articles that show you how to calculate specificity, but that rarely comes useful. For basics we have to know several things when it comes to specificity.

  1. style attribute (<div style="width: 100px">) has highest precedence. No matter where else you are trying to change the width it would not work.
  2. ID's are more specific that classes therefore they have higher precedence.
  3. Classes are more specific that html selectors therefore they win the precedence.

Some examples:

Example 1: [ id vs class ]

Let's say we have this:

 <div id="box" class="box"></div>

Then we apply two different styles in a separate file.

 #box {
   width: 200px;
   height: 300px;
   background-color: red;
 }

 .box {
   width: 100px;
   height: 100px;
   background-color: blue;
 }

As a result we will get 200x300 red box. As mentioned previously, id's have higher precedence.

Example 2: [ class vs class ]

We will use previous example but this time we will remove id:

<div class="box"></div>

And use two different styles for the same class name:

.box {
  width: 200px;
  height: 300px;
  background-color: red;
}

.box {
  width: 100px;
  height: 100px;
  background-color: blue;
}

Here the element has the same specificity. In this case latter style overwrites the previous one. So result will be 100x100 blue box.

Example 3: [ style tag vs class ]

Imagine we have the same example, but styles are defined in different locations

<style>
 .box {
    width: 200px;
    height: 300px;
    background-color: red;
  }
</style>
<div class="box"></div>

In a separate file we have this style:

  .box {
    width: 100px;
    height: 100px;
    background-color: blue;
  }

Who wins now? Style tag will have a higher precedence so it's style will be rendered. We will get 200x300 red box.

Final example: [ inline style vs style tag ]

<style>
 .box {
    width: 200px;
    height: 300px;
    background-color: red;
  }
</style>
<div class="box" style="width: 100px; height:100px; background-color: blue;"></div>

Remember I mentioned in the begining that inline CSS has the higher precedence? The result here is obvious. Inline wins the precedence, so we will get 100x100 blue box.

Final Notes
Nowadays we have so many packages and libraries that help us to achieve maximum performance and optimization for our applications. Although it is neccessary to know the rules and standarts, in the end no one will sit and go through thousands lines of CSS code. We can leverage CSS preprocessors such as SASS, LESS and PostCSS alongside tools like Gulp and Webpack to optimize our CSS and inject it to our html files for better loading performance and fewer network requests.

Question 10

Write a program in whatever language you are comfortable with based on below.

We have a set of three tables (for each one schema is followed by the sample data):
1) invoiceheader (
    invoicenum varchar, 
    invoicedate date, 
    invoiceamount float
)

invoicenum | invoicedate | invoiceamount
-----------+-------------+--------------
00551198   | 1/1/2014    | $150.5
00551199   | 1/2/2014    | $10

2) invoicedetail (
    invoicenum varchar, 
    trackingno varchar, 
    detailamount float
)

invoicenum | trackingno         | detailamount
-----------+--------------------+-------------
00551198   | 1Z2F12346861507266 | $50
00551198   | 1Z2F12346861507267 | $80
00551198   | 1Z2F12346861507268 | $20.5
00551199   | 1Z2F12346861503423 | $10.5

3) invoicecharges (
    invoicenum varchar, 
    trackingno varchar, 
    chargetype varchar, 
    chargeamount float
)

invoicenum | trackingno         | chargetype | chargeamount
-----------+--------------------+------------+-------------
00551198   | 1Z2F12346861507266 | FRT        | $40
00551198   | 1Z2F12346861507266 | FUE        | $11
00551198   | 1Z2F12346861507267 | FRT        | $65
00551198   | 1Z2F12346861507267 | FUE        | $17
00551198   | 1Z2F12346861507268 | FRT        | $10
00551198   | 1Z2F12346861507268 | FUE        | $5
00551198   | 1Z2F12346861507268 | HAZ        | $5.5
00551199   | 1Z2F12346861503423 | FRT        | $8
00551199   | 1Z2F12346861503423 | FUE        | $2.5

The relationship between tables: the data set contains invoice with overall invoice amount, list of packages uniquely identified by tracking# in detail table and break down of charges for the tracking#. I.e. Freight, Fuel.

Using the data from the tables above program should generate the following reports:

Report 1
Input parameters: from date and to date
For specified time period print all invoices

  • For each show:
    • invoicenum, invoice date and invoice amount
  • Print a total line:
    • Number of invoices and
    • Total amount for the period

Report 2
Same input as above
For specified time period, print all invoices where the invoice amount does not match the sum of all detailamount column values for this invoice

  • For each show:
    • invoicenum, invoice date and invoice amount, detailamount total and the discrepancy amount

Report 3
Same input as above
For specified time period print all tracking#s where the detailamount does not match the sum of all chargeamount column values for this invoice and trackingno

  • For each show:
    • invoicenum, invoice date, trackingno, detailamount, chargeamount total and the discrepancy amount

Answer: This code is available online to run. Click here

Here is how I organized data that was previously illustrated.

const invoice_amount = [
  {
    invoice_number: '00551198',
    date: new Date('1/1/2014').getTime(),
    invoice_amount: 150.5
  },
  {
    invoice_number: '00551199',
    date: new Date('1/2/2014').getTime(),
    invoice_amount: 10
  }
];

const detail_amount = [
  {
    invoice_number: '00551198',
    date: new Date('1/1/2014').getTime(),
    tracking: [
      {
        tracking_number: '1Z2F12346861507266',
        detail_amount: 50
      },
      {
        tracking_number: '1Z2F12346861507267',
        detail_amount: 80
      },
      {
        tracking_number: '1Z2F12346861507268',
        detail_amount: 20.5
      }
    ]
  },
  {
    invoice_number: '00551199',
    date: new Date('1/2/2014').getTime(),
    tracking: [
      {
        tracking_number: '1Z2F12346861503423',
        detail_amount: 10.5
      }
    ]
  }
];

const charge_amount = [
  {
    invoice_number: '00551198',
    date: new Date('1/1/2014').getTime(),
    charges: [
      {
        type: 'FRT',
        tracking_number: '1Z2F12346861507266',
        charge_amount: 40
      },
      {
        type: 'FUE',
        tracking_number: '1Z2F12346861507266',
        charge_amount: 11
      },
      {
        type: 'FRT',
        tracking_number: '1Z2F12346861507267',
        charge_amount: 65
      },
      {
        type: 'FUE',
        tracking_number: '1Z2F12346861507267',
        charge_amount: 17
      },
      {
        type: 'FRT',
        tracking_number: '1Z2F12346861507268',
        charge_amount: 10
      },
      {
        type: 'FUE',
        tracking_number: '1Z2F12346861507268',
        charge_amount: 5
      },
      {
        type: 'HAZ',
        tracking_number: '1Z2F12346861507268',
        charge_amount: 5.5
      }
    ]
  },
  {
    invoice_number: '00551199',
    date: new Date('1/2/2014').getTime(),
    charges: [
      {
        type: 'FRT',
        tracking_number: '1Z2F12346861503423',
        charge_amount: 8
      },
      {
        type: 'FUE',
        tracking_number: '1Z2F12346861503423',
        charge_amount: 2.5
      }
    ]
  }
];

Solution

let fromDate = '1/1/2014';
let toDate = '1/2/2014';

// HELPER FUNCTIONS
const getTime = time => {
  return new Date(time).getTime();
};

const filterInvoices = (invoice_obj, fromDate, toDate) => {
  return invoice_obj.filter(invoice => {
    if (invoice.date >= fromDate && invoice.date <= toDate) {
      return invoice;
    }
  });
};

// REPORT FUNCTIONS
const printReport1 = (fromDate, toDate) => {
  let date1 = getTime(fromDate);
  let date2 = getTime(toDate);
  let totalAmountCharged = 0;

  // filter results by specified date
  const result = filterInvoices(charge_amount, date1, date2);

  console.log('\nReport 1');
  console.log(`invoiceNum  \t|  invoiceDate  \t|  invoiceAmount`);
  console.log('-'.repeat(56));

  // iterate through the result and compute needed values

  result.forEach(invoice => {
    let invoice_amount = invoice.charges.reduce((acc, curr) => {
      return acc + curr.charge_amount;
    }, 0);
    let formattedDate = new Date(invoice.date).toDateString();
    totalAmountCharged += invoice_amount;
    console.log(`${invoice.invoice_number}  \t|  ${formattedDate}  \t|  $${invoice_amount}`);
  });

  console.log('-'.repeat(56));
  console.log(`Total number of invoices: ${result.length}`);
  console.log(`Total amount charged: $${totalAmountCharged}`);
};

const printReport2 = (fromDate, toDate) => {
  let date1 = getTime(fromDate);
  let date2 = getTime(toDate);

  const result_detail_amount = filterInvoices(detail_amount, date1, date2);
  const result_invoice_amount = filterInvoices(invoice_amount, date1, date2);

  console.log('\nReport 2');
  console.log(`invoiceNum\t|  invoiceDate  \t| invoiceAmount |   detailAmount total  |  discrepancyAmount`);
  console.log('-'.repeat(100));

  result_invoice_amount.forEach(invoice => {
    result_detail_amount.forEach(element => {
      if (invoice.invoice_number === element.invoice_number) {
        let amount = element.tracking.reduce((acc, curr) => {
          return acc + curr.detail_amount;
        }, 0);

        if (amount !== invoice.invoice_amount) {
          let formattedDate = new Date(invoice.date).toDateString();

          console.log(
            `${invoice.invoice_number}\t|  ${formattedDate}\t|  \t$${
              invoice.invoice_amount
            }  \t|  \t  $${amount}  \t|  ${invoice.invoice_amount - amount}`
          );
        }
      }
    });
  });
};

const printReport3 = (fromDate, toDate) => {
  let date1 = getTime(fromDate);
  let date2 = getTime(toDate);

  const result_detail_amount = filterInvoices(detail_amount, date1, date2);
  const result_charge_amount = filterInvoices(charge_amount, date1, date2);

  console.log('\nReport 3');
  console.log(
    `invoiceNum\t|  invoiceDate  \t|  trackingNumber  \t| invoiceAmount | charge total  |  discrepancyAmount`
  );
  console.log('-'.repeat(117));

  result_detail_amount.forEach(invoice => {
    invoice.tracking.forEach(tracking => {
      // take one tracking number and calculate charge amount related to that tracking number.
      result_charge_amount.forEach(element => {
        if (invoice.invoice_number === element.invoice_number) {
          let amount = element.charges
            .filter(charge => charge.tracking_number === tracking.tracking_number)
            .reduce((acc, curr) => {
              return acc + curr.charge_amount;
            }, 0);

          let formattedDate = new Date(invoice.date).toDateString();

          if (tracking.detail_amount !== amount) {
            console.log(
              `${invoice.invoice_number}\t|  ${formattedDate}\t|  ${tracking.tracking_number}\t|  \t$${
                tracking.detail_amount
              }  \t|  \t$${amount}  \t|  \t${tracking.detail_amount - amount}`
            );
          }
        }
      });
    });
  });
};

// INVOKE REPORT FUNCTIONS
printReport1(fromDate, toDate);
printReport2(fromDate, toDate);
printReport3(fromDate, toDate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment