📜 ⬆️ ⬇️

Tasks with interviews (front-end)

It so happened that during my career as a front-end developer, I visited many interviews. The topic of the interview does not lose its relevance, and in the comments, when it comes to interviews, spears begin to break. I also want to contribute and share the accumulated collection of questions. I beg.

image

Lyrical digression


I am invited to interviews willingly, I don’t know, the reason for this is a pretty photo in a resume or its content. If a summary, then to describe the technology used in each current job, I spend two, three hours. Sometimes I look at others, how they are decorated, and suddenly I will find something useful for myself ...

Tasks


To start something easier.
')
1. There is some string (var str = 'fgfggg';), what happens if we take str [0]?

Answer
str [0] returns the character of the string, which is at the zero index. The string in js is immutable, that is, a character can be read from it, but there is no writing.

2. Implement the methods that in the process of executing the line (2) .plus (3) .minus (1) would give at the output 4.

Answer
Since we are working with numbers, we need to expand the Number prototype with new methods.

Number.prototype.plus = function (value) {
	return this + value;
}

Number.prototype.minus = function (value) {
	return this - value;
}

this plus. , this , . minus.

3. , : « ?»

Array.prototype.sort = function () {}
var t = [2, 1, 22];
t.sort()

— [1, 2, 22], undefined.
, , - , .
prototype.js jQuery.

4. , '*', '1', 'b', '1c', , '1*b*1c'

, , .

function getStr() {
	return [].slice.call(arguments, 1).join(arguments[0])
}


5. , .

, , .

.

var sum = 0;

function getSum(obj) {
	sum += obj.valueNode;
	if (obj.next != null) {
		for (var i = 0; i < obj.next.length; i++) {
			getSum(obj.next[i]);
		}
	}

	return sum;
}

var tree1 = {
				valueNode: 1,
				next: [
					{
						valueNode: 3,
						next: null
					},
					{
						valueNode: 2,
						next: null
					}
				]
			} 

var tree = {
	valueNode: 3,
	next: [{
				valueNode: 1,
				next: null
			},
			{
				valueNode: 3,
				next: null
			},
			{
				valueNode: 2,
				next: null
			},
			{
				valueNode: 2,
				next: [
					{
						valueNode: 1,
						next: null
					},
					{
						valueNode: 5,
						next: null
					}
				]
			}]
};
console.log(getSum(tree1));
sum = 0;
console.log(getSum(tree));

.

function getSum(obj) {
	var arr = [obj],
		sum = 0,
		current;

	while(arr.length > 0) {
		current = arr.shift();
		sum += current.valueNode;

		if (current.next != null) {
			for (var i = 0; i < current.next.length; i++) {
				arr.push(current.next[i]);
			}
		}
	}

	return sum;
}

var tree = {
	valueNode: 3,
	next: [{
				valueNode: 1,
				next: null
			},
			{
				valueNode: 3,
				next: null
			},
			{
				valueNode: 2,
				next: null
			},
			{
				valueNode: 2,
				next: [
					{
						valueNode: 1,
						next: null
					},
					{
						valueNode: 5,
						next: null
					}
				]
			}]
};
getSum(tree)


6. js before, after?

, — , before after, .

, - , .

7. 20X20px , 60px, .





8. (, , )?

, . , body. , inherit, . , body.
border-radius, , , .

9. ?

, . , «» «». , , .
. ul , padding, margin list-style-type. , , .

10. , , , .

body {
  overflow: hidden;
}

.wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: rgba(230, 230, 230, .1);
}

.popup {
  position: absolute;
  width: 400px;
  height: 300px;
  right: 0;
  left: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}


11. .


width: 100px;
height: 100px;
border-right: 1px solid #f00;
border-radius: 0 50% 50% 0;


12. , .

var arr = [{date: '10.01.2017'}, {date: '05.11.2016'}, {date: '21.13.2002'}];

arr.forEach(function(item) {
	var arrDate = item.date.split('.'),
      date = new Date(Number(arrDate[2]), Number(arrDate[1]), Number(arrDate[0]));
      item.time = date.getTime();
});

arr.sort(function (a, b) {
  if (a.time - b.time < 0) {
        return false;
      } else {
        return true;
      }
});

var res = arr.map(function (item) {
  return {date: item.date};
});

console.log(res);


13. , ('', '', '')

var arr = ['kot', 'tok', 'okt'],
	arr1 = ['kot', 'tok', 'ott'];

function sameWords(arr) {
  var word1, word2;
  
  for (var i = 0; i < arr.length-1; i++) {
    word1 = 0;
    word2 = 0;
    
    if (arr[i].length !== arr[i+1].length) {
        return false;   
    } else {
      for (var j = 0; j < arr[i].length; j++) {
        word1 += arr[i][j].charCodeAt(0);
        word2 += arr[i+1][j].charCodeAt(0);
      }
      
      if (word1 !== word2) {
        return false;
      }
    }      
  }
  
  return true;
}

