javascript-algorithms | 📝 Algorithms and data structures | Learning library

 by   trekhleb JavaScript Version: Current License: MIT

kandi X-RAY | javascript-algorithms Summary

javascript-algorithms is a JavaScript library typically used in Tutorial, Learning, Example Codes applications. javascript-algorithms has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i dist-javascript-algorithms-and-data-structures' or download it from GitHub, npm.
This repository contains JavaScript based examples of many popular algorithms and data structures. Each algorithm and data structure has its own separate README with related explanations and links for further reading (including ones to YouTube videos). Read this in other languages: 简体中文, 繁體中文, 한국어, 日本語, Polski, Français, Español, Português, Русский, Türk, Italiana, Bahasa Indonesia, Українська, Arabic, Deutsch.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        javascript-algorithms has a medium active ecosystem.
                        summary
                        It has 165228 star(s) with 27262 fork(s). There are 4360 watchers for this library.
                        summary
                        It had no major release in the last 6 months.
                        summary
                        There are 107 open issues and 208 have been closed. On average issues are closed in 48 days. There are 186 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of javascript-algorithms is current.
                        This Library - Support
                          Best in #Learning
                            Average in #Learning
                            This Library - Support
                              Best in #Learning
                                Average in #Learning

                                  kandi-Quality Quality

                                    summary
                                    javascript-algorithms has 0 bugs and 0 code smells.
                                    This Library - Quality
                                      Best in #Learning
                                        Average in #Learning
                                        This Library - Quality
                                          Best in #Learning
                                            Average in #Learning

                                              kandi-Security Security

                                                summary
                                                javascript-algorithms has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                javascript-algorithms code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                This Library - Security
                                                  Best in #Learning
                                                    Average in #Learning
                                                    This Library - Security
                                                      Best in #Learning
                                                        Average in #Learning

                                                          kandi-License License

                                                            summary
                                                            javascript-algorithms is licensed under the MIT License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            This Library - License
                                                              Best in #Learning
                                                                Average in #Learning
                                                                This Library - License
                                                                  Best in #Learning
                                                                    Average in #Learning

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        javascript-algorithms releases are not available. You will need to build from source code and install.
                                                                        summary
                                                                        Deployable package is available in npm.
                                                                        summary
                                                                        Installation instructions are not available. Examples and code snippets are available.
                                                                        This Library - Reuse
                                                                          Best in #Learning
                                                                            Average in #Learning
                                                                            This Library - Reuse
                                                                              Best in #Learning
                                                                                Average in #Learning
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed javascript-algorithms and discovered the below as its top functions. This is intended to give you an instant insight into javascript-algorithms implemented functionality, and help decide if they suit your requirements.
                                                                                  • Convert a ZBox into a ZBox
                                                                                    • Retrieves the number of consecutive columns in the board .
                                                                                      • Extracts the edges of the given graph .
                                                                                        • Sorts all vertices in the given graph
                                                                                          • Add a new option to the current array .
                                                                                            • This is the algorithm for searching for the triangulation into a cycle .
                                                                                              • Makes a stack up to the root node .
                                                                                                • Traverse the chessboard .
                                                                                                  • Recursively compute the state of the puzzle .
                                                                                                    • Find all the paths in the given start .
                                                                                                      Get all kandi verified functions for this library.
                                                                                                      Get all kandi verified functions for this library.

                                                                                                      javascript-algorithms Key Features

                                                                                                      📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

                                                                                                      javascript-algorithms Examples and Code Snippets

                                                                                                      Calculates the inverse of a matrix to solve with linearization .
                                                                                                      javascriptdot imgLines of Code : 34dot imgno licencesLicense : No License
                                                                                                      copy iconCopy
                                                                                                      
                                                                                                                                          function matrixChainOrder(p) { const n = p.length; const m = []; const s = []; for (let i = 1; i <= n; i++) { m[i] = []; m[i][i] = 0; } for (let i = 0; i <= n; i++) { // to help printing the optimal solution s[i] = []; // auxiliary for (let j = 0; j <= n; j++) { s[i][j] = 0; } } for (let l = 2; l < n; l++) { for (let i = 1; i <= (n - l) + 1; i++) { const j = (i + l) - 1; m[i][j] = Number.MAX_SAFE_INTEGER; for (let k = i; k <= j - 1; k++) { // q = cost/scalar multiplications const q = m[i][k] + m[k + 1][j] + ((p[i - 1] * p[k]) * p[j]); if (q < m[i][j]) { m[i][j] = q; s[i][j] = k; // s[i,j] = Second auxiliary table that stores k } } } } // console.log(m); // console.log(s); printOptimalParenthesis(s, 1, n - 1); return m[1][n - 1]; }
                                                                                                      Sorts an array .
                                                                                                      javascriptdot imgLines of Code : 22dot imgno licencesLicense : No License
                                                                                                      copy iconCopy
                                                                                                      
                                                                                                                                          function countingSort(array) { if (array.length < 2) { return array; } const maxValue = findMaxValue(array); let sortedIndex = 0; const counts = new Array(maxValue + 1); array.forEach(element => { if (!counts[element]) { counts[element] = 0; } counts[element]++; }); // console.log('Frequencies: ' + counts.join()); counts.forEach((element, i) => { while (element > 0) { array[sortedIndex++] = i; element--; } }); return array; }
                                                                                                      binary search helper
                                                                                                      javascriptdot imgLines of Code : 21dot imgno licencesLicense : No License
                                                                                                      copy iconCopy
                                                                                                      
                                                                                                                                          function binarySearch(array, value, compareFn = defaultCompare) { const sortedArray = quickSort(array); let low = 0; let high = sortedArray.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); const element = sortedArray[mid]; // console.log('mid element is ' + element); if (compareFn(element, value) === Compare.LESS_THAN) { low = mid + 1; // console.log('low is ' + low); } else if (compareFn(element, value) === Compare.BIGGER_THAN) { high = mid - 1; // console.log('high is ' + high); } else { // console.log('found it'); return mid; } } return DOES_NOT_EXIST; }
                                                                                                      Community Discussions

                                                                                                      Trending Discussions on javascript-algorithms

                                                                                                      How to sort and chunk a dependency tree of actions, so you can batch as many actions as possible together at each step?
                                                                                                      chevron right
                                                                                                      Return value evaluation of a stored function inside a loop with let variable
                                                                                                      chevron right
                                                                                                      JavaScript: filter array of objects using an object
                                                                                                      chevron right
                                                                                                      What the point of spread operaror in JavaScript especially on this example?
                                                                                                      chevron right
                                                                                                      Why does freecodecamp not let my while loop continue?
                                                                                                      chevron right
                                                                                                      How does recursion work in a Countdown function
                                                                                                      chevron right
                                                                                                      Please suggest how to debug
                                                                                                      chevron right
                                                                                                      Arguments Optional - why do I get a string for arguments (2)([3])?
                                                                                                      chevron right
                                                                                                      trying to understand this profile lookup in JavaScript
                                                                                                      chevron right
                                                                                                      What is wrong in my regex /(?=^[a-z]+\d{2,})(?=\w{5,})/ pattern?
                                                                                                      chevron right

                                                                                                      QUESTION

                                                                                                      How to sort and chunk a dependency tree of actions, so you can batch as many actions as possible together at each step?
                                                                                                      Asked 2022-Jan-20 at 13:20

                                                                                                      Say you have a bunch of actions for creating/inserting records into a bunch of different database tables. You have some records which can be inserted without any dependency on the output of any other insert. You have some which need to wait for one other thing to finish. And you have others that need to wait for many things to finish, which might finish at different times in the flow.

                                                                                                      How can you write an algorithm which would sort and chunk the actions in the dependency tree so the inserts / database actions can be optimally batched? By optimally batched, I mean if you can insert 10 records into the same table at once, then do that. Any time you can batch insert, you should, to minimize the number of database calls/inserts.

                                                                                                      Here is a snippet from the example code I whipped together with a fake sequence of actions using a simple data structure to capture all the required information.

                                                                                                      ...
                                                                                                      { action: 'create', table: 'tb1', set: 'key12', input: {
                                                                                                        p: { type: 'binding', path: ['key10', 'z'] },
                                                                                                        q: { type: 'binding', path: ['key11', 'a'] }
                                                                                                      } },
                                                                                                      { action: 'create', table: 'tb4', set: 'key13' },
                                                                                                      { action: 'create', table: 'tb3', set: 'key14' },
                                                                                                      { action: 'create', table: 'tb4', set: 'key15', input: {
                                                                                                        a: { type: 'binding', path: ['key8', 'z'] },
                                                                                                      } },
                                                                                                      ...
                                                                                                      

                                                                                                      Note that there are 4 possible properties on our "dependency node item":

                                                                                                      • action: This is always "create" in our situation, but potetntially could be other things in the future.
                                                                                                      • table: The table name to insert into.
                                                                                                      • set: The name of the variable to add to the shared global "scope" in the action dependency tree, so other actions can read this as input.
                                                                                                      • input: Inputs to the action, which in our case are all "binding" inputs (but could just as well be literal values, but that would be too easy). For binding inputs, it reads some property/column value from a record stored in the shared scope of the dependency tree.

                                                                                                      Given that, it should be possible somehow to construct a simple algorithm that chunks the actions into subsets which can be run in parallel AND batched. For example, our code below would end up something like this structure (I manually created this output, so there could be mistakes though I think I got it right. Oh and note, while the tables are numbered, it doesn't imply an order to them necessarily, just were simple names to pick):

                                                                                                      // this is "close to" the desired result, because
                                                                                                      // there might be a slightly different sort applied
                                                                                                      // to this when implemented, but the chunking pattern
                                                                                                      // and grouping of elements should be exactly like This
                                                                                                      // (I am pretty sure, I manually did this 
                                                                                                      // so there could be small mistakes, but I doubt it)
                                                                                                      const closeToDesiredResult = [
                                                                                                        [
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb1', set: 'key1' },
                                                                                                            { action: 'create', table: 'tb1', set: 'key21' },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb2', set: 'key2' },
                                                                                                            { action: 'create', table: 'tb2', set: 'key3' },
                                                                                                            { action: 'create', table: 'tb2', set: 'key23' },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb4', set: 'key6' },
                                                                                                            { action: 'create', table: 'tb4', set: 'key8' },
                                                                                                            { action: 'create', table: 'tb4', set: 'key13' },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb3', set: 'key5' },
                                                                                                            { action: 'create', table: 'tb3', set: 'key7' },
                                                                                                            { action: 'create', table: 'tb3', set: 'key9' },
                                                                                                            { action: 'create', table: 'tb3', set: 'key14' },
                                                                                                            { action: 'create', table: 'tb3', set: 'key24' },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb6', set: 'key17' },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb5', set: 'key16' },
                                                                                                          ]
                                                                                                        ],
                                                                                                        [
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb1', set: 'key4', input: {
                                                                                                              x: { type: 'binding', path: ['key2', 'baz'] }
                                                                                                            } },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb3', set: 'key10', input: {
                                                                                                              y: { type: 'binding', path: ['key6', 'foo'] },
                                                                                                              z: { type: 'binding', path: ['key1', 'bar'] }
                                                                                                            } },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb4', set: 'key15', input: {
                                                                                                              a: { type: 'binding', path: ['key8', 'z'] },
                                                                                                            } },
                                                                                                          ]
                                                                                                        ],
                                                                                                        [
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb1', set: 'key12', input: {
                                                                                                              p: { type: 'binding', path: ['key10', 'z'] },
                                                                                                              q: { type: 'binding', path: ['key11', 'a'] }
                                                                                                            } },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb4', set: 'key11', input: {
                                                                                                              a: { type: 'binding', path: ['key10', 'z'] },
                                                                                                              b: { type: 'binding', path: ['key1', 'bar'] }
                                                                                                            } },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb6', set: 'key18', input: {
                                                                                                              m: { type: 'binding', path: ['key4', 'x'] },
                                                                                                            } },
                                                                                                            { action: 'create', table: 'tb6', set: 'key19', input: {
                                                                                                              m: { type: 'binding', path: ['key4', 'x'] },
                                                                                                              n: { type: 'binding', path: ['key13', 'a'] },
                                                                                                            } },
                                                                                                          ]
                                                                                                        ],
                                                                                                        [
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb2', set: 'key22', input: {
                                                                                                              w: { type: 'binding', path: ['key18', 'm'] },
                                                                                                              x: { type: 'binding', path: ['key17', 'm'] },
                                                                                                            } },
                                                                                                          ],
                                                                                                          [
                                                                                                            { action: 'create', table: 'tb6', set: 'key20', input: {
                                                                                                              m: { type: 'binding', path: ['key18', 'm'] },
                                                                                                              n: { type: 'binding', path: ['key17', 'm'] },
                                                                                                            } },
                                                                                                          ]
                                                                                                        ]
                                                                                                      ]
                                                                                                      

                                                                                                      Notice how there are 4 top-level chunks in the resulting array. These are the main steps. Then within each step, everything is grouped by table, so they can all be run in parallel, and within each table group, they can all be batch inserted. Boom.

                                                                                                      How would you implement this, it seems quite tricky for my mind to grasp?

                                                                                                      const actionTree = generateActionTree()
                                                                                                      const chunkedActionTree = chunkDependencyTree(actionTree)
                                                                                                      
                                                                                                      function chunkDependencyTree(list) {
                                                                                                        const independentOnesMapByTableName = {}
                                                                                                        list.forEach(node => {
                                                                                                          // easy case
                                                                                                          if (!node.input) {
                                                                                                            const group = independentOnesMapByTableName[node.table]
                                                                                                              = independentOnesMapByTableName[node.table] ?? []
                                                                                                            group.push(node)
                                                                                                          } else {
                                                                                                            // I am at a loss for words...
                                                                                                          }
                                                                                                        })
                                                                                                      }
                                                                                                      
                                                                                                      function generateActionTree() {
                                                                                                        // this would be constructed through a bunch of real-world
                                                                                                        // functions, queuing up all the actions
                                                                                                        // and pointing outputs to inputs.
                                                                                                        return [
                                                                                                          { action: 'create', table: 'tb1', set: 'key1' },
                                                                                                          { action: 'create', table: 'tb2', set: 'key2' },
                                                                                                          { action: 'create', table: 'tb2', set: 'key3' },
                                                                                                          { action: 'create', table: 'tb3', set: 'key5' },
                                                                                                          { action: 'create', table: 'tb4', set: 'key6' },
                                                                                                          { action: 'create', table: 'tb3', set: 'key7' },
                                                                                                          { action: 'create', table: 'tb4', set: 'key8' },
                                                                                                          { action: 'create', table: 'tb3', set: 'key9' },
                                                                                                          { action: 'create', table: 'tb3', set: 'key10', input: {
                                                                                                            y: { type: 'binding', path: ['key6', 'foo'] },
                                                                                                            z: { type: 'binding', path: ['key1', 'bar'] }
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb1', set: 'key4', input: {
                                                                                                            x: { type: 'binding', path: ['key2', 'baz'] }
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb4', set: 'key11', input: {
                                                                                                            a: { type: 'binding', path: ['key10', 'z'] },
                                                                                                            b: { type: 'binding', path: ['key1', 'bar'] }
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb1', set: 'key12', input: {
                                                                                                            p: { type: 'binding', path: ['key10', 'z'] },
                                                                                                            q: { type: 'binding', path: ['key11', 'a'] }
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb4', set: 'key13' },
                                                                                                          { action: 'create', table: 'tb3', set: 'key14' },
                                                                                                          { action: 'create', table: 'tb4', set: 'key15', input: {
                                                                                                            a: { type: 'binding', path: ['key8', 'z'] },
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb5', set: 'key16' },
                                                                                                          { action: 'create', table: 'tb6', set: 'key17' },
                                                                                                          { action: 'create', table: 'tb6', set: 'key18', input: {
                                                                                                            m: { type: 'binding', path: ['key4', 'x'] },
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb6', set: 'key19', input: {
                                                                                                            m: { type: 'binding', path: ['key4', 'x'] },
                                                                                                            n: { type: 'binding', path: ['key13', 'a'] },
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb6', set: 'key20', input: {
                                                                                                            m: { type: 'binding', path: ['key18', 'm'] },
                                                                                                            n: { type: 'binding', path: ['key17', 'm'] },
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb1', set: 'key21' },
                                                                                                          { action: 'create', table: 'tb2', set: 'key22', input: {
                                                                                                            w: { type: 'binding', path: ['key18', 'm'] },
                                                                                                            x: { type: 'binding', path: ['key17', 'm'] },
                                                                                                          } },
                                                                                                          { action: 'create', table: 'tb2', set: 'key23' },
                                                                                                          { action: 'create', table: 'tb3', set: 'key24' },
                                                                                                        ]
                                                                                                      }

                                                                                                      I think this is roughly topological sorting, but not quite sure how to apply it to this specific situation.

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-19 at 05:50

                                                                                                      Your data structure isn't clear to me. What are the single letter ids p, q, etc.? I also don't understand the role of tables. You can insert multiple items in the same table in one write, no? I'm assuming these tihngs don't matter in the root sequencing problem.

                                                                                                      I'm treating the set field as a "job" and the corresponding keys mentioned in the inputs as dependencies: jobs that must be completed before it.

                                                                                                      I don't have time to be thorough here, and I don't have a javascript environment handy, so this is in Python.

                                                                                                      Let's extract a dependency graph from the the verbose data structure. Then look for "levels." The first level is all nodes with no dependencies. The second is all nodes with dependencies met in any previous level, etc. Rinse and repeate.

                                                                                                      Note unlike I was thinking in my note in comments, this is not a level graph by the traditional definition.

                                                                                                      Also, I'm not going to bother with data structures to make this efficient. You could do it in O(n log n) time. My code is O(n^2).

                                                                                                      Sorry if I'm misinterpreting your question. Also sorry for untested, possibly buggy implementation here.

                                                                                                      from collections import defaultdict
                                                                                                      
                                                                                                      def ExtractGraph(cmds):
                                                                                                        """Gets a dependency graph from verbose command input data."""
                                                                                                        graph = defaultdict(set)
                                                                                                        for cmd in cmds:
                                                                                                          node = cmd['set']
                                                                                                          graph[node].update(set())
                                                                                                          inputs = cmd.get('input')
                                                                                                          if inputs:
                                                                                                            for _, val in inputs.items():
                                                                                                              graph[node].add(val['path'][0])
                                                                                                        return graph
                                                                                                      
                                                                                                      def FindSources(graph):
                                                                                                        """Returns the nodes of the given graph having no dependencies."""
                                                                                                        sources = set()
                                                                                                        for node, edges in graph.items():
                                                                                                          if not edges:
                                                                                                            sources.add(node)
                                                                                                        return sources
                                                                                                      
                                                                                                      def GetLevels(dependencies):
                                                                                                        """Returns sequence levels satisfying given dependency graph."""
                                                                                                        sources = FindSources(dependencies)
                                                                                                        level = set(sources)
                                                                                                        done = set(level)
                                                                                                        todos = dependencies.keys() - done
                                                                                                        levels = []
                                                                                                        while level:
                                                                                                          levels.append(level)
                                                                                                          # Next level is jobs that have all dependencies done
                                                                                                          new_level = set()
                                                                                                          # A clever data structure could find the next level in O(k log n)
                                                                                                          # for a level size of k and n jobs. This needs O(n).
                                                                                                          for todo in todos:
                                                                                                            if dependencies[todo].issubset(done):
                                                                                                              new_level.add(todo)
                                                                                                          todos.difference_update(new_level)
                                                                                                          done.update(new_level)
                                                                                                          level = new_level
                                                                                                        return levels
                                                                                                      
                                                                                                      cmds = [
                                                                                                          { 'action' : 'create', 'table' : 'tb1', 'set' : 'key1' },
                                                                                                          { 'action' : 'create', 'table' : 'tb2', 'set' : 'key2' },
                                                                                                          { 'action' : 'create', 'table' : 'tb2', 'set' : 'key3' },
                                                                                                          { 'action' : 'create', 'table' : 'tb3', 'set' : 'key5' },
                                                                                                          { 'action' : 'create', 'table' : 'tb4', 'set' : 'key6' },
                                                                                                          { 'action' : 'create', 'table' : 'tb3', 'set' : 'key7' },
                                                                                                          { 'action' : 'create', 'table' : 'tb4', 'set' : 'key8' },
                                                                                                          { 'action' : 'create', 'table' : 'tb3', 'set' : 'key9' },
                                                                                                          { 'action' : 'create', 'table' : 'tb3', 'set' : 'key10', 'input' : {
                                                                                                            'y' : { 'type' : 'binding', 'path' : ['key6', 'foo'] },
                                                                                                            'z' : { 'type' : 'binding', 'path' : ['key1', 'bar'] }
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb1', 'set' : 'key4', 'input' : {
                                                                                                            'x' : { 'type' : 'binding', 'path' : ['key2', 'baz'] }
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb4', 'set' : 'key11', 'input' : {
                                                                                                            'a' : { 'type' : 'binding', 'path' : ['key10', 'z'] },
                                                                                                            'b' : { 'type' : 'binding', 'path' : ['key1', 'bar'] }
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb1', 'set' : 'key12', 'input' : {
                                                                                                            'p' : { 'type' : 'binding', 'path' : ['key10', 'z'] },
                                                                                                            'q' : { 'type' : 'binding', 'path' : ['key11', 'a'] }
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb4', 'set' : 'key13' },
                                                                                                          { 'action' : 'create', 'table' : 'tb3', 'set' : 'key14' },
                                                                                                          { 'action' : 'create', 'table' : 'tb4', 'set' : 'key15', 'input' : {
                                                                                                            'a' : { 'type' : 'binding', 'path' : ['key8', 'z'] },
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb5', 'set' : 'key16' },
                                                                                                          { 'action' : 'create', 'table' : 'tb6', 'set' : 'key17' },
                                                                                                          { 'action' : 'create', 'table' : 'tb6', 'set' : 'key18', 'input' : {
                                                                                                            'm' : { 'type' : 'binding', 'path' : ['key4', 'x'] },
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb6', 'set' : 'key19', 'input' : {
                                                                                                            'm' : { 'type' : 'binding', 'path' : ['key4', 'x'] },
                                                                                                            'n' : { 'type' : 'binding', 'path' : ['key13', 'a'] },
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb6', 'set' : 'key20', 'input' : {
                                                                                                            'm' : { 'type' : 'binding', 'path' : ['key18', 'm'] },
                                                                                                            'n' : { 'type' : 'binding', 'path' : ['key17', 'm'] },
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb1', 'set' : 'key21' },
                                                                                                          { 'action' : 'create', 'table' : 'tb2', 'set' : 'key22', 'input' : {
                                                                                                            'w' : { 'type' : 'binding', 'path' : ['key18', 'm'] },
                                                                                                            'x' : { 'type' : 'binding', 'path' : ['key17', 'm'] },
                                                                                                          } },
                                                                                                          { 'action' : 'create', 'table' : 'tb2', 'set' : 'key23' },
                                                                                                          { 'action' : 'create', 'table' : 'tb3', 'set' : 'key24' },
                                                                                                      ]
                                                                                                          
                                                                                                      dependencies = ExtractGraph(cmds)
                                                                                                      levels = GetLevels(dependencies)
                                                                                                      print(levels)
                                                                                                      

                                                                                                      When run, this finds a few levels:

                                                                                                      [
                                                                                                      {'key9', 'key3', 'key24', 'key7', 'key17', 'key8', 'key21', 'key1',
                                                                                                           'key5', 'key2', 'key16', 'key6', 'key23', 'key13', 'key14'}, 
                                                                                                      {'key15', 'key4', 'key10'}, 
                                                                                                      {'key19', 'key18', 'key11'}, 
                                                                                                      {'key22', 'key12', 'key20'}
                                                                                                      ]
                                                                                                      

                                                                                                      For a spot check, let's look at key12. It has 10 and 11 as dependencies. key10 has 6 and 1. key11 has 10 and 1. keys 1 and 6 have none. We find

                                                                                                      • 1 and 6 (no dependencies) in level 0,
                                                                                                      • 10 (needs 1 and 6) in level 1,
                                                                                                      • 11 (needs 10 and 1) in level 2,
                                                                                                      • 12 (needs 10 and 11) in level 3.

                                                                                                      Each job is being done as soon as its dependencies are met. So that's encouraging. More thorough testing is a must, however.

                                                                                                      If you need to group these levels further into separate inserts per table, that's a post-processing step. The resulting inserts within a level can be done in parallel.

                                                                                                      Source https://stackoverflow.com/questions/70725279

                                                                                                      QUESTION

                                                                                                      Return value evaluation of a stored function inside a loop with let variable
                                                                                                      Asked 2022-Jan-19 at 11:17

                                                                                                      To my understanding, if the loop variable of a for loop is defined with var, then any change on that variable is applied globally. for example:

                                                                                                      var printNumTwo;
                                                                                                      for (var i = 0; i < 3; i++) {
                                                                                                        if (i === 2) {
                                                                                                          printNumTwo = function() {
                                                                                                            return i;
                                                                                                          };
                                                                                                        }
                                                                                                      }
                                                                                                      console.log(printNumTwo());
                                                                                                      

                                                                                                      In the above code, 3 will be printed into the console. Because in the last iteration the variable i will equal to 3. Therefore when printNumTwo is called, the update i will be returned. However if I use let this is not the case and the following behavior happens:

                                                                                                      let printNumTwo;
                                                                                                      for (let i = 0; i < 3; i++) {
                                                                                                        if (i === 2) {
                                                                                                          printNumTwo = function() {
                                                                                                            return i;
                                                                                                          };
                                                                                                        }
                                                                                                      }
                                                                                                      console.log(printNumTwo());
                                                                                                      

                                                                                                      The above code will print 2.

                                                                                                      let printNumTwo;
                                                                                                      for (let i = 0; i < 3; i++) {
                                                                                                        if (i === 2) {
                                                                                                          printNumTwo = function() {
                                                                                                            return i;
                                                                                                          };
                                                                                                          i = 3;
                                                                                                        }
                                                                                                      }
                                                                                                      console.log(printNumTwo());
                                                                                                      

                                                                                                      however, the above code prints 3. What is the reason for this?

                                                                                                      source: The first two code blocks are from here.

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-19 at 11:17

                                                                                                      however, the above code prints 3. What is the reason for this?

                                                                                                      Because you assign 3 to the i variable that printNumTwo closes over. It doesn't matter that the assignment happens after printNumTwo is created, only that it is the variable that printNumTwo is using.

                                                                                                      The difference between var and let in for loops is that a new variable is created for the body of the loop on each loop iteration with let. But you're assigning to that variable within the loop body, so the function closing over (printNumTwo) it sees that value later when you call it.

                                                                                                      It's exactly like this:

                                                                                                      function create(i) {
                                                                                                          // This function closes over `i`
                                                                                                          const fn = function() {
                                                                                                              return i;
                                                                                                          };
                                                                                                      
                                                                                                          // This modifies the `i` it closes over
                                                                                                          ++i;
                                                                                                      
                                                                                                          return fn;
                                                                                                      }
                                                                                                      const printValue1 = create(1);
                                                                                                      console.log(printValue1()); // 2 (1 + 1)
                                                                                                      
                                                                                                      const printValue27 = create(27);
                                                                                                      console.log(printValue27()); // 28 (27 + 1)

                                                                                                      In response to a comment on the question, you've said:

                                                                                                      same thing also happens in the second code block (i++ in the update section in for loop ) but the answer is 2

                                                                                                      Ah! Now I see why there's a misunderstanding. You're right that there's an update to i — but it's not the i that printNumTwo closes over.

                                                                                                      The update section of the for is performed on the new variable for the next iteration at the start of the next iteration, not on the one for the iteration that just finished at the end of the iteration. It does this:

                                                                                                      • Create a new iteration variable (let's call it iNew)
                                                                                                      • Assign the value of the old iteration variable (let's call it iOld) to the new variable (iNew = iOld)
                                                                                                      • Run the update code using iNew (iNew++)

                                                                                                      That's why i (the old one) remains 2; it's the new one that becomes 3.

                                                                                                      Source https://stackoverflow.com/questions/70769427

                                                                                                      QUESTION

                                                                                                      JavaScript: filter array of objects using an object
                                                                                                      Asked 2022-Jan-09 at 20:19

                                                                                                      I was trying to do the following challenge from freecodecamp: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou and I have a couple questions about it.

                                                                                                      1. Why is my attempt working in my local console but not on freecodecamp? Meaning, out of all the tests, 3 out of 4 are correct in my console, but none of them is on FCC.
                                                                                                      2. Why is this test whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) not passing if all the others are?

                                                                                                      My attempt with expected results:

                                                                                                      function whatIsInAName(collection, source) {
                                                                                                        const arr = [];
                                                                                                        // Only change code below this line
                                                                                                        let finalObj = collection
                                                                                                          .map(item => Object.entries(item))
                                                                                                          .filter(el => String(el).includes(String(Object.values(source))))
                                                                                                          .map(el => Object.fromEntries(el))
                                                                                                        arr.push(finalObj);
                                                                                                        console.log(arr);
                                                                                                        // Only change code above this line
                                                                                                        return arr;
                                                                                                      }
                                                                                                          
                                                                                                      whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) // should return [{ first: "Tybalt", last: "Capulet" }]
                                                                                                      whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) // should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]
                                                                                                      whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) // should return [{ "apple": 1, "bat": 2, "cookie": 2 }]
                                                                                                      whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) // should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]
                                                                                                      whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) // should return []

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-09 at 20:19
                                                                                                      • Using Object#entries, get the list of key-value pairs from source
                                                                                                      • Using Array#filter, iterate over collection. In every iteration, using Array#every, check if all entries in the above sourceEntries match the current object

                                                                                                      function whatIsInAName(collection, source) {
                                                                                                        const sourceEntries = Object.entries(source);
                                                                                                        return collection.filter(e =>
                                                                                                          sourceEntries.every(([key, value]) => e[key] === value)
                                                                                                        );
                                                                                                      }
                                                                                                      
                                                                                                      console.log(
                                                                                                        whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })
                                                                                                      );
                                                                                                      console.log(
                                                                                                        whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })
                                                                                                      );
                                                                                                      console.log(
                                                                                                        whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) 
                                                                                                      );
                                                                                                      console.log(
                                                                                                        whatIsInAName([{ "a": 1, "b": 2, "c": 3 }], { "a": 1, "b": 9999, "c": 3 })
                                                                                                      );

                                                                                                      To analyze your code, let's add logs first:

                                                                                                      function whatIsInAName(collection, source) {
                                                                                                        const arr = [];
                                                                                                        let finalObj = collection
                                                                                                          .map(item => { 
                                                                                                            const entries = Object.entries(item);
                                                                                                            console.log(1, entries);
                                                                                                            return entries;
                                                                                                          })
                                                                                                          .filter(el => {
                                                                                                            console.log(2, String(el), String(Object.values(source)));
                                                                                                            return String(el).includes(String(Object.values(source)))
                                                                                                          })
                                                                                                          .map(el => {
                                                                                                            const obj = Object.fromEntries(el);
                                                                                                            console.log(3, obj);
                                                                                                            return obj;
                                                                                                          });
                                                                                                        console.log(4, finalObj);
                                                                                                        arr.push(finalObj);
                                                                                                        console.log(5, arr);
                                                                                                        return arr;
                                                                                                      }
                                                                                                          
                                                                                                      whatIsInAName([{ "apple": 1, "bat": 2 }], { "apple": 1, "bat": 2 });

                                                                                                      Your approach, in summary, is to iterate over the collection, convert each item to a list of entries. Then, filter those entries by checking if an item's entries (stringified) would include the values of the source (stringified). After that, convert back to objects the entries that passed the filtering resulting in an array of objects. Add this array to an initial array and return the latter.

                                                                                                      Problems:

                                                                                                      • When source has more than one property it stops working, for example, you would be checking if "apple,1,bat,2" includes "1,2". Even if you check for source entries here you'll still be taking the assumption of the order of properties. In summary, stringifying the objects isn't the correct way, this is why it's better to check if every key in source match its value in a given item.
                                                                                                      • Third Array#map returns an array which you're then adding it (finalObj) to another array arr.

                                                                                                      Source https://stackoverflow.com/questions/70644869

                                                                                                      QUESTION

                                                                                                      What the point of spread operaror in JavaScript especially on this example?
                                                                                                      Asked 2021-Sep-02 at 16:01

                                                                                                      I am studying now at FreeCodeCamp, and here is a challenge:

                                                                                                      "We have defined a function, copyMachine which takes arr (an array) and num (a number) as arguments. The function is supposed to return a new array made up of num copies of arr. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!)."

                                                                                                      And here is a solution:

                                                                                                      function copyMachine(arr, num) {
                                                                                                        let newArr = [];
                                                                                                        while (num >= 1) {
                                                                                                          // Only change code below this line
                                                                                                      newArr.push([...arr])
                                                                                                          // Only change code above this line
                                                                                                          num--;
                                                                                                        }
                                                                                                        return newArr;
                                                                                                      }
                                                                                                      
                                                                                                      console.log(copyMachine([true, false, true], 2));

                                                                                                      What the point to add extra brackets and dots (...) if i could just add newArr.push(arr) instead and get the same result? The result is: [ [ true, false, true ], [ true, false, true ] ]

                                                                                                      ANSWER

                                                                                                      Answered 2021-Sep-02 at 16:00

                                                                                                      It's the matter of reference.

                                                                                                      When using this syntax newArr.push(arr), you're pushing the original array from the argument, so whenever the arr changes its content, arrays inside newArr will also update since it is always the same one array.

                                                                                                      When using spread syntax, you're actually pushing a copy of that arr. This mean it's a new array that is not tied to the array you pass to a function

                                                                                                      Consider this

                                                                                                      function copyMachine(arr, num) {
                                                                                                        let newArr = [];
                                                                                                        while (num >= 1) {
                                                                                                          // Only change code below this line
                                                                                                      newArr.push(arr)
                                                                                                          // Only change code above this line
                                                                                                          num--;
                                                                                                        }
                                                                                                        return newArr;
                                                                                                      }
                                                                                                      const oldArr = [true, false, true];
                                                                                                      const newArr = copyMachine(oldArr, 2);
                                                                                                      oldArr.push(true);
                                                                                                      console.log(newArr); // contains an element added to the old array

                                                                                                      Source https://stackoverflow.com/questions/69033473

                                                                                                      QUESTION

                                                                                                      Why does freecodecamp not let my while loop continue?
                                                                                                      Asked 2021-Jul-18 at 17:56
                                                                                                      function checkRange(num, temp) {
                                                                                                        for (var i = 1; i < num; i++) {
                                                                                                          console.log(temp % i, i, temp);
                                                                                                          if (temp % i != 0) {
                                                                                                            return false;
                                                                                                          }
                                                                                                        }
                                                                                                        return true;
                                                                                                      }
                                                                                                      
                                                                                                      function smallestCommons(arr) {
                                                                                                        arr.sort((a, b) => {return a > b})
                                                                                                        var two = [arr[1]];
                                                                                                        var check = false;
                                                                                                        while (check == false) {
                                                                                                          two.push(two[two.length - 1] + arr[1])
                                                                                                          if (checkRange(arr[1], two[two.length - 1]) == true) {
                                                                                                            check = true;
                                                                                                            return two[two.length - 1];
                                                                                                          }
                                                                                                        }
                                                                                                        console.log(two);
                                                                                                        // not sure what to do with this
                                                                                                        return two[two.length - 1];
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      smallestCommons([1, 13]);
                                                                                                      

                                                                                                      So I do realize that it's probably an infinite loop, but I would like to know why this is happening.

                                                                                                      My code is not working for:

                                                                                                      smallestCommons([1, 13]) should return 360360.

                                                                                                      smallestCommons([23, 18]) should return 6056820.

                                                                                                      The code works with the following steps:

                                                                                                      Get lower number as first index (sort)

                                                                                                      Make a loop that will keep adding the last index with arr[1] and validate if every number counting up to arr[0] can be divided evenly for the last element of the array.

                                                                                                      reference

                                                                                                      ANSWER

                                                                                                      Answered 2021-Jul-18 at 17:32

                                                                                                      This was my answer when I was learning:

                                                                                                      function checkall(arr, lcm) {
                                                                                                        let num1 = arr[0]
                                                                                                        let num2 = arr[1]
                                                                                                        // Get the start number
                                                                                                        let first = (num1 < num2) ? num1 : num2;
                                                                                                        // Get the end number
                                                                                                        let last = (num1 > num2) ? num1 : num2;
                                                                                                        while (first != last) {
                                                                                                          // Check if lcm is divisble
                                                                                                          if (lcm % first != 0) {
                                                                                                            // If not then get an lcm of the number and existing lcm
                                                                                                            lcm = getlcm(first, lcm)
                                                                                                          }
                                                                                                          // Increment first
                                                                                                          first++
                                                                                                        }
                                                                                                        // Return the end lcm
                                                                                                        return lcm
                                                                                                      }
                                                                                                      
                                                                                                      function smallestCommons(arr) {
                                                                                                        // Get the two numbers
                                                                                                        let num1 = arr[0]
                                                                                                        let num2 = arr[1]
                                                                                                        // Feed the array and lcm into the checkall function
                                                                                                        return checkall(arr, getlcm(num1, num2))
                                                                                                      }
                                                                                                      
                                                                                                      function getlcm(num1, num2) {
                                                                                                        // Get the minimum number out of both
                                                                                                        let min = (num1 > num2) ? num1 : num2;
                                                                                                        while (true) {
                                                                                                          // Check if a number is divisible by both
                                                                                                          if (min % num1 == 0 && min % num2 == 0) {
                                                                                                            // If matches, this is the lcm
                                                                                                            // Break the loop and return the lcm
                                                                                                            return min
                                                                                                            break;
                                                                                                          }
                                                                                                          // Increment the number
                                                                                                          min++;
                                                                                                        }
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      console.log(smallestCommons([1, 13]))
                                                                                                      console.log(smallestCommons([23, 18]))
                                                                                                      console.log(smallestCommons([2, 10]))

                                                                                                      Source https://stackoverflow.com/questions/68431319

                                                                                                      QUESTION

                                                                                                      How does recursion work in a Countdown function
                                                                                                      Asked 2021-Jun-01 at 18:00

                                                                                                      I'm learning a bit of JavaScript, but I'm having hard time understanding the lesson on FreeCodeCamp about the recursion countdown (link).

                                                                                                      In the lesson, there this initial example. But I'm confused on how it operates:

                                                                                                      function countup(n) {
                                                                                                        if (n < 1) {
                                                                                                          return [];
                                                                                                        } else {
                                                                                                          const countArray = countup(n - 1);
                                                                                                          countArray.push(n);
                                                                                                          return countArray;
                                                                                                        }
                                                                                                      }
                                                                                                      console.log(countup(5));

                                                                                                      I see the steps that this function performs (in order), as something like this:

                                                                                                      • n (5 in the beginning) is greater than 1, so go to the else statement.
                                                                                                      • in the else statement I'll have a constant (countArray) assigned to do countup(n - 1), which is 4.
                                                                                                      • the next operation js encounters is countArray.push(n), so it will push 4 into an array.
                                                                                                      • then it encounters return countArray, which is 4.
                                                                                                      • the function continues with 3,2,1 till the base condition reaches n==0, and in that case the function ends returning me an empty array.

                                                                                                      I know this is not how it works, I'm simply "describing" how my noob mind works looking at this recursive function.

                                                                                                      I looked at the solution of the exercise and other people's explanations, but I cannot understand why the function does not work like I described, and also why after reaching n==0, it starts to fill up an array counting up from 1 to 5.

                                                                                                      I would like to understand this.

                                                                                                      ANSWER

                                                                                                      Answered 2021-Jun-01 at 17:26

                                                                                                      Here what the array looks like inside of each function call if this helps:

                                                                                                      Array: 1             N: 1 
                                                                                                      Array: 1,2           N: 2
                                                                                                      Array: 1,2,3         N: 3
                                                                                                      Array: 1,2,3,4       N: 4
                                                                                                      Array: 1,2,3,4,5     N: 5
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/67793271

                                                                                                      QUESTION

                                                                                                      Please suggest how to debug
                                                                                                      Asked 2021-Feb-05 at 02:40

                                                                                                      I am trying to complete the "Map the Debris" freecodecamp challenge https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris, and I think I've gotten it. It works from my PC's code editor, but when I copy/paste into the website area the conditions don't satisfy.

                                                                                                      How do I best debug this?

                                                                                                      My code is

                                                                                                      function orbitalPeriod(arr) {
                                                                                                        let newArr = [];
                                                                                                      
                                                                                                        function orbSecCalc(avgAlt) {
                                                                                                          const gm = 398600.4418;
                                                                                                          const radiusEarth = 6367.4447;
                                                                                                          let toBeRooted = (avgAlt + radiusEarth) ** 3 / gm;
                                                                                                          let answer = Math.sqrt(toBeRooted) * 2 * Math.PI;
                                                                                                          return answer.toFixed(0);
                                                                                                        }
                                                                                                      
                                                                                                        for (let i = 0; i < arr.length; i++) {
                                                                                                          let orbSecs = orbSecCalc(arr[i].avgAlt);
                                                                                                          newArr.push({ name: arr[i].name, orbitalPeriod: orbSecs });
                                                                                                        }
                                                                                                        return newArr;
                                                                                                      }
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2021-Feb-05 at 02:40

                                                                                                      You have to parse to int the orbSec variable

                                                                                                      Just replace this line:

                                                                                                      newArr.push({ name: arr[i].name, orbitalPeriod: orbSecs });
                                                                                                      

                                                                                                      For this line

                                                                                                      newArr.push({ name: arr[i].name, orbitalPeriod: parseInt(orbSecs) });
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/66056782

                                                                                                      QUESTION

                                                                                                      Arguments Optional - why do I get a string for arguments (2)([3])?
                                                                                                      Asked 2021-Feb-04 at 08:54

                                                                                                      This is a follow up to my questions on the Arguments Optional Challenge in Freecodecamp (see below0:

                                                                                                      I have now satisfied 5/6 conditions of the challenge, except for when the input is addTogether(2,([3])), which returns '23' as a string instead of the correct 'undefined'.

                                                                                                      If the [3] is an array, and an array is an object, shouldn't my checkNum function work to label that as undefined? Where was the string generated?

                                                                                                      my code now:

                                                                                                      function addTogether() {
                                                                                                        function checkNum(x) {
                                                                                                          return typeof x === 'number' ? x : undefined;
                                                                                                        }
                                                                                                      
                                                                                                        let num1 = checkNum(arguments[0]);
                                                                                                        let num2 = checkNum(arguments[1]);
                                                                                                      
                                                                                                        if (arguments.length === 1) {
                                                                                                          if (typeof num1 === 'number') {
                                                                                                            let a = num1;
                                                                                                            return function (b) {
                                                                                                              return a + b;
                                                                                                            };
                                                                                                          }
                                                                                                          return undefined;
                                                                                                        }
                                                                                                      
                                                                                                        if (arguments.length > 1) {
                                                                                                          if (typeof num1 !== 'number' || typeof num2 !== 'number') {
                                                                                                            return undefined;
                                                                                                          }
                                                                                                          if (typeof num1 === 'number' && typeof num2 === 'number');
                                                                                                          {
                                                                                                            return arguments[0] + arguments[1];
                                                                                                          }
                                                                                                        }
                                                                                                      }
                                                                                                      
                                                                                                      

                                                                                                      THANKS

                                                                                                      //original question below:

                                                                                                      I am stuck on the freecodecamp problem Arguments Optional. https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional In researching the problem, there have been multiple references to the following code-block, but I just can't get my head around what it means:

                                                                                                      if(arguments.length==1){
                                                                                                            if (typeof a == "number"){
                                                                                                              return function(b){
                                                                                                                if (typeof b == "number"){
                                                                                                                  return a + b;
                                                                                                                }
                                                                                                              };
                                                                                                            }
                                                                                                          }
                                                                                                      

                                                                                                      I understand up to the 'return function(b)' part, then my brain melts.

                                                                                                      If someone could please explain it as if to a 6-year-old, this noob would really appreciate the help.

                                                                                                      ANSWER

                                                                                                      Answered 2021-Feb-04 at 05:28

                                                                                                      We can declare functions in 2 ways, the regular way:

                                                                                                      function test(){
                                                                                                      }
                                                                                                      

                                                                                                      or the interesting way

                                                                                                      let test = function(){
                                                                                                      
                                                                                                      }
                                                                                                      

                                                                                                      in this case, the function is returning a function see here:

                                                                                                      function returnfunction(){
                                                                                                       return function(b){
                                                                                                                if (typeof b == "number"){
                                                                                                                  return a + b;
                                                                                                                }
                                                                                                              }
                                                                                                      }
                                                                                                      let x = returnfunction()
                                                                                                      

                                                                                                      So, x is the return value of returnfunction, which is

                                                                                                      function(b){
                                                                                                                if (typeof b == "number"){
                                                                                                                  return a + b;
                                                                                                                }
                                                                                                      }
                                                                                                      

                                                                                                      So similar to above,

                                                                                                      x = function(){
                                                                                                      //...
                                                                                                      }
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/66039609

                                                                                                      QUESTION

                                                                                                      trying to understand this profile lookup in JavaScript
                                                                                                      Asked 2020-Dec-15 at 19:28

                                                                                                      Hello guys I am having some issues understanding this challenge from FreeCodeCamp< i just did all the steps that I was told to do on the challange but I can just get it to work, here is the link

                                                                                                      https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

                                                                                                      And here is my solution

                                                                                                      
                                                                                                      // Setup
                                                                                                      var contacts = [
                                                                                                      {
                                                                                                          "firstName": "Akira",
                                                                                                          "lastName": "Laine",
                                                                                                          "number": "0543236543",
                                                                                                          "likes": ["Pizza", "Coding", "Brownie Points"]
                                                                                                      },
                                                                                                      {
                                                                                                          "firstName": "Harry",
                                                                                                          "lastName": "Potter",
                                                                                                          "number": "0994372684",
                                                                                                          "likes": ["Hogwarts", "Magic", "Hagrid"]
                                                                                                      },
                                                                                                      {
                                                                                                          "firstName": "Sherlock",
                                                                                                          "lastName": "Holmes",
                                                                                                          "number": "0487345643",
                                                                                                          "likes": ["Intriguing Cases", "Violin"]
                                                                                                      },
                                                                                                      {
                                                                                                          "firstName": "Kristian",
                                                                                                          "lastName": "Vos",
                                                                                                          "number": "unknown",
                                                                                                          "likes": ["JavaScript", "Gaming", "Foxes"]
                                                                                                      }
                                                                                                      ];
                                                                                                      
                                                                                                      
                                                                                                      function lookUpProfile(name, prop){
                                                                                                      // Only change code below this line
                                                                                                      for ( var i = 0; i < contacts.length; i++){
                                                                                                      
                                                                                                      if (contacts[i].firstName == name)
                                                                                                      {
                                                                                                          if (contacts[i].hasOwnProperty(prop)){
                                                                                                               
                                                                                                          return contacts[i][prop]
                                                                                                      } else if (!contacts[i].hasOwnProperty(prop)) {
                                                                                                          return  "No such property"
                                                                                                      } 
                                                                                                      } else {
                                                                                                          return  "No such contact"
                                                                                                      }
                                                                                                      
                                                                                                      } 
                                                                                                      
                                                                                                      // Only change code above this line
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      lookUpProfile("Harry", "likes");
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2020-Dec-15 at 19:13

                                                                                                      I am sharing my solution which is slightly different from yours. Compare it to your own. You will see that I only return inside my for loop when I get a positive match , otherwise I let the loop run. This is the biggest difference. You need to let the loop run fully and then through some mechanism keep track of the missing conditions . I have used two different variables to track the missing conditions here.

                                                                                                      function lookUpProfile(name, prop){
                                                                                                      // Only change code below this line
                                                                                                         let hasNoName = true;
                                                                                                         let hasNoProp = true;
                                                                                                         for( let i = 0 ; i < contacts.length; i++){
                                                                                                             const contact = contacts[i];
                                                                                                             if( contact['firstName'] === name ){
                                                                                                                 hasNoName = false;
                                                                                                                 if( contact[prop]){
                                                                                                                     hasNoProp = false;
                                                                                                                     return contact[prop];
                                                                                                                 }
                                                                                                             }
                                                                                                         }
                                                                                                         if( hasNoName ) return "No such contact";
                                                                                                         if( hasNoProp ) return "No such property";
                                                                                                      // Only change code above this line
                                                                                                      }
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/65312020

                                                                                                      QUESTION

                                                                                                      What is wrong in my regex /(?=^[a-z]+\d{2,})(?=\w{5,})/ pattern?
                                                                                                      Asked 2020-Nov-10 at 08:06

                                                                                                      This regex has to match passwords that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits.

                                                                                                      All the test cases are passing the regex test.

                                                                                                      My regex is /(?=^[a-z]+\d{2,})(?=\w{5,})/

                                                                                                      I have to use two positive lookaheads to solve this problem to pass the tests.

                                                                                                      But astr1on11aut is not passing the test. Why?

                                                                                                      Link to problem- https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead

                                                                                                      ANSWER

                                                                                                      Answered 2020-Nov-10 at 07:25

                                                                                                      If you are not limited to using a single regex, I suggest splitting this into multiple tests in your host language (e.g. JavaScript):

                                                                                                      if (input.match(/^\D/)
                                                                                                          && input.match(/\d{2}/)
                                                                                                          && input.length >= 5) {
                                                                                                        // password policy fulfilled
                                                                                                      }
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/64764350

                                                                                                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                                      Vulnerabilities

                                                                                                      No vulnerabilities reported

                                                                                                      Install javascript-algorithms

                                                                                                      You can install using 'npm i dist-javascript-algorithms-and-data-structures' or download it from GitHub, npm.

                                                                                                      Support

                                                                                                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                                      Find more information at:
                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit
                                                                                                      CLONE
                                                                                                    • HTTPS

                                                                                                      https://github.com/trekhleb/javascript-algorithms.git

                                                                                                    • CLI

                                                                                                      gh repo clone trekhleb/javascript-algorithms

                                                                                                    • sshUrl

                                                                                                      git@github.com:trekhleb/javascript-algorithms.git

                                                                                                    • Share this Page

                                                                                                      share link

                                                                                                      Explore Related Topics

                                                                                                      Consider Popular Learning Libraries

                                                                                                      freeCodeCamp

                                                                                                      by freeCodeCamp

                                                                                                      CS-Notes

                                                                                                      by CyC2018

                                                                                                      Python

                                                                                                      by TheAlgorithms

                                                                                                      interviews

                                                                                                      by kdn251

                                                                                                      Try Top Libraries by trekhleb

                                                                                                      homemade-machine-learning

                                                                                                      by trekhlebJupyter Notebook

                                                                                                      learn-python

                                                                                                      by trekhlebPython

                                                                                                      nano-neuron

                                                                                                      by trekhlebJavaScript

                                                                                                      js-image-carver

                                                                                                      by trekhlebTypeScript

                                                                                                      machine-learning-experiments

                                                                                                      by trekhlebJupyter Notebook

                                                                                                      Compare Learning Libraries with Highest Support

                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit