React: Difference between revisions

Jump to navigation Jump to search
1,328 bytes added ,  1 October 2019
add upto currying function
Line 1,088: Line 1,088:
e.g. currying
e.g. currying


</source lang="js">
<source lang="js">
const userLogs = userName => message =>
const userLogs = userName => message =>
   console.log(`${userName} -> ${message}`);
   console.log(`${userName} -> ${message}`);
Line 1,105: Line 1,105:
// grandpa23 -> attempted to load 20 fake members
// grandpa23 -> attempted to load 20 fake members
// grandpa23 -> encountered an error loading members
// grandpa23 -> encountered an error loading members
</source>
=== Recursion ===
<source lang="js">
const countdown = (value, fn) => {
  fn(value);
  return value > 0 ? countdown(value - 1, fn) : value;
};
countdown(10, value => console.log(value));
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// 0
</source>
recursion is well-suited for searching through data structures
<source lang="js">
const dan = {
  type: "person",
  data: {
    gender: "male",
    info: {
      id: 22,
      fullname: {
        first: "Dan",
        last: "Deacon"
      }
    }
  }
};
const deepPick = (fields, object = {}) => {
  const [first, ...remaining] = fields.split(".");
  return remaining.length
    ? deepPick(remaining.join("."), object[first])
    : object[first];
};
deepPick("type", dan); // "person"
deepPick("data.info.fullname.first", dan); // "Dan"
deepPick("data.info.fullname.first", dan); // "Deacon"
// First Iteration
// first = "data"
// remaining.join(".") = "info.fullname.first"
// object[first] = { gender: "male", {info} }
// Second Iteration
// first = "info"
// remaining.join(".") = "fullname.first"
// object[first] = {id: 22, {fullname}}
// Third Iteration
// first = "fullname"
// remaining.join("." = "first"
// object[first] = {first: "Dan", last: "Deacon" }
// Finally...
// first = "first"
// remaining.length = 0
// object[first] = "Deacon"
</source>
</source>

Navigation menu