Mozio Interview

by ramsunvtech

HTML

<ul class="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<ul class="list2">
    <li>Text</li>
    <li>Text</li>
    <li>Text</li>
    <li>Text</li>
    <li>Text</li>
</ul>

<form name="myForm" action="">
    <label>
        <input name="username" placeholder="Name" type="text" required>
    </label>
    <label>
        <input name="email" placeholder="Email" type="email" required>
    </label>
    <button>Submit</button>
</form>

JavaScript

/***********************************************\
 * Mozio JavaScript challenge
 * Browser support is irrelevant here, but any comments on specific
 * methods you use is a plus to show deeper understanding of the language
\***********************************************/

/**
 * Task 1: Write a function that repeats the String
 * with the following output:
 * 'Mozio'.repeatString(3); // 'MozioMozioMozio';
 */
 String.prototype.repeatString = function(count) {
  'use strict';

  // When String is null, throw a TypeError
  if (this == null) {
    throw new TypeError('can\'t convert ' + this + ' to object');
  }

  // Convert this to actual String.
  let str = '' + this;

  // To convert string to integer.
  count = +count;

  // Check if its NaN (Not an Nunber).
  if (count != count) {
    count = 0;
  }

  // Check if its Lesser than Zero.
  if (count < 0) {
    throw new RangeError('repeatString count must be non-negative');
  }

  if (count == Infinity) {
    throw new RangeError('repeatString count must be less than infinity');
  }

  // To the Largest integer lesser than or equal to given number.
  count = Math.floor(count);
  if (str.length == 0 || count == 0) {
    return '';
  }

  // Ensuring count is a 31-bit integer allows us to heavily optimize
  // strings 1 << 28 chars or longer, so:
  if (str.length * count >= 1 << 28) {
    throw new RangeError('repeatString count must not overflow maximum string size');
  }

  let maxCount = str.length * count;
  count = Math.floor(Math.log(count) / Math.log(2));
  while (count) {
      str += str;
      count--;
  }
  str += str.substring(0, maxCount - str.length);
  return str;
}

console.log('Mozio'.repeatString(3));

/**
 * Task 2: Could you find a way to optimize the following code?
 */
(function() {
  const $ = (selector) => document.querySelectorAll(selector);
  
  function logContent() {
    console.log(this.innerHTML);
  }

  let list = $('.list li');

  for (let i = 0; i < list.length; i++) {
    let item...