GithubHelp home page GithubHelp logo

yeecai / front-end-trivia Goto Github PK

View Code? Open in Web Editor NEW
0.0 0.0 0.0 241 KB

My collection of knowledge about JS/React/Css...topic interested in Issues.

HTML 5.69% JavaScript 70.32% Vue 10.91% Python 0.46% TypeScript 9.56% Shell 3.06%

front-end-trivia's People

Contributors

yeecai avatar

Watchers

 avatar

front-end-trivia's Issues

microfrontends pros & cons

What is micro frontends, image you can deploy part of your project created by CRA instead a whole one, different projects share npm library

pros:

  1. stack unrelated, each team can choose stack differently or upgrade stack independently
  2. good for name collosion using teamname prefixes ref
  3. if one part of the system failed, others won't be affect?

cons:

  1. complex architecture

EventLoop, setTimeOut vs Promise

JS engine can initiate microtasks

each macrotask queue has a microtask q

function sleep(duration) {
    return new Promise(function(resolve, reject) {
        console.log("b");
        setTimeout(resolve,duration);
    })
}
console.log("a");
sleep(5000).then(()=>console.log("c"));

// setTimeOut -> 2 macro tasks
//a b c

function sleep(duration){
return new Promise(function(resolve){
setTimeout(resolve, duration);
})
}
async function changeColor(duration,color){
document.getElementById("traffic-light").style.background = color;
await sleep(duration);

}
async function main(){
while(true){
await changeColor(3000,"green");
await changeColor(1000, "yellow");
await changeColor(2000, "red");
}
}
main()

//我们现在要实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色,你会怎样编写这个代码呢?欢迎你留言讨论

var r = new Promise(function(resolve, reject){
    console.log("a");
    resolve()
});
setTimeout(()=>console.log("d"), 0)
r.then(() => console.log("c"));
console.log("b")

https://html.spec.whatwg.org/

var elementDefinations = Array.prototype.map.call(document.querySelectorAll(".element"), e => ({
text:e.innerText,
name:e.childNodes[0].childNodes[0].id.match(/the-([\s\S]+)-element:/)?RegExp.$1:null}));
for(let defination of elementDefinations) {

console.log(defination.name + ":")
let categories = defination.text.match(/Categories:\n([\s\S]+)\nContexts in which this element can be used:/)[1].split("\n");
for(let category of categories) {
console.log(category);
}

/*
let contentModel = defination.text.match(/Content model:\n([\s\S]+)\nTag omission in text/html:/)[1].split("\n");
for(let line of contentModel)
console.log(line);
*/
}

for(let defination of elementDefinations) {

//console.log(defination.name + ":")
let categories = defination.text.match(/Categories:\n([\s\S]+)\nContexts in which this element can be used:/)[1].split("\n");
defination.categories = [];
for(let category of categories) {
if(category.match(/^([^ ]+) content./))
defination.categories.push(RegExp.$1);
else
console.log(category)
}

/*
let contentModel = defination.text.match(/Content model:\n([\s\S]+)\nTag omission in text/html:/)[1].split("\n");
for(let line of contentModel)
console.log(line);
*/
}

for(let defination of elementDefinations) {
//console.log(defination.name + ":")
let categories = defination.text.match(/Categories:\n([\s\S]+)\nContexts in which this element can be used:/)[1].split("\n");
defination.contentModel = [];
let contentModel = defination.text.match(/Content model:\n([\s\S]+)\nTag omission in text/html:/)[1].split("\n");
for(let line of contentModel)
if(line.match(/([^ ]+) content./))
defination.contentModel.push(RegExp.$1);
else if(line.match(/Nothing.|Transparent./));
else if(line.match(/^Text[\s\S]*.$/));
else
console.log(line)
}

var dictionary = Object.create(null);

for(let defination of elementDefinations) {
dictionary[defination.name] = defination;
}

DIP

ref 内网域名代替ip,改dns执行完成解耦切换

Javascript float number problem

what:

the classic problem 0.1 + 0.2 !== 0.3

why:

fix:

I tried code like:

export const floatCal = (num1 = 0.1, num2 = 0.2, mark = 'plus') => {
  const num1Digits = (num1.toString().split('.')[1] || '').length
  const num2Digits = (num2.toString().split('.')[1] || '').length
  const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits))
  if (mark === 'plus') {
    return (num1 * baseNum + num2 * baseNum) / baseNum
  } else if (mark === 'minus') {
    return (num1 * baseNum - num2 * baseNum) / baseNum
  }
}

But num1 * baseNum the mutiple operation will still cause overflow, then thanks to MikeMcl, bignumber.js library saved my day.

npm install bignumber.js
export const floatCal = (num1 = 0.1, num2 = 0.2, mark = 'plus') => {
  const _num1 = new BigNumber(num1)
  const _num2 = new BigNumber(num2)
  if (mark === 'plus') {
    return _num1.plus(_num2)
  } else if (mark === 'minus') {
    return _num1.minus(_num2)
  }
}

