1. Introduction

You’ve been developing projects and neighborhoods for a while, and you’ve come across some impressive business needs. These business requirements may be encountered in your own development project, seen in the community, or otherwise exposed to requirements, but the implementation logic of these business requirements is worth writing. Because these business logic can be as exercise, you can practice for everyone. Also hope that you can from these requirements to achieve the logic inside the relevant knowledge of javascript, of course, if you think the code needs to be optimized, or what suggestions, better implementation scheme, feel I write wrong, or feel can share the needs, can be mentioned in the comments!

2. Month axes

The requirement is, just look at the picture below

The implementation is actually very simple, I put a comment on the code, everyone will understand!

``````var _date=[],dateData=["January"."February"."March"."April"."May"."June"."July"."August"."September"."October"."November"."December"]; Var dateDataRet= object.assign ([],dateData).reverse(); Var yearText=new Date().getFullYear(); // Select * from 'now' where 'now' = '2' and 'December' = '11'... var now=new Date().getMonth();for(leti=0; i<6; i++){if(now - if I < 0) {/ / now - I < 0, take data from dateDataRet inside, the subscript = | now -i | 1. _date.push(yearText-1+'years'+dateDataRet[Math.abs(now-i)-1]);
}
else{// get data from dateData, subscript =now-i _date.push(yearText+)'years'+dateData[now-i]);
}

}
_date.reverse();Copy the code``````

You might be confused, but just look at the circular diagram below

3. Numerical interval

In the figure below, there are several numerical intervals, and there will be a minimum and a maximum

``````var _min=5,_max=50;
functionCheckArr (arr,min, Max){function(n1,n2){returnN1. Min - n2 min}) / / traversefor(var i=0; i<arr.length; I++){// the minimum value of the interval cannot be greater than or equal to the maximum value of the intervalif(arr[i].min>=arr[i].max){
console.log(The minimum value of the interval cannot be greater than or equal to the maximum value of the interval.);
return; } // The minimum value of the interval cannot be less than the default minimum valueif(arr[i].min<min){
console.log(The minimum value of the interval must not be less than the default minimum.);
return; } // The maximum value of the interval cannot be greater than the default maximum valueif(arr[i].max>max){
console.log('The maximum value of the interval must not be greater than the default maximum.');
return; } // Compare elements, starting with the second elementif(I >0){//minInclude, maxInclude, asfalseIt does not contain, istrueIs contains / / {min: 10, Max: 20, minInclude:false,maxInclude:false} / / is equivalent to (10, 20) / / {min: 20, Max: 30, minInclude:true,maxInclude:false} // the same as [20,30]; // if both the previous maximum and the current minimum are inclusive, then the minimum value of the current interval must be 1 greater than the maximum value of the previous intervalif(arr[i].minInclude&&arr[i-1].maxInclude&&arr[i].min-arr[i-1].max! ==1){ console.log('Error in value range - the minimum value of the current interval and the maximum value of the previous interval are both inclusive cases, the minimum value of the current interval must be 1 greater than the maximum value of the previous interval.');
return; } // If the previous maximum and the current minimum. If one is included and one is not included, then the minimum value of the current interval must be equal to the maximum value of the previous intervalelse if(arr[i].minInclude! ==arr[i-1].maxInclude&&arr[i].min! ==arr[i-1].max){ console.log('Error in value range - the minimum value of the current interval and the maximum value of the previous interval. One is included and one is not included. The minimum value of the current interval must be equal to the maximum value of the previous interval.');
return; } // If both the previous maximum value and the current minimum value are not included, the current minimum value must not be satisfiedelse if((! arr[i].minInclude)&&(! arr[i-1].maxInclude)){ console.log('Error in value range - the previous maximum and current minimum are not included cases and do not satisfy the terminally connected');
return; }}}}Copy the code``````

The test case

``````var arr1=[{min:10,max:20,minInclude:false,maxInclude:true},{min:21,max:30,minInclude:true,maxInclude:true}],
arr2=[{min:10,max:20,minInclude:false,maxInclude:true},{min:20,max:30,minInclude:true,maxInclude:false}],
arr3=[{min:10,max:20,minInclude:false,maxInclude:true},{min:20,max:30,minInclude:false,maxInclude:false}],
arr4=[{min:10,max:20,minInclude:false,maxInclude:false},{min:20,max:30,minInclude:true,maxInclude:false}],
arr5=[{min:10,max:20,minInclude:false,maxInclude:false},{min:21,max:30,minInclude:true,maxInclude:false}],
arr6=[{min:10,max:20,minInclude:false,maxInclude:false},{min:15,max:30,minInclude:false,maxInclude:false}],
arr7=[{min:10,max:20,minInclude:false,maxInclude:false},{min:20,max:30,minInclude:false,maxInclude:false}],
arr8=[{min:1,max:20,minInclude:false,maxInclude:false},{min:20,max:30,minInclude:false,maxInclude:false}],
arr9=[{min:20,max:20,minInclude:false,maxInclude:false},{min:20,max:30,minInclude:false,maxInclude:false}],
arr10=[{min:20,max:30,minInclude:false,maxInclude:false},{min:20,max:70,minInclude:false,maxInclude:false}];
Copy the code``````

