yeecai / front-end-trivia Goto Github PK
View Code? Open in Web Editor NEWMy collection of knowledge about JS/React/Css...topic interested in Issues.
My collection of knowledge about JS/React/Css...topic interested in Issues.
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:
cons:
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")
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;
}
ref 内网域名代替ip,改dns执行完成解耦切换
the classic problem 0.1 + 0.2 !== 0.3
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)
}
}
git rebase -i HEAD~commitCount
pick the first one and squash the laters
git rebase --abort
git rebase --continue
" As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree."
No UI is better than wrong UI
Commands:
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
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.
left div 200px
make the right div fit in the rest of the line
margin -200px
padding 200px
let jsonTemp = yourJson.replace((/([\w+)(:)/g), ""$1"$2")
let correctTemp = jsonTemp.replace((/'/g, """)
transfer irregular object-like string into JSONlike string then, use JSON.parse to turn it into object
Types feature pros cons
DES ,AES... priviate key to encrypt and dencrypt
RSA public key to encrypt and private key to dencrypt
todo
A serious one
attributes
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.
/*
* 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.
yeees
link
function.toString
new Function()()
https://z.itpub.net/article/detail/040A64E02537CC9DE6D95FD0D182ACB4
// eslint-disable-next-line no-unused-vars
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
记录一次get带数组的
后端用 Java.util.List 接收
不能直接传 qs.stringify 类型是string,会报错
解决办法
用groupIds = qs.stringify({ groupIds: group }, { arrayFormat: "repeat" })
得到groupIds = groupIds=0&groupIds=1,然后直接url: url/?${groupIds}
p.then(null, c) === p.catch(c)
type myState: 'coding' | 'reading' | 'resting'
,type isWinterComing: true | false
function example(obj: string| string[]) { }
Q:
A:
function multiplier(factor) {
return number => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));
// -> 10
let wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
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 {} as an empty object no"emtpy" enough?
ctrl + r repeatedly can go up to last option
https://unix.stackexchange.com/questions/73498/how-to-cycle-through-reverse-i-search-in-bash
It might cause memory leaks & performance sucks
more event handler more function refer
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
How new Date() knows the time zone?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.