console.log(sameWords(arr));
console.log(sameWords(arr1));



promse, , , .(14, 15, 16)

, js-, callback-, . , Callback Hell, , .

var promis = new Promise(function (resolve, reject) {
	...
	setTimeout(function () {
		resolve(res);
	}, 5000);
});


var promisesImages = [];

for (let i = 0; i < count; i++) {
    promisesImages.push(new Promise((resolveImg, rejectImg) => {
        let img =  new Image(),
            startTime = Date.now();

        img.src = this.imgUrl + '?' + Math.floor(Math.random() * 100000000);

        img.onload = () => {
            resolveImg(Date.now() - startTime);
        };
        img.onerror = rejectImg;
    }));
}

Promise.all(promisesImages)
    .then((timings) => {...})


17. : « ?».

, - - , .

18. . , , , , , , , ?



Callback Hell Promise Hell. ?

function test() {
	return new Promise(function (resolve) {
		setTimeout (function () {
			resolve(1);
		})
	})
}

async function test1() {
	var res = await test();
	console.log(res + 1);
}

test1 «» test. , , - , : « , , , , , callback — , , , , ». , javascript , - , , , , , .

(19) . .
console.log(1);
setTimeout(function() {
	console.log(2);
}, 0)
console.log(3);

, . . : «1, 3, 2. js , setTimeout setInterval, 0, .»
, , , 132, .

(20) setTimeout setInterval . : « ?»

, , . , .


(), , . .
for (var i = 0; i < 10; i++) {
	setTimeout(function () {
		console.log(i);
	}, 100);
}

21. , ( )?

,

for (var i = 0; i < 10; i++) {
	(function (i) {
		setTimeout(function () {
			console.log(i);
		}, 100);
	})(i)
}

, i

for (var i = 0; i < 10; i++) {
	setTimeout(function (i) {
		console.log(i);
	}.bind(this, i), 100);
}

setInterval setTimeout , -
for (var i = 0; i < 10; i++) {
	setTimeout(function (i) {
		console.log(i);
	}, 100, i);
}

es6

for (let i = 0; i < 10; i++) {
	setTimeout(function () {
		console.log(i);
	}, 100);
}

es6, , let {}.

- .

22. , «hello world», , , , , , .

, , , , .

var zero = [].length,
     one = [{}].length,
     two = [,,].length,
    seven = [,,,,,,,].length;

console.log(String.fromCharCode(Number(String(seven) + String(two))));

H, , 10 …

(23) . 1 100 , , , , . O(n^2) .

, (n + 1) / (n / 2).

. .

var sum = 101*50,
     sumArr = eval([4, 2, ... 3, 7].join('+').replace('++', '+')),
     res;
res = sum-sumArr;


, - : « ?»

