Why do I think data structures and algorithms are important for front-end development?

Source: Internet
Author: User
From a demand

In my previous project, I had encountered a requirement to write a cascade selector, presumably:

The example in the figure uses the Cascader component of ant-design.

To achieve this, I need a data structure like this:

var data = [{ "value":  "Zhejiang",  "children": [{ "value":  "Hangzhou",  "children": [{ "West Lake"}]}]}, { "value": " Sichuan ", " children ": [{" value ":  "Chengdu",  "children": [{ "value":  "Jin Li"}, { "value": " value ": " Aba ", " children ": [{ "Value":  "Jiuzhaigou"}]}]}]           

A hierarchy of data, it is very easy to implement this function, because the structure and components of the structure is consistent, recursive traversal can be.

However, since the backend typically uses a relational database, the returned data will typically look like this:

var data = [{ "province":  "Zhejiang",  "City":  "Hangzhou",  "name":  "West Lake"}, {  "province":  "Sichuan",  "City":  "Chengdu",  "name":  "Jin Li"}, {  "province":  "Sichuan",  "City":  "Chengdu",  "name":  "Square"}, {  "province":  "Sichuan",  "City":  "Aba",  "name":  "Jiuzhaigou"}]    

The front side want to transform the data is not difficult, because to merge duplicates, you can refer to the data deduplication method to do, so I wrote a version.

' Use strict '/** * Convert a Flat object with no hierarchy to a tree structure ({value, children}) Structure Object * @param {array} tabledata-an array of objects that are flat @param {array} rou Te-an array of strings, which is the key of the object in the previous array, and the final object hierarchy of the output is the order of the string key in keys * @return {array} Save the object with a tree structure */var transobject =function(Tabledata, Keys) {Let hashTable = {}, res = []ForLet i =0; i < tabledata.length; i++) {if (!hashtable[tabledata[i][keys[0]]) {Let Len = Res.push ({value:tabledata[i][keys[0]], children: []})Here you want to save the key corresponding to the array ordinal, otherwise it involves finding hashtable[tabledata[i][keys[0]] = {$ $pos: Len-1}}if (!hashtable[tabledata[i][keys[0]]][tabledata[i][keys[1]]) {Let Len = res[hashtable[tabledata[i][keys[0]]].$ $pos].children.push ({value:tabledata[i][keys[1]], children: []}) hashtable[tabledata[i][keys[0]]][tabledata[i][keys[1]] = {$ $pos: Len-1}} res[hashtable[tabledata[i][keys[0]]].$ $pos].children[hashtable[tabledata[i][keys[0]]][tabledata[i][keys[1]]].$ $pos].children.push ({value:tabledata[i][keys[2]})}return res}var data = [{"Province":"Zhejiang","City":"Hangzhou","Name":"West Lake"}, { "province":  "Sichuan",  "City":  "Chengdu",  "name":  "Jin Li"}, {  "province":  "Sichuan",  "City":  "Chengdu",  "name":  "Square"}, {  "province":  "Sichuan",  "City":  "Aba",  "name":  "Jiuzhaigou"}] var keys = [ ' province ',  ' city ', Span class= "hljs-string" > ' name ']console.log (Transobject (data, keys))    

Fortunately, the length of the keys is only 3, this kind of thing has no way to write, it is obvious that there are repeating parts here, can be done through the loop, but think for a long time have no ideas, on hold.

Later, one day after supper is not very busy, and next to do the data colleague chatted about this demand, ask how to use the loop to deal with. He looked and asked me, "Do you know the trie tree?" ”。 The first time I heard this concept, he simply gave me a little talk, and then said that the feeling of dealing with something similar, so I can study the principle of the trie tree and try to optimize it.

Reason, trie tree this data structure on the Internet does have a lot of information, but very few use JavaScript implementation, but the principle is not difficult. After the attempt, I transObject optimized the code to this. (For Trie tree, please read the relevant materials yourself)

var transobject =function(Tabledata, Keys) {let hashTable = {}, res = [] for (let i = 0; i < tabledata.length; i++) {let arr = res, cur = hashTable for (let j = 0; j < Keys.length; j+ +) {let key = Keys[j], filed = Tabledata[i][key] if (!cur[filed]) {let pusher = {value:filed}, tmp if (J!== (Keys.length-1)) {tmp = [] Pusher.children = tmp} cur[filed] = {$ $pos: Arr.push (Pusher)-1} cur = cur[filed] arr = tmp} else {cur = cur[filed] arr = arr[cur.$ $pos].children}} } return res}           

In this way, the solution has nothing to do with the length of the keys.

This is probably my first time to really combine the knowledge of the data structure with the front-end project requirements.

And talk about my interview problems.

So far I have had several interviews with front-end development, and indeed many interviewers will ask some algorithms. This is usually related to linked lists, trees, strings, and arrays of knowledge. The front-end interview to the algorithm requirements are not high, it seems that the industry has been a consensus. Although the algorithm good front-end interview will certainly add points, but only by common face test, but not to contact the demand, it is difficult to let people feel that the algorithm for the front-end is really important.

Until one day, an interviewer asked me such a question, I followed my own memories of the dialogue simulation, a refers to the interviewer, B refers to me:

A: Have you ever written a waterfall stream?

B: I've written a stream of equal-width waterfalls. The implementation is when the user pulls to the bottom of a certain height, the back end of the request a certain number of pictures, and then inserted into the page.

A: Let me ask, how can I minimize the difference in height between several columns of pictures?

B: This needs the back end to send the data inside the picture height, then I can see the current height of the smallest is the column, the new picture into the column, and then look at the new height of the smallest column.

A: I don't think you understand my question, I mean how to sort the pictures sent from the backend, so that the height difference between the several columns is minimized?

B: (Thought for a while) sorry, I have no idea about this question.

A: You're a software engineering professional, right? Do you have a dynamic plan for the data structure class?

B: Maybe, but I don't remember much.

The dialogue is probably the case, although the interview is finally pass, but this problem really let me care, because I think, the height difference "the most" small, really can be solved with a very simple algorithm?

The essence of this problem is that there is an array that divides the elements of an array into n parts, each sum of all the elements, and how to make the difference between each and every share the smallest.

Search the above question, will soon be able to find the relevant answers, a very basic kind of dynamic programming problem-knapsack problem.

I did see the concept of the knapsack problem (and just the concept). At that time I saw this passage:

Many programming problems that use recursive solutions can be rewritten to solve using dynamic programming techniques. A dynamic planning scenario typically uses an array to create a table that holds the solution that is decomposed into many sub-problems. When the algorithm is executed, the final solution will be found in the obvious place in the table.

The following is an example of rewriting the Fibonacci sequence with dynamic programming. I saw that it was just a recursive result, saved in an array, naïve to think that dynamic programming is a way to optimize recursion, and not to understand it in depth.

Superficial understanding, it's really going to be a problem sooner or later. While I thought I knew the importance of the algorithm, it was still too young.

Dynamic programming can solve a kind of "optimal solution" problem, which in a way let me refreshing. Because this article mainly is to explain the data structure and the algorithm to the front end significance, regarding the dynamic programming detail, this article also does not involve, moreover the level certainly is not enough. There are many very good blog posts on the Internet, especially the "Backpack ninth lecture".

Say two more words--a study questions

The following flattened object is converted to a tree object. parentthe node for which the field is an empty string is the root node:

var input = {h3: {parent:  ' H2 ', Name:  ' H0 ', Name:  ' company organization '}, H7: {PA Rent:  ' h6 ', Name:  ' deputy General Manager (General Affairs) ', H4: {parent:  ' H3 ', Name:  ' sales Manager '}, H2: {parent:  ' H1 ', Name:  ' general manager '}, H8: {parent:  ' H0 ', Name:  ' financial Controller '}, h6 : {Parent:  ' H4 ', Name:  ' warehouse director '}, H5: {parent:  ' h4 ', Name:  ' sales rep '}, H0: {parent: ", Name:               

This requirement is actually very practical at the front end, and the object in the example is a company organization chart. This is required if the requirement is for you to draw such a diagram at the front end with techniques such as SVG. (Another scenario I came up with was to show a file tree like Windows Explorer on the front end)

I thought for a long time, did not think of a circular solution, and later found the answer on the StackOverflow:

var plain2Tree = function (obj) {  var key, res for(key in obj) { var parent = obj[key].parent if(parent === ‘‘) { res = obj[key] } else { obj[parent][key] = obj[key] } } return res}

This code is the use of JavaScript inside the reference type, then the idea, and the operation of the pointer is no different, is to construct a tree.

But for me, never thinking about the tree and the pointer, it was very passive.

Conclusion

The above list of three questions, hope can arouse everyone on the front-end application of data structure and algorithm-related knowledge of the resonance.

Why do I think data structures and algorithms are important for front-end development?

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.