Salary is too low to resign, interview heart very difficult.

Repeated interview encountered obstacles, daily a quick look.

In my spare time every day, I will sort out some front end test questions into a daily question, and then push them to everyone on the official account. It only takes a few minutes to do a question every day, which will surely help you get a better offer when changing jobs. Today’s article is a sorting out of the good questions in the recent daily questions and some answers shared by my fans. I hope it can help you to share them with more friends. At the same time pay attention to the public number [front-end some play], every morning at 8:40, push a daily question on time.

Subject to a

The title

Now there is a list of pocket money given by my wife every month, but for some reasons, there is no pocket money in some months, as shown in the following data

January, February, May pocket money
{1:200.2:140.5:400}
Copy the code

Please convert the above data format to [200, 140, NULL, NULL, 400, NULL, NULL, NULL, NULL, NULL, NULL, null, null], where the array length is 12, corresponding to 12 months, please improve the following code

const obj = { 1: 200.2: 140.5: 400 };
function translate(obj) {
  // Add the code here
}
// output [200, 140, NULL, NULL, 400, null, null, null, null, null, null, null, null, null]
console.log(translate(obj));
Copy the code

The answer

The answer to this question can have many, the following list of several groups of friends contributed to the answer, for your reference

The answer to a
const obj = { 1: 200.2: 140.5: 400 };
function translate(obj) {
  return  Array.from({ length: 12 }).map((_, index) = > obj[index + 1] | |null);
}
// output [200, 140, NULL, NULL, 400, null, null, null, null, null, null, null, null, null]
console.log(translate(obj));
Copy the code
The answer to the second
const obj = { 1: 200.2: 140.5: 400 };
function translate(obj) {
  return Object.assign(Array(13).fill(null), obj).slice(1);
}
// output [200, 140, NULL, NULL, 400, null, null, null, null, null, null, null, null, null]
console.log(translate(obj));
Copy the code
Answer three
const obj = { 1: 200.2: 140.5: 400 };
function translate(obj) {
   // Add the code here
    let result = Array(12).fill(null)
    Object.entries(obj).forEach(([key, value]) = > {
        result[key - 1] = value;
    });

    return result;
}
// output [200, 140, NULL, NULL, 400, null, null, null, null, null, null, null, null, null]
console.log(translate(obj));
Copy the code

Topic 2

The title

Print the number of 1s in all numbers between 1 and 400. For example, 1 contains one 1, 11 contains two 1s, 20 contains no 1s, and 1 through 21 contains 13 1s.

function getCount() {}/ / output 180
console.log(getCount())
Copy the code

The answer

The answer to a

This answer is more classic, performance is also very good

const sum1s = num= > {
  let numstr
  if(! num)return 0
  if (typeof num === 'string') numstr = num
  else numstr = String(num)

  if (Number(numstr) === 0) return 0

  const curr =
    numstr[0] > 1
      ? 10 ** (numstr.length - 1) +
        numstr[0] * (numstr.length - 1) * 10 ** (numstr.length - 2)
      : sum1s(10 ** (numstr.length - 1) - 1) + 1

  return curr + sum1s(numstr.substr(1))}/ / output 180
console.log(sum1s(400))
Copy the code
The answer to the second

This uses regex, but the performance of regex can be a bit poor for long strings

function countOne(num){
    // num is a positive integer, and the method is a bit violent
    return Array.from({length:num},(v,i) = >i+1).join(' ').replace(/[^1]/g.' ').length
}
console.log(countOne(400))
Copy the code
Answer three

The following is a reasonable answer. Convert each number into a string and count the number of 1s

function getCount() {
  let count = 0
  for(let i=1; i<400; i++) { count = count +`${i}`.split('1').length - 1
  }
  return count
}

/ / output 180
console.log(getCount())
Copy the code

The title three

Hanging curtain painting pavilion painting curtain hanging, who department huai Think huai department who? Shadow lane flower branch flower lane shadow, silk pull willow line liu pull silk. This is a palindrome, meaning that every line is read the same way forward or backward. The following is a palindrome number, which means that the numbers read forward and backward are the same, for example, 11,1221,2112, etc.

The title

Please print all palindrome numbers between 1 and 10000. 1 to 9 are not palindromic numbers because they have only one digit.

The answer

The answer to a
const palindrome = length= > {
  const res = []
  const digits = ['0'.'1'.'2'.'3'.'4'.'5'.'6'.'7'.'8'.'9']

  const add = (current, length) = > {
    if (length <= 1) return
    digits.forEach(digit= > {
      res.push(digit + current + digit)
      add(digit + current + digit, length - 2)
    })
  }
  digits.forEach(num= > {
    add(num, length - 1)
    res.push(num + num)
    add(num + num, length - 2)})return res.filter(num= >! num.startsWith('0'))}// A total of 189