eval([4, 2, ... 3, 7].join('+')


.

(24) -. , .

function Book(name, author) {
    this.name = name;
    this.author = author;
    return this;
}

function Foo(Book, ' javascript', ' ')

Foo

function Foo(Book, ' javascript', ' '). , - ? Object.create(), . , -, «» Object.create.

function Book(name, author) {
    this.name = name;
    this.author = author;
    return this;
} 

function Foo(Cclass, name, author) {
  return Object.create(Cclass.prototype);
}

var book = Foo(Book, 'js', 'petr');

console.log(book.name); -> undefined

, . -.
, .

function Book(name, author) {
    this.name = name;
    this.author = author;
    return this;
}

function Foo(Cclass, name, author) {
    return Cclass.call({}, name, author);
}

var book = Foo(Book, 'js', 'petr');
console.log(book.name);

.


(25) , . . , , , replace — , , . - , .

function isPalindrom1(str) {
    if (str.toLowerCase().replace(/[^--]/g, '') === str.toLowerCase().replace(/[^--]/g, 
    '').split('').reverse().join('')) {
        return true;
     } else {
        return false;
     }
}

, , .

, - . : «». , . , . , replace — .

, :
function isPalindrom(str) {
    var str = str.toLowerCase(),
          lim = str.length - 1,
          i = 0,
          j = str.length - 1;

    while (i <= lim) {
        if (/[^--]/.test(str[i])) {
            i += 1;
        }
        if (/[^--]/.test(str[j])) {
            j -= 1;
        }
        if (str[i] != str[j]) {
            return false;
        }
        i += 1;
        j -= 1;
   }
   return true;
}
console.log(isPalindrom('     '));

26. js, css? , ?


<script></script>
<style></style>  


<script src="script.js"><script>
<link rel="stylesheet" href="/css/style.css"> 

.

, , . , , js , - , .
, , . .

27. opacity visible: hidden , overflow: hidden?

opacity . 0 1, 0 — , .5 — , 1 — . 0 .
visible: hidden , . opacity, js- .
display: none — , . javascript width, height.
overflow: hidden; — , .


28. f: f(2, 3) -> 5, f(2)(3), 5

 function f(a, b) {
 	if (b !== undefined) {
 		return a + b;
 	} else {
 	return function (b) {
 		return a + b;
 		}
 	}
 }

, , - .

.
f(1)(2)(3)() -> 6, f(0)(3)(1)(5)() -> 8

function f(arg) {
	var value = arg;

	return function (arg) {
		if (arg !== undefined) {
			return f(value + arg);
		} else {
		return value;
		}
	}
}


,

foo(1)(2)(3) -> 6
foo(1)(2)(3)(4) -> 10
foo(-1)(2)(3)(4)(7) -> 15
foo(1)(2)(3)...(n) 1+2+3...+n

, , . , .

function foo(value) {
	var acc = value;
	function addNext(next) {
		acc += next;
		return addNext;
	}
	addNext.toString = addNext.valueOf = function() {
		return acc;
	}
	return addNext;
}


29. : ' live/die'

, on/off, / . , on/off.
bind/unbind

30. JSONP,


, - . ? ajax, . - , , ajax-.
- .
jquery, - «dataType» — «jsonp».
, , js

	var url = 'http://mydomen.com/news.php',
		script = document.createElement('script'),
		callbackName = 'jsonCallback' + Math.randome();

	script.src = url + '?callback' + callbackName;
	window[callbackName] = function(response){
		console.log(response);
	}

	document.header.appendChild(script);

script , src, , . script. . , .
, callbackName , , , .
<script src='http://mydomen.com/news.php?callback0.90428777...'>

-
echo $_REQUEST[callback] + '(' + json_encode($arDate) + ')';

window
 window.jsonCallback0.90428777 -> function (response) {
 	console.log(response);
 }

src GET , jsonp POST

31. CORS?

jsonp, «» , , '*', , , .
jsonp GET .

jsonp «», , . . JSONP , CORS-
<script src="http://bla-bla/get?callback=f'></script>

<? echo $GET['callback'].'('.$date.')';


date
');alert(document.cookie);'


- , .
, json-, .

32. .

1 js-
2 css
3
4
) js css ( , ), - , , , , . expires.
) , . , , , ETag( , ) , , , .
(Last_Modifed), .
) , nginx. . Content-Encoding: gzip
) js .

, .

33. CommonJS AMD ?

, . RequaerJs, ,

define([
	mod1,
	mod2,
	mod3
], function (Mod1, Mod2, Mod3) {
	new Mod1();
	....
});

define — , , , define, callbeck-. , , callbeck-.
Node.Js . :

var mod = requaer('modul');

mod , ,

34. . seven, plus, one, five, minus, two. seven(plus(one())) -> 8. five(minus(two())) -> 3

:

function one(arg){
	if (typeof arg === 'function') {
		return arg(1);
	} else {
		return 1;
	}
}

function seven(arg) {
	if (typeof arg === 'function') {
		return arg(7);
	} else {
		return 7;
	}
}

function plus(arg) {
	return function (a) {
		return a + arg;
	}
}

five, minus, two. , ,

function one(arg) {
	return 1 + (arg || 0);
}

function two(arg) {
	return 2 + (arg || 0);
}

function five(arg) {
	return 5 + (arg || 0);
}

function seven(arg) {
	return 7 + (arg || 0);
}

function plus(arg) {
	return arg;
}

function minus(arg) {
	return -arg;
}


35. .

, , .

var m = [1, 7, 5, 13, 8],
      count = m.length - 1,
      max;
for (var i = 0; i < count; i++) {
    for (var j = 0; j < count - i; j++) {
        if (m[j] > m[j + 1]) {
            max = m[j];
            m[j] = m[j + 1];
            m[j + 1] = max;
        }
    }
}


36. .

. 23+1-, , , , . 51-. .
, wikipedia