mongo commands

Commands:

  1. db.test.find().limit(1).sort({$natural:-1}) find the last inserted one

https://stackoverflow.com/questions/15306916/dynamically-create-collection-with-mongoose

Create new database
https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project

Get all databases, trying with this one
https://stackoverflow.com/questions/14822550/getting-list-of-all-databases-with-mongoose
https://stackoverflow.com/questions/20117104/mongodb-root-user

root password

mongosh:

Use admin
db.createUser({user:'admin',pwd:'',roles:["root"]})
db.createUser({user:'admin',pwd:'password',roles:["readWrite"]})
show users

Do you know what's the second parameter of setState?

Got asked during the interview, I didn't know(sad face) so there's the digging:
the 1st one is an updater function you can use when your next state change depends on the last one, then an optional object can be used to when you don't care about the previous state.

setState(updater, [callback])

setState((previousState, currentProps) => { 
// state and props are guarueented to be the latest.
 return {foo: previousState.foo + currentProps.bar}
}

the formal updater vs the optional object as updater
setState({state:1})

the 2nd parameter is a callback will be executed after the setState and re-render so you can do that same operation in componentDidUpdate.

this.setState({ theState: theValue}, ()=> doSthAfterStateChange() )

More, setState will always re-render unlesss shouldComponentUpdate return false, so only call setState when the mutable data is different from before when can't do conditional control in shouldComponentUpdate(), to reduce re-renders.

React docs, Reference2 from medium
to read: why is setState asynchronous

In conclusion: if you need set state base on the previous state, write the updater in a formal way, and if you need to do some sth after the setState use the setState callback or do it in componentDidMount.

css

left div 200px
make the right div fit in the rest of the line
margin -200px
padding 200px

Good code habbits

  1. meaningful variable name
  2. isVisible for boolean type variable
  3. verb for function, like toggleFunction
  4. when merge conflit, be careful, add file one by one instead add .
  5. Use const for constant for readability & maintainability.

C2<script>

  • attributes

    • type: MIME type, it's text/javascript by default, application/x-javascript when transferring Javascript file.
    • async: download immediately the script but should not block other jobsI.g. downloading other resources. So the execution order of different async scripts is not guaranteed, so better don't do anything dom manipulation in the async script.
    • defer: download the script file immediately but delay the execution after the dom is built. Both async n defer work for script file. In theory the execution should be in order but in fact not, so better have only one defer script.
    • the rest:charset-not so important, language-decrepared, src-where the script file comes from, either local or other domain(www.xxx.com).
  • XHTML file can <script/> but not HTML file.

  • if the <script> tag included external script file then the code within the tag won't be executed.

  • in old time, the script tag should be placed in head tag but it might block the render process white downloading for remote script file. so nowadays, it should be placed at the end of the body tag.

C3 Basics

  • JS is case sensitive, test is different from Test, type of is reserved but not typeOf.
  • name is JS should start with_/$/[a-z], others can be a-Z/_/$/0-9.
  • // and /* */
/*
 * this extra 
 * and this extra star mark is unnecessary but for easier to read
 */
  • ; is not necessary but good for performance because the parser need not time to guess where to press the 'enter' button.

inline styles vs css-js vs css modules

inline styles don't have media query, can't do some tricks, and overwrites the class styles, but it's useful when you just want something quick and dirty

css-js is less performant than css modules

#HTTP get

记录一次get带数组的

后端用 Java.util.List 接收

不能直接传 qs.stringify 类型是string,会报错

解决办法

用groupIds = qs.stringify({ groupIds: group }, { arrayFormat: "repeat" })
得到groupIds = groupIds=0&groupIds=1,然后直接url: url/?${groupIds}

https://juejin.cn/post/6860724669062840327

5miutesTypeScript

  1. Translate
    TS build a type-system, create type for variable by it's value.
  2. Declare
  • define an interface then declare the variable with the interface: - [ ] ``
  • with class: - [ ] ``
  • with function: - [ ] ``
  1. Combining types:
  • |(Unions):
    create union type with |
    type myState: 'coding' | 'reading' | 'resting' ,
    type isWinterComing: true | false
    ...
    ;
    provide optional types for function paramater,
    function example(obj: string| string[]) { }
  • generics:
  1. Structural type: aka "duck typing"
    The function will accept it if the variable has same shape with the parameter.

reference

Q:

  1. type vs interface vs class

A:

C3Basics

  • JS is case sensitive, typeof is

Dependencies vs devDependencies

npm install will install both while npm install --production only install packages in dependencies

webpack, jest etc. tools only for helping development and not required in production code can be skipped in production deployment

why do we even need framework?

Without a framework, we can still build everything from scratch with basic JS/CSS/HTML, but gonna be a lot of work, like keeping UI in sync.

frameworks can be a very useful tool provides a lot of feature for a beginner like me, make the developing process shorter.

You can absolutely make your own framework to help to develop.

React: reconciliation
Vue: observer

C5 Date

How new Date() knows the time zone?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.