当前位置:网站首页>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
边栏推荐
- Data consistency between redis and database
- Learning notes of raspberry pie 4B - IO communication (SPI)
- Unique in China! Alibaba cloud container service enters the Forrester leader quadrant
- [golang] leetcode intermediate - alphabetic combination of island number and phone number
- Analysis report on the development trend and Prospect of global and Chinese supercontinuum laser source industry Ⓚ 2022 ~ 2027
- Blue Bridge Cup -- guess age
- LeetCode 1647. Minimum deletion times of unique character frequency
- Weekly leetcode - nc9/nc56/nc89/nc126/nc69/nc120
- Text replacement demo
- Mindmanager2022 serial number key decompression installer tutorial
猜你喜欢
Code in keil5 -- use the code formatting tool astyle (plug-in)
Es6~es12 knowledge sorting and summary
In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions
Correlation
How to solve the problem of requiring a password when accessing your network neighborhood on your computer
How to switch between dual graphics cards of notebook computer
Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
[dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)
Mysql database - Advanced SQL statement (I)
随机推荐
[flax high frequency question] leetcode 426 Convert binary search tree to sorted double linked list
320. Energy Necklace (ring, interval DP)
Blue Bridge Cup -- Mason prime
Go Technology Daily (2022-02-13) - Summary of experience in database storage selection
Pooling idea: string constant pool, thread pool, database connection pool
Can you draw with turtle?
pivot ROP Emporium
webAssembly
Label coco format data and format data in the upper left corner and lower right corner are mutually converted
Pat grade A - 1164 good in C (20 points)
Preliminary analysis of smart microwave radar module
Pointer concept & character pointer & pointer array yyds dry inventory
BUUCTF,Misc:LSB
Correlation
Leetcode week 4: maximum sum of arrays (shape pressing DP bit operation)
33 restrict the input of qlineedit control (verifier)
Kali2021.4a build PWN environment
File copy method
QGIS grid processing DEM data reclassification
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