当前位置:网站首页>Yyds dry goods inventory [practical] simply encapsulate JS cycle with FP idea~
Yyds dry goods inventory [practical] simply encapsulate JS cycle with FP idea~
2022-07-03 22:38:00 【Nuggets Anthony】

This article brings FP The idea of functional programming is JS【 loop 】 Application in .
Idle time , blunt (づ ̄3 ̄)づ╭~
Usually , Write a loop :
for (let i=9; i<=22; i++) {
// do something with i
}
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
perhaps :
let i = 9;
while (i <= 22) {
// do something with i
i++;
}
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
What's wrong with that ?
Says there is , There are QAQ
- Prone to marginal problems —— It's also called “off-by-one” Bug, Almost a mistake . Such as omission
<Number ; - If the index i change , Loops can cause errors ( Then why i Easy to change ? Because for loops , such as while structure , Indexes i It's an external variable , The modification of external variables is not controlled by the inside of the loop ;)
- The code is too long , The loop structure may be longer than the function code of the operation ;
therefore , We try to use FP The idea of functional programming is to transform the loop ~
The expectations after the transformation are similar :
range(9, 22).forEach(i => {
/* do something with i */
})
Copy code
- 1.
- 2.
- 3.
- 4.
range Function implementation :
const range = (from, to) => {
const arr = [];
do {
arr.push(from);
from++;
} while (to >= from);
return arr;
};
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
range(9,22) Unfolding is [9, 10, 11, … 22], If , Want to reverse the array , such as :range(12,4) Expand yes [12,11,10...4]
const range = (from, to, step = Math.sign(to - from)) => {
const arr = [];
do {
arr.push(from);
from += step;
} while ((step > 0 && to >= from) || (step < 0 && to <= from));
return arr;
};
range(12,4)
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
such , We made a simple package !
There's another problem —— At present, it is written like this , The cycle is uncontrolled . That is, we can't stop the cycle or jump out of the cycle at will ;
To solve this problem , Try to adopt .some(fn) Instead of .forEach(fn);
-
some() Method to test if there are at least 1 Elements passed the provided function test . What it returns is a Boolean Type value .
e.g.
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
as long as Fn The function returns false , The cycle will continue ; When it comes back true when , The cycle will end .
At the same time with the help of generators, Every time you call , It will generate a return value ;
range() The function evolves as follows :
function* range(from, to, step = Math.sign(to - from)) {
do {
yield from;
from += step;
} while ((step > 0 && to >= from) || (step < 0 && to <= from));
}
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
for (const i of range(9, 22)) { i => {
...
...
if (someCondition) continue;
...
if (somethingElse) break;
...
...
}
}
// Or assign an array
const arrayFrom9To22 = [...range(9, 22)];
// this produces [9, 10, 11, ... 22]
Copy code
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
In this way , You can even assign an array range(9,999999999999) Memory will not explode , Because it passes through generators Generate , It's inert. ; MDN- iterator Have a show :
Javascript The most common iterators in are Array iterator , It just returns each value in the associative array in order . Although it's easy to imagine that all iterators can be represented as arrays , But that's not the case . Array must be fully allocated , But iterators are only used when necessary , Therefore, it can represent a sequence of infinite size , for example 0 And infinity .
Summary : adopt FP Functional programming thinking is right “ loop ” It's simply packaged , Make the code more readable and extensible , The needle doesn't poke
边栏推荐
- SDMU OJ#P19. Stock trading
- 6.2 normalization 6.2.5 third normal form (3NF)
- Exness: the Central Bank of England will raise interest rates again in March, and inflation is coming
- BUUCTF,Misc:LSB
- finalize finalization finally final
- [golang] leetcode intermediate - alphabetic combination of island number and phone number
- Codeforces Round #768 (Div. 1)(A-C)
- Rest reference
- AST (Abstract Syntax Tree)
- Buuctf, misc: n solutions
猜你喜欢

1 Introduction to spark Foundation
![[automation operation and maintenance novice village] flask-2 certification](/img/9a/a9b45e1f41b9b75695dcb06c212a69.jpg)
[automation operation and maintenance novice village] flask-2 certification

The difference between SRAM and DRAM

Summary of fluent systemchrome

Format cluster and start cluster

webAssembly

Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?

2022 electrician (elementary) examination questions and electrician (elementary) registration examination

Shiftvit uses the precision of swing transformer to outperform the speed of RESNET, and discusses that the success of Vit does not lie in attention!

Data consistency between redis and database
随机推荐
WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
Cesium terrain clipping draw polygon clipping
WiFi 2.4g/5g/6g channel distribution
4 environment construction -standalone ha
Is it safe and reliable to open an account and register for stock speculation? Is there any risk?
Mysql database - Advanced SQL statement (I)
finalize finalization finally final
Market layout planning and latest dynamic analysis report of China's smart public security industry Ⓕ 2022 ~ 2028
Sow of PMP
Weekly leetcode - nc9/nc56/nc89/nc126/nc69/nc120
Exness: the Central Bank of England will raise interest rates again in March, and inflation is coming
Correlation
[dynamic programming] Jisuan Ke: Jumping stake (variant of the longest increasing subsequence)
DR882-Qualcomm-Atheros-QCA9882-2T2R-MIMO-802.11ac-Mini-PCIe-Wi-Fi-Module-5G-high-power
Harbor integrated LDAP authentication
DR-NAS26-Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-5GHz-high-power-Mini-PCIe-Wi-Fi-Module
Buuctf, web:[geek challenge 2019] buyflag
[SRS] build a specified version of SRS
Wisdom tooth technology announced that it had completed the round D financing of US $100million and had not obtained a valid patent yet
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch