Bonjour. OTUS relance une gamme complÚte de cours JavaScript en septembre. Pour le moment, vous pouvez regarder une leçon ouverte pour le développeur JavaScript. Cours professionnel , ainsi que vous inscrire aux journées portes ouvertes pour le développeur React.js et le développeur JavaScript. Cours de base . Eh bien, nous partageons traditionnellement avec vous la traduction de documents utiles.
Entretien frontal (en 2 parties)
1. Questions qui m'ont été posées lors des entretiens préliminaires.
2. Ressources pour préparer un entretien (pour le poste de développeur front-end).
Questions posées lors des entretiens frontaux
, COVID-19. , .
.
JS
, . .
JS
1. N, . array
.
:
/**
* [1,2,[3,4]] -> [1,2,3,4]
*/
let arr = [1,2,[3,4, [5,6, [7, [8, 9, 10]]]]]
function flatten(arr) {
return arr.reduce(function(acc, next){
let isArray = Array.isArray(next)
return acc.concat(isArray ? flatten(next) : next)
}, [])
}
if (!Array.prototype.flatten) {
Array.prototype.flatten = function() {
return flatten(this)
}
}
console.log(arr.flatten());
2.
:
class CustomPromise {
state = "PENDING"
value = undefined
thenCallbacks = []
errorCallbacks = []
constructor(action) {
action(this.resolver.bind(this), this.reject.bind(this))
}
resolver(value) {
this.state = "RESOLVED"
this.value = value
this.thenCallbacks.forEach((callback) => {
callback(this.value)
})
}
reject(value) {
this.state = "REJECTED"
this.value = value
this.errorCallbacks.forEach((callback) => {
callback(this.value)
})
}
then(callback) {
this.thenCallbacks.push(callback)
return this
}
catch (callback) {
this.errorCallbacks.push(callback)
return this
}
}
let promise = new CustomPromise((resolver, reject) => {
setTimeout(() => {
const rand = Math.ceil(Math.random(1 * 1 + 6) * 6)
if (rand > 2) {
resolver("Success")
} else {
reject("Error")
}
}, 1000)
})
promise
.then(function(response){
console.log(response)
})
.catch(function(error){
console.log(error)
})
3. , . .
:
// O(M)
function getMovies() {
return []; // [{id, name, year}]
}
// O(R)
function getRatings() {
return []; // [{id, movie_id, rating}] 0 <= rating <= 10 // e.g 9.3
}
/**
* minAvgRating ->
* avgRating >= minAvgRating
*
* sort ->
* name -> ascending order movies by name
* -name -> descending
*
* avgRating
*
*
* search ->
* 'ave' -> 'Avengers'
* 'avengers' -> 'Avengers'
* 'AvengersInfinitywar' -> 'Avengers'
*/
const toLower = str => str.toLocaleLowerCase()
const getAvrgRating = (movie, movingWithRatings) => {
let count = 0;
return movingWithRatings.reduce((acc, value, index) => {
const movieMatch = movie.id === value.movie_id
if (movieMatch) {
acc+=value.rating
count++
}
if (index === movingWithRatings.length - 1) {
acc = acc/count
}
return acc
}, 0)
}
const isSubString = (str1, str2) => {
str1 = toLower(str1.split(" ").join(""))
str2 = toLower(str2.split(" ").join(""))
if (str1.length > str2.length) {
return str1.startWith(str2)
} else {
return str2.startWith(str1)
}
}
const moviesList = getMovies()
const movingWithRatings = getRatings();
function queryMovies({ search, sort, minAvgRating }) {
let filteredMovies = movingWithRatings.filter(movie => getAvrgRating(movie, movingWithRatings) >= minAvgRating);
filteredMovies = filteredMovies.map(movie => moviesList.filter(listItem => listItem.id === movie.movie_id).pop())
filteredMovies = filteredMovies.filter(movie => isSubString(toLower(movie.name), toLower(search)))
filteredMovies = filteredMovies.sort((a, b) => {
const isDescending = sort[0] === '-' ? true : false
let sortCopy = isDescending ? sort.slice(1) : sort
const value1 = a[sortCopy]
const value2 = b[sortCopy]
if (isDescending) {
return value1 > value2 ? -1 : 1
}else {
return value1 < value2 ? -1 : 1
}
})
filteredMovies = filteredMovies.map(movie => ({
...movie,
avgRating: movingWithRatings.filter(ratedMovie => ratedMovie.movie_id === movie.id)[0].rating
}))
return filteredMovies
}
4.
URL- . .
, . .
//service.js
const POSTS_URL = `https://jsonplaceholder.typicode.com/posts`;
const COMMENTS_URL = `https://jsonplaceholder.typicode.com/comments`;
export const fetchAllPosts = () => {
return fetch(POSTS_URL).then(res => res.json());
};
export const fetchAllComments = () => {
return fetch(COMMENTS_URL).then(res => res.json());
};
import { fetchAllPosts, fetchAllComments } from "./service";
const fetchData = async () => {
const [posts, comments] = await Promise.all([
fetchAllPosts(),
fetchAllComments()
]);
const grabAllCommentsForPost = postId =>
comments.filter(comment => comment.postId === postId);
const mappedPostWithComment = posts.reduce((acc, post) => {
const allComments = grabAllCommentsForPost(post.id);
acc[post.id] = allComments;
return acc;
}, {});
console.log("mappedPostWithComment ", mappedPostWithComment);
};
fetchData();
5. getHashCode
string. .
:
let s1 = "sample"
if (!String.prototype.getHashCode) {
String.prototype.getHashCode = function(){
console.log('String instance ', this)
return this
}
}
6. ?
1+true
true+true
â1â+true
â2â > â3â
âtwoâ>âthreeâ
:
2
2
1true
false
true
7. bind
reduce
.
:
//bind
if (!Function.prototype.bind) {
Function.prototype.bind = function(...arg){
const func = this
const context = arg[0]
const params = arg.slice(1)
return function(...innerParam) {
func.apply(context, [...params, ...innerParam])
}
}
}
//reduce
Array.prototype.reduce = function(func, initState) {
const arr = this
const callback = func
let init = initState
arr.forEach(function(value, index){
init=callback(init, value)
})
return init
}
8. debounce
:
const debounce = function(func, interval) {
let timerId;
return function(e){
clearTimeout(timerId)
timerId = setTimeout(function(){
func.apply()
}, interval)
}
}
debounce(apiCall, 3000)
9. throttle
:
const throttle = (callback, interval) => {
let timerId;
let allowEvents = true;
return function() {
let context = this;
let args = arguments;
if (allowEvents) {
callback.apply(context, args)
allowEvents = false;
timerId = setTimeOut(function(){
allowEvents = true
}, interval)
}
}
}
10. API. API . API , . .
, . .
:
// setInterval, throttle
setInterval=>Endpoint=>Render
//
//Endpoint=>Render=>setTimeout=>Endpoint=>Render=>SetTimeout...
11. , , ES5.
class Parent(name){
constructor(name) {
this.name=name
}
getName(){return this.name}
}
class Children extends Parent {
constructor(props){
super(props)
}
}
:
function Parent(name) {
this.name = name
}
Parent.prototype.getName = function() {
return this.name
}
function Children(name){
Parent.call(this, name)
}
Children.prototype = new Parent()
12. ?
//Q.1
var x = 1;
var y = x;
x = 0;
console.log(x, y);
//Q.2
var x = [1];
var y = x;
x = [];
console.log(x,y);
//Q.3
function Abc() { console.log(this); };
Abc()
new Abc();
//Q.4
var x = 1;
var obj = {
x: 2,
getX: function () {
return console.log(this.x);
}
};
obj.getX()
let a = obj.getX
console.log(a)
//Q.5
// 2 a ?
//Q.6
console.log("A");
setTimeout(() => console.log("B"), 0);
setTimeout(() => console.log("C"), 0);
console.log("D");
//Q.7
setTimeout(function() {
console.log("A");
}, 0);
Promise.resolve().then(function() {
console.log("B");
}).then(function() {
console.log("C");
});
console.log("D");
//Q.8
let obj1 = {
a:1,
b:2
}
function mutate(obj) {
obj = {a:4, c:6}
}
console.log(obj1)
mutate(obj1)
console.log(obj1)
:
//A.1
0 1
//A.2
[] [1]
//A.3
window
//A.4
2 1
//A.5
a.call(obj);
//A.6
A, D, B , C
//A.7
D, B, C, A
//A.8
{ a: 1, b: 2 }
{ a: 1, b: 2 }
13. . .
const list = [1,2,3,4,5,6,7,8]
const filteredArray = list.filter(between(3, 6)) // [4,5]
:
function between(start, end) {
return function (value,index) {
return value>start && value<end
}
}
1. .
A := 1
B := A*2 + 2
C := B*2 + 3 ...
, :
, ;
, 'GREP', , (. . G + R + E + P) ;
, ( 32- ).
. , , . .
:
//A = 1
//B = A*2 +2
//C = B*2+ 3
//D = C*2+ 3
var genCharArray = function(charA, charZ) {
var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
for (; i <= j; ++i) {
a.push(String.fromCharCode(i));
}
return a;
}
var charMap = {};
var charArray = genCharArray('a', 'z');
charArray.forEach(function(char, index){
charMap[char] = Number(index + 1);
});
var charSequence = function(char){
if(typeof char==="string"){
char = charMap[char];
}
if(char==1){
return 1;
}else{
return char + 2 * charSequence(char-1);
}
}
var input = process.argv[2];
if(input.length===1){
console.log(charSequence(charMap[input]));
}else if(input.length>1){
var charTotalSequence = input.split("").reduce(function(acc, curr){
return acc + charSequence(charMap[curr]);
},0);
console.log(charTotalSequence);
}
2. , .
:
let nums = [2, 7, 10, 1, 11, 15, 9]
let target = 11
let numsMap = new Map()
let pairs = nums.reduce((acc, num) => {
let numToFind = target - num
if (numsMap.get(numToFind)) {
return [...acc, [num, numToFind]]
} else {
numsMap.set(num, true)
return [...acc]
}
}, [])
console.log("Pairs ", pairs)
3. . â , , . O(n). , .
:
let x = [1, 2, 3, 5, 4] //: 5
if x.length == 1 return x[0]
else
let i = 1
for(;i<x.length-1;i++){
if x[i-1]<x[i] and x[i] > x[i+1] return x[i]
}
if x.length - 1 == i return x[i]
4. 90 . , ( in-place, « »).
:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
// .
// .
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
// .
// .
[
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
// 90 .
5. M.
6. , .
:
let x = [1, 2, 3, 4, 5]
let target = 7
let found = []
const twoPointer = (l ,r, current) => {
while(l<r){
const totalSum = current + x[l] + x[r]
if (totalSum === target) {
found.push([current, x[l], x[r]])
return
} else if (totalSum > target) {
r--
} else {
l++
}
}
}
const threeSum = (x, target) => {
for (let i=0;i<x.length;i++) {
const current = x[i];
let leftPointer = i+1
let rightPointer = x.length - 1
if (current+x[leftPointer]+x[rightPointer] === target) {
found.push([current, x[leftPointer], x[rightPointer]])
} else {
twoPointer(leftPointer, rightPointer, current)
}
}
return found
}
7. k. , k .
:
const subStrHasSameCharCount = (str, startIndex, endIndex, totalHop) => {
let charMap = {}
for (let k=startIndex;k<endIndex;k++) {
let currentChar = str[k]
if (charMap[currentChar]) {
charMap[currentChar]++
} else {
charMap[currentChar] = 1
}
}
let totalCount = Object.values(charMap).length > 0
return totalCount ? Object.values(charMap).every(item => item == totalHop) : false
}
const characterWithCountK = (str, k) => {
if (k == 0) return ''
let count = 0
let initialHop = k
while (initialHop < str.length) {
for (let j=0;j<str.length;j++) {
let startIndex = j
let endIndex = j + initialHop
if(endIndex > str.length) continue
count = subStrHasSameCharCount(str, startIndex, endIndex, k)
? count + 1: count
}
initialHop+=k
}
count = subStrHasSameCharCount(str, 0, initialHop, k)
? count + 1: count
return count
}
let str = 'aabbcc'
let k = 2
console.log(characterWithCountK(str, k))
8. â s1 s2, a z . , s1 , .
:
let s1 = 'dadbcbc'
let s2 = 'ccbbdad'
let charMap = {}
const canBeRearranged = (s1, s2) => {
if(s1.length!==s2.length){
return false
}
for(let i=0;i<s1.length;i++){
const charFromString1 = s1[i]
const charFromString2 = s2[i]
if(charFromString1 in charMap){
charMap[charFromString1]++
} else {
charMap[charFromString1] = 1
}
if(charFromString2 in charMap){
charMap[charFromString2]--
} else {
charMap[charFromString2] = -1
}
}
for(let x in charMap){
if (charMap[x]!==0){
return false
}
}
return true
}
canBeRearranged(s1, s2)
9. . .
:
const swap = (index1, index2, arr) => {
let temp = arr[index1]
arr[index1] = arr[index2]
arr[index2] = temp
}
const shuffle = (arr) => {
let totalLength = arr.length
while(totalLength > 0) {
let random = Math.floor(Math.random() * totalLength)
totalLength--
swap(totalLength, random, arr)
}
return arr
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = shuffle(arr)
10. .
:
let arr = [4, 5, 7, 8, [5, 7, 9, [3, 5, 7]]]
let sum = 0
const calculateSum = (arr) => {
arr.reduce(function(acc, currentVal) {
const isEntryArray = Array.isArray(currentVal)
if (isEntryArray) {
return acc.concat(calculateSum(currentVal))
} else {
sum+=currentVal
return acc.concat(currentVal)
}
}, [])
}
calculateSum(arr)
console.log(sum)
11. .
:
const obj = {
level1: {
level2: {
level3: {
more: 'stuff',
other: 'otherz',
level4: {
the: 'end',
},
},
},
level2still: {
last: 'one',
},
am: 'bored',
},
more: 'what',
ipsum: {
lorem: 'latin',
},
};
var removeNesting = function(obj, parent){
for (let key in obj){
if (typeof obj[key] === "object") {
removeNesting(obj[key], parent+"."+key)
} else {
flattenedObj[parent+'.'+key] = obj[key]
}
}
}
let flattenedObj = {}
const sample = removeNesting(obj, "");
console.log(flattenedObj);
12. json, , , . .
13. , ( ). .
:
const employeesData = [{
id: 2,
name: ' ( )',
reportees: [6]
}, {
id: 3,
name: ' ( )',
reportees: []
}, {
id: 6,
name: ' ( )',
reportees: [9]
}, {
id: 9,
name: ' ( )',
reportees: []
}, {
id: 10,
name: ' ( )',
reportees: [2, 3],
}];
/*
A ( )
----B ( )
--------D ( )
------------E ( -)
----C ( )
*/
const findCeo = (currentEmp) => {
let parentEmployee = employeesData.filter(emp => emp.reportees.indexOf(currentEmp.id) > -1)
if (parentEmployee && parentEmployee.length > 0) {
return findCeo(parentEmployee[0])
} else {
return currentEmp
}
}
const logHierarchy = (currentEmp, indent) => {
console.log("-".repeat(indent) + currentEmp.name)
indent+=4;
for(let i=0;i <currentEmp.reportees.length;i++) {
let employee = employeesData.filter(emp => emp.id === currentEmp.reportees[i])
logHierarchy(employee[0], indent)
}
}
const traverse = (employee) => {
let ceo = findCeo(employee)
logHierarchy(ceo, 0)
}
traverse(employeesData[0])
14.
const inputMatrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11,12,13,14,15],
[16,17,18,19,20],
]
const exprectOutput = [1,2,3,4,5,10,15,20,19,18,17,16,11,6,7,8,9,14,13,12]
:
function spiralParser(inputMatrix){
const output = [];
let rows = inputMatrix.length;
let cols = rows > 0 ? inputMatrix[0].length : 0;
//singleEmptyRow => Edge case 1 //[]
if (rows === 0) {
return []
}
if (rows === 1) {
//singleElementRowNoCol => Edge case 2 //[[]]
if (cols === 0) {
return []
} else if (cols === 1){
//singleElementRow => Edge case 3 //[[1]]
output.push(inputMatrix[0][0])
return output
}
}
let top = 0;
let bottom = rows - 1;
let left = 0;
let right = cols - 1;
let direction = 0;
//0 => left->right
//1 => top->bottom
//2 => right->left
//3 => bottom->top
while(left <= right && top <= bottom) {
if(direction === 0) {
//left->right
for (let i=left; i<=right;i++) {
output.push(inputMatrix[top][i])
}
top++;
} else if (direction === 1) {
//top->bottom
for (let i=top; i<=bottom;i++) {
output.push(inputMatrix[i][right])
}
right--
} else if (direction === 2) {
//right->left
for (let i=right; i>=left;i--) {
output.push(inputMatrix[bottom][i])
}
bottom--
} else if (direction === 3) {
//bottom->top
for (let i=bottom; i>=top;i--) {
output.push(inputMatrix[i][left])
}
left++
}
direction = (direction + 1) % 4
}
return output;
}
console.log(spiralParser(inputMatrix2))
15. .
let str = 'bbbaaaaccadd'; // (4) a
:
//
maxNow = 1 1 ? 1 : 0
maxOverall = 1 1 ? 1 : 0
1
maxNow++ // 1
maxOverall = max(maxOverall, maxNow)
maxNow = 1
16. . (2) .
let inputArr = [2,9,1,5,2,3,1,2,7,4,3,8,29,2,4,6,54,32,2,100]
//ouput => [9,1,5,3,1,7,4,3,8,29,4,6,54,32,100,2,2,2,2,2]
:
let slowRunner = 0
for (let fastRunner=0;fastRunner<arr.length;fastRunner++) {
if (arr[fastRunner]!==2 && arr[slow] == 2) {
[arr[fastRunner], arr[slow]] = [arr[slow], arr[fastRunner]]
slowRunner++
}
}
17.
// = 1 -> 2 -> 3 -> 4 -> 5 -> 6
// = 1 <- 2 <- 3 <- 4 <- 5 <- 6
:
//
let current = head
let prev = null
let next = null
while(current) {
next = current.next
current.next = prev
prev = current
current = next
}
18. ( )
:
//
const preorder = (root) => {
let stack = []
stack.push(root)
( stack ) {
let current = stack.pop()
console.log(current.value)
if (current.right) {
stack.push(current.right)
}
if (current.left) {
stack.push(current.left)
}
}
}
1. , .
N . .
.
: , , .
:
;
;
.
.
:
/;
.
:
;
;
SOLID.
2. React- Ping
, API URL. 200, , . , , .
dev tools.
3. json
. id
. .
4. JavaScript Excel,
. 40 .
5. .
user () .
id:
:
: ,
:
:
.
.
:
, . .
.
, , .
( , . , .)
YouTube
, .
.
( ) .
1. ? ()
2. ()
3. ?
4. React- ?
5. - (-)?
6. - ?
7. .
8. CORS?
9. React.
10. connect Redux?
11. PureComponent React?
: