Skip to content

Test for front end engineers

Daisho Komiyama edited this page Jun 29, 2020 · 10 revisions

I'm starting with a warm-up exercise.

Create a function to reverse a string

My answer

// reverse('Hello'); // olleH
const testString = "Hello";

function reverse(str) {
    const len = str.length;
    let newstr = "";

    for (let i = (len - 1); i >= 0; i--) {
        newstr += str[i];
    }
    return newstr;
}

reverse(testString);

Example answer

// reverse('Hello'); // olleH
const testString = "Hello";

function reverse(str) {
    return str.split("").reverse().join("");
}

reverse(testString);

Create a function that takes a string and returns a new string with duplicates removed.

My answer

const str = "This is is a test test string";

function removeDuplicates(str) {
    const arr = str.split(" ");

    return arr.filter(item => {
        for (let i = 0; i < arr.length; i++) {
            if (item === arr[i]) {
                return = item === arr[i] ? false : true;
            }
        }
    }).join(" ");
}

removeDuplicates(str);

Example answer

const str = "This is is a test test string";

function removeDuplicates(str) {
  const arr = str.split(" ");

  const set = new Set(arr);
  const newString = [...set].join(" ");

  return newString;
}

console.log(removeDuplicates(str));

Without using .flat(), create a function to flatten an array

My answer

const arr = [1, 2, [3, 4, [5, 6, 7], 8], 9, 10];
const newarray = [];

function flatten(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (!Array.isArray(arr[i])) {
      newarray.push(arr[i]);
    }
    else {
      flatten(arr[i]);
    }
  }
  return newarray;
}

console.log(flatten(arr));

Example answer

const arr = [1, 2, [3, 4, [5, 6, 7], 8], 9, 10];
const newarray = [];

function flatten(arr) {
  return arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      acc = [...acc, ...flatten(item)];
    }
    else {
      acc.push(item);
    }
    return acc;
  }, []);
}

console.log(flatten(arr));
Clone this wiki locally