console.log(palindrome(4))
Copy the code
The answer to the second
function palindrome (max) {
  return Array(max + 1).fill(' ').reduce((a, c, i) = > {
    if (i > 10) {
      const arr = Array.from(`${i}`)
      const [x, y] = [`${i}`, arr.reverse().join(' ')]
      x === y && a.push(i)
    }
    return a
  }, [])
}
// A total of 189
console.log(palindrome(10000))
Copy the code
Answer three
const result = [...Array(10000).keys()].filter((x) = >  x> 10 && x === Number(x.toString().split(' ').reverse().join(' ')))console.log(result)
Copy the code

The title four

The title

Implement the function fn in the following code to print all parent ids corresponding to the specified ID and its own ID

const data = [
            {
                id: 1.name: '222'.children: [{
                    id: 2.name: '34'.children: [{
                        id: 112.name: '334'}, {id: 113.name: '354',}]}]}]function fn(id) {}// Output [1, 2, 112]
  console.log(fn(112))
Copy the code

The answer

The answer to a
const data = [
            {
                id: 1.name: '222'.children: [{
                    id: 2.name: '34'.children: [{
                        id: 112.name: '334'}, {id: 113.name: '354',}]}]}]function fn(id) {
  const res = []
  const find = _= > {
    if(! _)return
    return _.find(item= > (item.id === id || find(item.children)) && res.push(item.id))
  }
  find(data)
  return res.reverse()
}

console.log(fn(112))
Copy the code
The answer to the second
const fn = (id, ancestors = [], current = data) = > {
  for (let i = 0; i < current.length; i++) {
    if (current[i].id === id) return ancestors.concat(id)
    if (current[i].children && current[i].children.length) {
      const ret = fn(id, ancestors.concat(current[i].id), current[i].children)
      if (ret) return ret
    }
  }
}

console.log(fn(112))
Copy the code
Answer three
function fn(id) {
  const arr = []
  const getIds = (ids) = > {
    for (const v of ids) {
      arr.push(v.id)
      if (v.id === id) {
        return
      } else if (v.children) {
        getIds(v.children)
      } else {
        arr.pop()
      }
    }
  }
  getIds(data)
  return arr
}

console.log(fn(112))
Copy the code

Topic five

The title

Implement functions to convert entry to output data format

const entry = {
  'a.b.c.dd': 'abcdd'.'a.d.xx': 'adxx'.'a.e': 'ae'
}

// Require conversion to the following objects
const output = {
  a: {
    b: {
      c: {
        dd: 'abcdd'}},d: {
      xx: 'adxx'
    },
    e: 'ae'
  }
Copy the code

The answer

The answer to a
function transform(obj) {
  const res = {}
  for (let [keys, value] of Object.entries(obj)) {
    keys
      .split('. ')
      .reduce((prev, cur, idx, arr) = >
        prev[cur] = prev[cur] || (arr[idx + 1]? {} : value) , res) }return res
}
Copy the code
The answer to the second
const transform = (input: { [P in string]: string }): Object= > {
  const ret = {}
  Object.entries(input).forEach(([keys, val]) = > {
    let root = ret
    keys.split('. ').forEach((key, ind, arr) = > {
      if (ind === arr.length - 1) root[key] = val
      else {
        root[key] = root[key] || {}
        root = root[key]
      }
    })
  })
  return ret
}
Copy the code
Answer three
const entry = {
				'a.b.c.dd': 'abcdd'.'a.d.xx': 'adxx'.'a.e': 'ae',}const convert = (data) = > {
  let res = {}
  const entries = Object.entries(data)
  for (let i = 0; i < entries.length; i++) {
    let temp = res
    let [key, value] = entries[i]
    const everyOne = key.split('. ')
    for (let j = 0; j < everyOne.length; j++) {
      if (j === everyOne.length - 1) {
        temp[everyOne[j]] = value
      }
      temp[everyOne[j]] = temp[everyOne[j]] || {}
      temp = temp[everyOne[j]]
    }
  }
  return res
}
console.log(convert(entry))
Copy the code

conclusion

These daily problems are all programming problems, some of which are problems we might encounter in daily development. By doing these problems, you can also test your mastery of these practical programming skills. The daily question comes from the public account [front-end some play]. It is pushed at 8:40 am every day on time on weekdays. The daily question grows a little bit every day.

conclusion

Don’t blow out your inspiration and your imagination; Don’t be a slave to your model. — Vincent Van Gogh