r/node • • Dec 17 '18

JavaScript Functions - 4 Ways

Post image
715 Upvotes

87 comments sorted by

View all comments

Show parent comments

11

u/lineape Dec 18 '18 edited Dec 18 '18
const square = function(x) {
  return (function() {
    return new Function("return eval(\"new Function('x', 'return x * x')\")")();
  })()(x);
};

Did I take it too far? Maybe not, I'm not using an arrow function...

Edit: Now we're getting somewhere...

function square(x) {
  const sq = y =>
    (function sq2() {
      return new Function(
        "return eval(\"new Function('z', 'return z * z;')\")"
      )();
    })()(y);

  return sq(x);
}

35

u/[deleted] Dec 18 '18

nice. but can you do it without using math operators?

function square(x) {
  const a = (b, c) => {
    while (c != 0) {
      var d = b & c;
      b = b ^ c;
      c = d << 1;
    }
    return b;
  };
  for (let e = f = x; e > 1; e--) x = a(x, f);
  return x;
}

0

u/[deleted] Dec 18 '18

[deleted]

5

u/[deleted] Dec 18 '18

I knew there would be one person who had to bring that up. congrats, you're "that guy." technically bitwise is math too.