var notation = '23+1-', notation1 = '7 2 3 * -', notation2 = '1 2 + 4 * 3 +';
function getComputation(notation) {
    var queue = [], tmp, num1, num2;
    for (var i = 0; i < notation.length; i++) {
        if (/\d+/.test(notation[i]) === true) {
            queue.push(Number(notation[i]));
        }
        else {
            switch (notation[i]) {
                case '+':
                    tmp = queue.pop() + queue.pop();
                    queue.push(tmp);
                    break;
                case '-':
                    num1 = queue.pop();
                    num2 = queue.pop();
                    if (num1 > num2) {
                        tmp = num1 - num2;
                    }
                    else {
                        tmp = num2 - num1;
                    }
                    queue.push(tmp);
                    break;
                case '*':
                    tmp = queue.pop() * queue.pop();
                    queue.push(tmp);
                    break;
                case '/':
                    tmp = queue.pop() / queue.pop();
                    queue.push(tmp);
                    break;
            }
        }
    }
    return queue[0];
}
console.log(getComputation(notation));
console.log(getComputation(notation1));
console.log(getComputation(notation2));

, .

37. div, div, padding 50%, ?

.wrap {
  width: 200px;
  border: 1px solid green;
}

.block {
  width: 200px;
  padding-bottom: 50%;
  border: 1px solid red;
}



, .
, , ?

38. , , .   : "())({}}{()][]["

function validBraces(str) {

	var arrOpenSymbols = [],
		result = false,
		countOpenSymbols;
	if (str.length > 0) {
		for (var i = 0; i < str.length; i++) {
			if (str[i] === '{' || str[i] === '[' || str[i] === '(') {
				arrOpenSymbols.push(str[i]);
			} else {
				countOpenSymbols = arrOpenSymbols.length;
				if ((str[i] === '}' && arrOpenSymbols[(countOpenSymbols-1)] === '{') ||
					(str[i] === ']' && arrOpenSymbols[(countOpenSymbols-1)] === '[') ||
					(str[i] === ')' && arrOpenSymbols[(countOpenSymbols-1)] === '(')
					) {
						arrOpenSymbols.pop();
				}
			}
		}

		if (arrOpenSymbols.length === 0) {
			result = true;
		} else {
			result = false;
		}
	}
	return result;
}
console.log('');
console.log(validBraces('()'));
console.log(validBraces('[)'));
console.log(validBraces('{}[]()'));
console.log(validBraces('([{}])'));
console.log(validBraces('())({}}{()][]['));

'{', '[', ']', '}'

function validBraces(str) {
	try {
	 	eval(str);
	 	return true;
	 } catch (err) {
	 	return false;
	 }
}


39. , div root id.

<div id="root" style="background: red;">
    root
    <span id="id1" style="background: lightblue;">id1</span>
    <div id="id2" style="background: green;">
        id2
        <div id="id3" style="background: yellow;">id3</div>
    </div>
</div>

$('#root').on('click', function (event) {
    event.stopPropogation();
    console.log($(event.target).attr('id'));
})


40. ,
//
var arr = [
 {name: 'width', value: 10}, 
 {name: 'height', value: 20}
]

//
{width: 10, height: 20}

function getObj(arr) {
    var obj = {};
    
    arr.forEach(function(item){
        obj[item.name] = item.value;
    });
    
    return obj;
}


41. ?

var i = 10;
var array = [];

while (i--) {
    (function (i) {
        var i = i;
        array.push(function() {
            return i + i;
        });
    })(i);
}    

console.log([
    array[0](),
    array[1](),
])

[18, 16],

(function (i) {})(i);

, var i = i — .

function() { return i + i; }

i, , . , .

42. . , x

function f() { console.log(this.x); }
var obj = {x: 'bar'};

f.call(obj, a, b);
f.apply(obj, [a, b]);

obj.funk = function f() { console.log(this.x); }
obj.funk();

function f() { console.log(this.x); }.bind(obj, a, b);
f();


43.
function Book() {
    this.name = 'foo'
}

Book.prototype = {
    getName: function() {
        return this.name;
    }
};

var book = new Book();

Book.prototype.getUpperName = function() {
    return this.getName().toUpperCase();
}

book.getUpperName();

?
) , .. ,
) 'FOO'

'FOO'

44. js :
a=3; b=«hello»;
.
)
)
) var — .

) )

45. — typeof (function(){})()
) callback
) method
) undefined
) function

)

46. margin: -10px;


47. 0.1 + 0.2 0.30000000000000004

, .

48. php-,
, , , .

<div class="block1">
  <div></div>
</div>
<div class="block2">
  <div></div>
</div>

.block1 {
  width: 150px;
  height: 20px;
  border: 1px solid red;
}
.block2 {
  display: none;
  width: 100px;
  height: 50px;
  border: 1px solid red;
}

function showBlock() {
  var block1 = document.getElementsByClassName('block1')[0],
      block2 = document.getElementsByClassName('block2')[0];
  if (!(block1.childNodes.length > 0 )) {
    block2.style.display = 'block';
  }
}
document.addEventListener("DOMContentLoaded", function () {
  showBlock();
});


, , - , - , , , .


, , , .
?
?
?

Source: https://habr.com/ru/post/351874/


All Articles