The results

4. Array comparison

This is based on a question THAT I answered, and I’m going to rewrite it

How does JavaScript compare two arrays? Array B is adding or deleting array A, right? (No jquery, native JS) The problem is:

arryA

``````var arrayA = ['a'.'b'.'c'];
Copy the code``````

arryB

``````var arrayB = [{
key:'a',
num1:'1',
num2:'2',
num3:'3',
tot:'6'
},{
key:'b',
num1:'11',
num2:'22',
num3:'33',
tot:'66'
},{
key: 'c',
num1: '111',
num2: '222',
num3: '333',
tot:666
}];
Copy the code``````

1. If there is A in arryA but not in arryB, then add a key value of boj of A in arryB, and other attribute values can all be ‘0’; As follows: {key: ‘a’, num1: ‘0’, num2: ‘0’, num3: ‘0’, tot ‘, 0 ‘}

2. If there is A in arryA and OBj whose key value is A in arryB, then arryB does not change, and other attributes and attribute values in the OBJ are unchanged;

3. If a is deleted in arryA, then obj with key value a in arryB is deleted.

``// Prepare a temporary arrayfunctioncompareArr(arr1,arr2){ var result=[],arr; / / traversefor(var i=0; i<arr1.length; I ++){// look for arrayB based on the value of arR1 [I]. If arR2 has an item that satisfies the condition (object in arrayB with key value equal to arrayA[I]), return the item that satisfies the condition, otherwise return underfind; arr=arr2.find(function(val){returnval.key===arr1[i]}); {key:arrayA[I],num1: arrayA[I],num1: arrayA[I]'0',num2:'0',num3:'0',tot:'0'}. arr? result.push(arr):result.push({key:arrayA[i],num1:'0',num2:'0',num3:'0',tot:'0'}); }}Copy the code``

test

``````var arrayA = ['b'.'c'];
var arrayB = [{
key:'a',
num1:'1',
num2:'2',
num3:'3',
tot:'6'
},{
key:'b',
num1:'11',
num2:'22',
num3:'33',
tot:'66'
},{
key: 'c',
num1: '111',
num2: '222',
num3: '333',
tot:666
}];
compareArr(arrayA,arrayB);
Copy the code``````

5. 5. Smart Car

Statistics of students applying for excellent graduates, and meet the conditions (excellent grades, scholarships, awarded merit students). The premise is to apply

The general flow chart looks like this!

I’ll put a comment on the code, so it’s not hard to understand

``````// List of students //isApply: whether there are applied for outstanding graduateslet studentList = [
{
name: 'aa',
isApply: false,
id: 1
},
{
name: 'bb',
isApply: true,
id: 2
},
{
name: 'cc',
isApply: true, id: 3 } ]; // Select * from the list where you want to graduate.true

let _student = studentList.filter(function (item) {
returnitem.isApply; }); //isExcellent: id list of excellent students //isScholarship: ID list of students who have won scholarships //isThreeGood: ID list of students who have won three good students // Accord: setletisExcellent = [1, 2, 3, 4, 5], isScholarship = [4, 2, 5, 6, 2, 1, 2], isThreeGood = [2, 1, 4, 52, 36], accord = []; // Array deduplicate functionfunction removeRepeatArr(arr) {
return arr.filter(function (item, index, self) {
returnself.indexOf(item) === index; }); } // Count the number of occurrences of an element in an arrayfunction getEleCount(obj, ele) {
let num = 0;
for (let i = 0, len = obj.length; i < len; i++) {
if(ele === obj[i]) { num++; }}returnnum; } // Add the id of the student who received a good grade, the ID of the student who received a scholarship, and the ID of the student who received a merit grade. // But before adding, id of students who have obtained excellent grades, ID of students who have won scholarships, id of students who have obtained merit. The three arrays are re-added into accord, because a student may have more than one excellent performance, more than one scholarship, and more than one merit student // This will facilitate the following judgment: Accord. Push. Apply (accord, removeRepeatArr(isExcellent)); accord.push.apply(accord, removeRepeatArr(isScholarship)); accord.push.apply(accord, removeRepeatArr(isThreeGood)); console.log(accord); // List of eligible studentslet accordStudent = [];
for (leti = 0; i < _student.length; I++) {// as long as the student id appears in accord twice or moreif(getEleCount(accord, _student[I].id) >= 2) {// record which student is eligible accordstudent.push (_student[I]); } } console.log(accordStudent);Copy the code``````

6. Maximum length of a contiguous array

This is also based on the question I answered: here it is

``````/ / if there is an array, the array under the maximum continuous length is 4 -- -- - 8,9,10,11 var arr =,2,4,5,6,8,9,10,11 [1]; // Code implementationfunctionCountLen (arr){// Return 0 if the argument is not an array or has a length of 0if(arr.constructor! ==Array||arr.length===0){return0; } var nowLen=1,maxLen=0;for(var i=1,len=arr.length; i<len; I++){// is the current array element 1 larger than the last arrayif(arr [I] - arr (I - 1) = = = 1) {/ / if it is, the current continuous length nowLen + 1 nowLen++; }else{// Otherwise, determine whether the current continuous length is greater than the maximum continuous lengthif(maxLen<nowLen){// if so, set maxLen=nowLen} // The current continuous length is initialized to 1 nowLen=1; } // Check whether the current contiguous length is greater than the maximum contiguous length (avoid the bug when the maximum contiguous length is the last array)if(maxLen<nowLen){maxLen=nowLenreturn maxLen;
}
Copy the code``````

