当前位置:网站首页>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
边栏推荐
- pivot ROP Emporium
- 33 restrict the input of qlineedit control (verifier)
- What are the common computer problems and solutions
- WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
- finalize finalization finally final
- Report on the current situation and development trend of ethoxylated sodium alkyl sulfate industry in the world and China Ⓞ 2022 ~ 2027
- SDMU OJ#P19. Stock trading
- Plug - in Oil Monkey
- 2 spark environment setup local
- How to solve win10 black screen with only mouse arrow
猜你喜欢

The overseas listing of Shangmei group received feedback, and brands such as Han Shu and Yiye have been notified for many times and received attention

Unique in China! Alibaba cloud container service enters the Forrester leader quadrant

Redis single thread and multi thread
![[Android reverse] use the DB browser to view and modify the SQLite database (copy the database file from the Android application data directory | use the DB browser tool to view the data block file)](/img/6e/3ffa91154a718b6ace6c8ca87c5995.jpg)
[Android reverse] use the DB browser to view and modify the SQLite database (copy the database file from the Android application data directory | use the DB browser tool to view the data block file)

Programming language (1)

The latest analysis of R1 quick opening pressure vessel operation in 2022 and the examination question bank of R1 quick opening pressure vessel operation

4 environment construction -standalone ha

How to switch between dual graphics cards of notebook computer

QGIS grid processing DEM data reclassification

Flutter internationalized Intl
随机推荐
Creation of the template of the password management software keepassdx
[Android reverse] use the DB browser to view and modify the SQLite database (copy the database file from the Android application data directory | use the DB browser tool to view the data block file)
The overseas listing of Shangmei group received feedback, and brands such as Han Shu and Yiye have been notified for many times and received attention
How to restore the factory settings of HP computer
Redis single thread and multi thread
Correlation
Programming language (1)
Yyds dry goods inventory Prometheus alarm Art
Code in keil5 -- use the code formatting tool astyle (plug-in)
How to solve win10 black screen with only mouse arrow
Morning flowers and evening flowers
webAssembly
Recursion and recursion
What are the common computer problems and solutions
Get current JVM data
JS closure knowledge points essence
[automation operation and maintenance novice village] flask-2 certification
WiFi 2.4g/5g/6g channel distribution
Awk getting started to proficient series - awk quick start
Format cluster and start cluster