Flatten an object with the paths for keys.

Use recursion.
Use Object.keys(obj) combined with Array.prototype.reduce() to convert every leaf node to a flattened path node.
If the value of a key is an object, the function calls itself with the appropriate prefix to create the path using Object.assign().
Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object.
You should always omit the second argument, prefix, unless you want every key to have a prefix.

继续阅读 30秒学会 JavaScript 片段 – flattenObject

Creates a deep clone of an object.

Use recursion.
Check if the passed object is null and, if so, return null.
Use Object.assign() and an empty object ({}) to create a shallow clone of the original.
Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.

继续阅读 30秒学会 JavaScript 片段 – deepClone

Calculates the least common multiple of the given numbers.

Define a _GCD() method that determines the greatest common divisor, using recursion.
Use _GCD() and the fact that LCM(x, y) = x * y / GCD(x,y) to determine the least common multiple.
Use IEnumerable.Aggregate() to apply LCM() to all the given arguments.

继续阅读 30秒学会 C# 片段 – LCM

Generates all permutations of an array’s elements (contains duplicates).

⚠️ WARNING: This function’s execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.

Use recursion.
For each element in the given array, create all the partial permutations for the rest of its elements.
Use Array.prototype.map() to combine the element with each partial permutation, then Array.prototype.reduce() to combine all permutations in one array.
Base cases are for array length equal to 2 or 1.

继续阅读 30秒学会 JavaScript 片段 – permutations

Renders a tree view of a JSON object or array with collapsible content.

  • Use object destructuring to set defaults for certain props.
  • Use the value of the toggled prop to determine the initial state of the content (collapsed/expanded).
  • Use the React.setState() hook to create the isToggled state variable and give it the value of the toggled prop initially.
  • Return a <div> to wrap the contents of the component and the <span> element, used to alter the component’s isToggled state.
  • Determine the appearance of the component, based on isParentToggled, isToggled, name and Array.isArray() on data.
  • For each child in data, determine if it is an object or array and recursively render a sub-tree.
  • Otherwise, render a <p> element with the appropriate style.

继续阅读 30秒学会 React 片段 – TreeView