This and the above code is basically the same, but the judgment condition is a tiny difference, directly paste, you see

``````functioncountTrue(arr){debugger; // Return 0 if the argument is not an array or has a length of 0if(arr.constructor! ==Array||arr.length===0){return0; } var nowLen=0,maxLen=0;for(var i=0,len=arr.length; i<len; I++){// is the current array element 1 larger than the last arrayif(arr[I]){// If so, the current continuous length nowLen+1 nowLen++; }else{// Otherwise, determine whether the current continuous length is greater than the maximum continuous lengthif(maxLen<nowLen){// set maxLen=nowLen if yes} // Set the current continuous length to 0 nowLen=0; } // Check whether the current contiguous length is greater than the maximum contiguous length (avoid the bug when the maximum contiguous length is the last array)if(maxLen<nowLen){maxLen=nowLenreturn maxLen;
}
Copy the code``````

8. Name conversion

For example, the hump naming method turns to the ‘-‘ naming method.

``````var str = "shouHou";
//The \$1- The first parenthesis matches the content // this instance,The \$1='H'
str = str.replace(/([A-Z])/g,"-The \$1").toLowerCase();
Copy the code``````

For example, the ‘-‘ naming method is changed to the hump naming method

``````var str="shou-hou";
//\$0- Indicates the matching resultThe \$1- The first parenthesis matches the content // this instance\$0='-h'    The \$1='h'
str=str.replace(/-(\w)/g,function(\$0.The \$1) {return The \$1.toUpperCase();
});
Copy the code``````

9. Format characters

This is most commonly used for display requirements in terms of amounts, such as 10000 returned in the background. The front end should be displayed as 10,000 or other formats!

