当前位置:网站首页>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
边栏推荐
- Rest reference
- The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
- Take you to master the formatter of visual studio code
- 540. Single element in ordered array
- QGIS grid processing DEM data reclassification
- Overview of Yunxi database executor
- Pooling idea: string constant pool, thread pool, database connection pool
- How to solve the problem of computer networking but showing no Internet connection
- Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)
- Text replacement demo
猜你喜欢
![[Android reverse] use DB browser to view and modify SQLite database (download DB browser installation package | install DB browser tool)](/img/1d/044e81258db86cf34eddd3b8f5cf90.jpg)
[Android reverse] use DB browser to view and modify SQLite database (download DB browser installation package | install DB browser tool)

The reason why the computer runs slowly and how to solve it

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

How the computer flushes the local DNS cache

STM32 multi serial port implementation of printf -- Based on cubemx

Mysql database - Advanced SQL statement (I)

Pooling idea: string constant pool, thread pool, database connection pool

Weekly leetcode - nc9/nc56/nc89/nc126/nc69/nc120

On my first day at work, this API timeout optimization put me down!

Covariance
随机推荐
6.0 kernel driver character driver
DR-NAS26-Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-5GHz-high-power-Mini-PCIe-Wi-Fi-Module
股票炒股开户注册安全靠谱吗?有没有风险的?
Yyds dry goods inventory Spring Festival "make" your own fireworks
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
Conditional statements of shell programming
finalize finalization finally final
2022 electrician (elementary) examination questions and electrician (elementary) registration examination
Oil monkey plug-in
320. Energy Necklace (ring, interval DP)
Shell script three swordsman awk
Awk getting started to proficient series - awk quick start
540. Single element in ordered array
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
Morning flowers and evening flowers
User login function: simple but difficult
Subset enumeration method
Mongoose the table associated with the primary key, and automatically bring out the data of another table
Sow of PMP
[golang] leetcode intermediate - alphabetic combination of island number and phone number