``````// STR //size- Delimiter every few characters default 3 //delimiter- Delimiter default', '
function formatText(str,size,delimiter){
var _str=str.toString();
var _size=size||3,_delimiter=delimiter||', '; /* if _size is 3"\ d {1, 3} (? =(\d{3})+\$)"
*/
var regText='\\d{1,'+_size+'} (? =(\\d{'+_size+'}) + \$) '; / * / \ d {1, 3} (? =(\d{3})+\$)/g */ var reg=new RegExp(regText,'g'); / * (?) Match the front - sign (\d+) match the middle number ((\.\d+)?) Matches the number behind the decimal point //\$0- Matching result,The \$1- What the first parenthesis returns ----(-?)\$2.\$3And so on */return_str.replace(/^(-?) (\d+)((\.\d+)?) \$/,function (\$0.The \$1.\$2.\$3) {
return The \$1 + \$2.replace(reg, '\$&,) + \$3; })}Copy the code``````

10. Object merge and record abnormal data

You might be confused about this requirement. For example, there are two places where my information is recorded

``````let info1={
name:"Waiting",
sex:"Male",
age:24,
job:"The web front end"
},info2={
name:"Wait!",
country:"china",
phone:"12345678910",
job:"The web front end"
}Copy the code``````

Now I’m going to merge my information and record any information that might have exceptions. For example, the name attribute above is present in both objects, and the values of the two objects are different, so it is not clear whether the name attribute in Info1 is correct or the name attribute in INFO2 is correct. Therefore, you need to record the name attribute so that you can check the name attribute later.

The following figure

Now, step by step, forget about 3721, and just merge the attributes

``````let objAll={};
function assignObj(objArr) {
let _obj={};
for(leti=0; i<objArr.length; i++){ _obj=Object.assign(_obj,objArr[i],{}); }return JSON.parse(JSON.stringify(_obj));
}
objAll=assignObj([objA,objB]); Copy the code``````

Then prepare a field to record the exception information

``objAll.warnInfo=[];Copy the code``

Finally, the object is checked to determine which information is abnormal

``````  functionCheckObj (_objAll,objList) {// Get all propertieslet _keys=Object.keys(_objAll);
for(leti=0; i<objList.length; i++){for(letj=0; j<_keys.length; J ++){// if the _keys[j] attribute exists in both _objList [I] and _objAll, and the two values are not the same, then the attribute is a piece of data.if(objList[i][_keys[j]]!==undefined&&_objAll[_keys[j]]!==objList[i][_keys[j]]){
_objAll.isError.push(_keys[j]);
}
}
}
return _objAll;
}
console.log(checkObj(objAll,[objA,objB]));

Copy the code``````

11. Filter labels

Render the label below, as shown below

The first thing you might think is that it’s just an array of objects: for example

``````var searchTag=[
{label:'Product code',value:'the 100072236-8'},
{label:'Product Name',value:'glycerin'}]Copy the code``````

But data like this, obviously, has to be processed to produce it

Because it’s not possible to send a request like this

``http://example.com? Product code =100072236-8Copy the code``

The parameters sent in the past should look like this

``````http://example.com?proId=100072236-8

var searchParam={proId:'the 100072236-8',proName:'glycerin'}   Copy the code``````

How to process the data, in fact, very simple, code without comment, I want to understand

``````var searchTag=[];
var searchText={proId:'Product code',proName:'Product Name'};
var searchParam={proId:'the 100072236-8',proName:'glycerin'};
Object.keys(searchParam).forEach(function (item) {
searchTag.push({
label:searchText[item],
key:item,
value:searchParam[item]
})
})
console.log(searchTag)
Copy the code``````

With this data, rendering to the page is easy!

12. Import excel content

That’s what excel does

Convert to the following data

Directory as follows

Let’s start writing code, using Node.js

``````let path = require('path'); NPM install ejsexcel --savelet ejsExcel=require('ejsexcel');
let_data=[]; Ejsexcele.getexcelarr (exBuf).then(exlJson=>{// Get excel dataletworkBook=exlJson; // Obtain the first Excel sheet, sheet1letworkSheets=workBook[0]; // Export the js pathlet newfilepath=path.join(__dirname,"/resource/test.js"); WorkSheets. ForEach ((item,index)=>{workSheets. ForEach ((item,index)=>{workSheetsif_data.push({name:item[0], phone:item[1]})}}); // Write to js file fs.writeFileSync(newFilepath,'let _data='+JSON.stringify(_data)+'; export {_data}'); }).catch(error=>{// print the error message console.log("Read error!");
console.log(error);
});Copy the code``````

Then the command line executes the JS

``````\$ node importFile.js
Copy the code``````

Then I found an extra test.js file

Excel data so imported into a JS array, as long as the introduction of this array, you can use the normal!

13. Random loop

The business was actually displaying the customer’s information, which felt a bit like a random loop of a music player.

There are two requirements: 1. In a prompt list, the prompt information is randomly displayed every 500ms. 2. In the same round of loop, a prompt message can only be displayed once. 3. After all the prompts in the list are displayed, proceed to the next round of display. This logic is nothing, just put a comment on the code, I think you’ll get the idea!

``````var tipList=['hint 1'.'2'.'tip 3'.'tip 4'.'tip 5'.'prompt 6'.'tip 7'.'tip 8'.'tip 9'];
var tipListShow=[];
tipListShow=Object.assign([],tipList);
var i=0,timer=null;
function play() {// delete the item from tipListShow after it is displayed. console.log(tipListShow.splice(Math.floor(Math.random() * tipListShow.length),1)[0]); // When the loop is complete, the length of tipListShow will be 0, and then the value will be reassigned, ready for the next random loopif(tipListShow.length===0){ tipListShow=Object.assign([],tipList); i=0; } // If you want to pause or stop, clear the timer. Next time, create the timer again and play(); ! timer=setTimeout(function() { play(); }, 500); } play();Copy the code``````

14. Summary

Ok, so much for some of the business requirements logic I’ve ggathered, and how to implement it! There is no need to contact a lot of logic, but it is worth writing, can be used as an exercise, record here. My above code implementation may be a little rough, you have a better implementation scheme, welcome to suggest. If you have any requirements that you can use as a practice, you can mention them. Let everyone have some more exercises can try, study below!

— — — — — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — — want to know more, pay attention to focus on my WeChat public number: waiting for book cabinet