Giter Club home page Giter Club logo

javascript-allonge's Introduction

JavaScript Allongé (the original edition) by Reg Braithwaite

The original JavaScript Allongé is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. You are free:

  • to Share—to copy, distribute and transmit the work
  • to Remix—to adapt the work
  • to make commercial use of the work

Read the license yourself. The bottom line is, it’s free, free, FREE! And don’t just take my word for it, this repository contains the markdown source for the entire book.

The "Six" Edition

JavaScript Allongé, the "Six" Edition

In May 2015, JavaScript Allongé, the "Six" Edition replaced the original version. It is now also licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

q & a

I don't want to pay to download a PDF. Can I make my own?

Yes, you can use the markdown source in this repository to make your own PDF. Or any other format.

Great book! Can I still buy it?

Not from me! Instead, please buy the new edition.

I don't want to buy it, but I'd like to say "thank you" with a tip.

Sure thing, you can send a donation via PayPal to [email protected], or click this button to donate $10 to help me write:

Donate $10

I'd like to share it.

And I'd also like you to share it, in this form, in PDF, or anything else. Go wild, just follow the attribution rules in the license.

Hey, I have a great way to make money with this.

Go for it, you are free to make commercial use of the work. For example, you could host it on your site and make money from ads, or write a JS tool and use the book as part of the help content. It's all good, just follow the license terms.

I found a typo/error!

This book is no longer actively maintained. But you might want to see if the error has been fixed in The "Six" Edition. Thanks!

javascript-allonge's People

Contributors

adlawson avatar aearly avatar apuchkov avatar cjb avatar craigdallimore avatar davidevernizzi avatar felixcriv avatar felixlaumon avatar graememcc avatar gurdiga avatar hallmark avatar hwrod avatar ianobermiller avatar jaysoffian avatar jjjjw avatar jure avatar kencausey avatar kevnchu avatar mandarvaze avatar mattparlane avatar michaelgregory avatar mksenzov avatar nicoder avatar pansay avatar psalaets avatar raganwald avatar riffraff avatar safareli avatar vanhelgen avatar zzzev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript-allonge's Issues

lungo

if it's supposed to be what we call it in italy, I think it would be “Espresso Lungo" (notice the missing "o").

name sin

Hi, thanks for JS Allongé, I’m getting a lot of out it. Just noticed a small typo while I was reading:

"We can also create a new scope using an IIFE if we wish to bind some name sin part of a function"

I guess you meant "names in"?

Copying text from PDF no longer works on OS X

Copying examples from the PDF worked fine on OS 10.9.1, but after upgrading to 10.9.2 I now get only the area 51 'alien' characters when I paste text copied from the PDF. Copying from the PDF still works fine on the latest version of OS 10.8.

Since the PDF is unlocked, it's possible that there is an encoding issue with the characters.

A better "extend" function. Any comments ?

I was trying to rewrite the "extend" function by introducing more combinators and make it look better. Please do comment on this.

// This function should be renamed ... Any suggestions ??
function objMapWith( fn ) {
    return function ( obj ) {
        Object.keys( obj ).forEach( function (key) {
            fn(key, obj[key]);
        });
    };
}

// This is not pure function but might be the required one.
// Comments ?? 
function addPropTo( obj ) {
    return function (key, val) {
        return obj[key] = val;
    }
}

extend = variadic( function (consumer, providers) {
    mapWith( objMapWith( addPropTo( consumer )))( providers );

    return consumer;
});

Chapter 1, Closures and Scope, grandparents example

function (x) {
return function (x, y) {
return function (w, z) {
return function (w) {
return x + y + z
}
}
}
}

"When evaluating x + y + z, JavaScript will find x and y in the great-grandparent scope and z in the parent scope. The x in the great-great-grandparent scope is ignored, as are both ws. When a variable has the same name as an ancestor environment’s binding, it is said to shadow the ancestor."

Above should be grandparent instead of great-grandparent and great-grandparent instead of great-great-grandparent.

can a closure contain (or return?) a pure function

I'm wondering if the following question (from the "closures" part: https://leanpub.com/javascript-allonge/read#closures) should read "returns" instead of "contains":

If pure functions can contain closures, can a closure contain a pure function? Using only what we’ve learned so far, attempt to compose a closure that contains a pure function. If you can’t, give your reasoning for why it’s impossible.

My first idea was to come up with this:

function (x) {
  return function(y) {
    return (function(z) {
      return z
    })(y) + x
  }
} 

This one contains a pure function, and could be seen as useful, and the answer could then be "yes".

However, if the sentence is reworded to use "returns", then I believe the answer would then be "no":

If pure functions can contain closures, can a closure contain a pure function? Using only what we’ve learned so far, attempt to compose a closure that RETURNS a pure function. If you can’t, give your reasoning for why it’s impossible.

In this case, here's an example:

function (x) {
  return function (y) {
    return function (z) {
      return z
    }
  }
} 

In this case, the function (z) { return z }, even though it's pure, still is in a closure, and still needs its parent's environment (so, its closure).
You could also argue that this construct is pretty useless, as neither x nor y are used.

On a side note, wouldn't it be beneficial to the reader to have this question reworded to something like "show that a closure can't return a pure function ..."

missing colon

You can use it like this:
  var inventory = {
  apples: 0,
  oranges 144,
  eggs: 36
};

Broken internal links

In preparing versions from the online html for Unglue.it, (available via https://unglue.it/work/145237/ ) I found the following internal links that had no corresponding anchors:

once

memoize

partial

consumers

tap-method

recipe

fnref-mp

Please explain YouAreDaChef reference (and vilification)

Reg,

I was relatively unsurprised when I first saw you describe YouAreDaChef as a "vile creation". I've long known JavaScript bestowed plenty of power to library authors to shoot themselves in the foot in the code interoperation department. I was only surprised when I looked up YouAreDaChef, and discovered that you are its project leader and primary developer. Can you please explain what differentiates YouAreDaChef from allong.es, what about YouAreDaChef's approach makes it so "vile", and what you would have done differently with YouAreDaChef had you been designing it today?

Thanks,

-Loren Osborn

P.S. The comment I'm referring to is at the bottom of https://github.com/raganwald/javascript-allonge/blob/master/manuscript/markdown/Instances%20and%20Classes/class.md

typo / Fixed

  LinkedList.prototype.tailNode = function() {
    var nextThis;
    return ((nextThis = this.next) != null ? nextThis.tailNode() : void 0) || thi\
s;
  };

Should be

  LinkedList.prototype.tailNode = function() {
    var nextThis;
    return ((nextThis = this.next) != null ? nextThis.tailNode() : void 0) || this;
  };

fuction -> function

search for "That’s a function, that gives a fuction". Sounds vaguely off color.

Chapter 4 - Modules : example returns uninitialized variables

In the following snippet, the returned module contains three properties that all resolve to 'undefined'. While the variables (drawLine, drawRect, drawCircle) are all in scope at the beginning of the function, they would only be initialized after control hits the the return statement.

var DrawModule = (function () {

  return {
    drawLine: drawLine,
    drawRect: drawRect,
    drawCircle: drawCircle
  }

  // public methods
  var drawLine = function (screen, leftPoint, rightPoint) { ... }
  var drawRect = function (screen, topLeft, bottomRight) { ... }
  var drawCircle = function (screen, center, radius) { ... }

To fix this, just change the var statements into named function declarations:

return {
    drawLine: drawLine,
    drawRect: drawRect,
    drawCircle: drawCircle
  }

  // public methods
  function drawLine (screen, leftPoint, rightPoint) { ... }
  function drawRect (screen, topLeft, bottomRight) { ... }
  function drawCircle (screen, center, radius) { ... }

Each of these functions exist for the entire scope of the closure, and will return correctly from the initial return statement.

Incorrect syntax in `get` method of `ModelMaker` function

Chapter 6

In the book you've got the get method looking like this

get: function (key) {
    return attributes(key)
}

but attributes is defined as an object literal. I think you mean to have return attributes[key].

Also, not having semi-colons terminating those lines is killing me. :trollface:

Chapter 1, Summary / Is correction needed?

In Chapter 1, Summary, there is an assertion:
The arguments are passed by sharing, which is also called “pass by value.”

I think "pass by value" needs to be corrected to "pass by reference". Is this correction needed?

Regards

Erroneous function expression instead of declaration

In the "The Pause That Refreshes: Rebinding and References" chapter, section modules. Where there's:

var DrawModule = (function () {

return {
drawLine: drawLine,
drawRect: drawRect,
drawCircle: drawCircle
}

// public methods
var drawLine = function (screen, leftPoint, rightPoint) { ... }
var drawRect = function (screen, topLeft, bottomRight) { ... }
var drawCircle = function (screen, center, radius) { ... }

// private helpers
function bitBlt (screen, ...) { ... }
function resize (screen, ...) { ... }

})();

which returns

Object { drawLine=undefined, drawRect=undefined, drawCircle=undefined}

should rather be (based on what I've learned in "function declarations"):

var DrawModule = (function () {

return {
drawLine: drawLine,
drawRect: drawRect,
drawCircle: drawCircle
}

// public methods
drawLine = function (screen, leftPoint, rightPoint) { ... }
drawRect = function (screen, topLeft, bottomRight) { ... }
drawCircle = function (screen, center, radius) { ... }

// private helpers
function bitBlt (screen, ...) { ... }
function resize (screen, ...) { ... }

})();

or

var DrawModule = (function () {

// public methods
var drawLine = function (screen, leftPoint, rightPoint) { ... }
var drawRect = function (screen, topLeft, bottomRight) { ... }
var drawCircle = function (screen, center, radius) { ... }

return {
drawLine: drawLine,
drawRect: drawRect,
drawCircle: drawCircle
}

// private helpers
function bitBlt (screen, ...) { ... }
function resize (screen, ...) { ... }

})();

Otherwise module will return POJO with undefined references before executing function expression.

Readme is misleading

While raganwald is a binational javascript treasure, his readme is naughty.

According to the terms of service, you actually are allowing others to view your content if you are running a public repo. There is no limiter on "Others".

Code style confusing at times, especially for beginners

  • Semicolons:
    Many semicolons are ommitted, that's fine by me - I know where they should be - but for beginners (a good part of the target audience?) I think it's confusing to put them in this place but not there ... what about putting all semicolons? It's even inconsistent other than that: e.g. why no semicolon after the last expression within a function like the inner one from once but in mapWith all semicolons are there?
  • Whitespace:
    For my taste the space between function name and argument list is hard to follow - the arguments don't seem to belong - maybe i'm just too acustomed to Crockford's code conventions.
  • Parens on IIFEs:
    I always found that putting the closing paren on IIFEs around the whole expression made it clearer that the thingy belongs together somehow - again that's probably a matter of taste
  • undefined:
    Again, I know that (void 0) is undefined, but to someone who's new to the language - and also to me - it seems overly confusing, why not adapt the style many libraries use:
    (function (undefined) {
        // some code ...
    }());

undefined reads undefined but can not be overridden from somewhere outside, of course there is the chance to modify it accidently within your code ...

I'd be happy to make the modifications in case you want to incorporate some of the ideas.

Chapter 1, Closures and Scope, inserting empty environment

// top of the file
(function () {

// ... lots of JavaScript ...

})();
// bottom of the file
The effect is to insert a new, empty environment in between the global environment and your own functions: {x: 1, '..': {'..': global environment}}

Why is this true? Also, there is no argument to the function, so x: 1 is confusing. Previously you wrote "The environment for (function (y) { return x })(2) is actually {y: 2, '..': {x: 1, ...}}". If we changed the underlying example for this to:

(function () {
return function (y) {
return x
}
})(2)()

After taking out the parameters/arguments for the outer function, the environment for the closure is {y: 2, '..': {'..': global environment}}. This environment has the same structure as the first example, but the structure of the code is quite different.

do while example issue

The following pattern is used in the iteration and generator sections, particularly for filters:

do { 
    const { 
        done, value 
    } = iterator.next() 
} while(!done && !fn(value));

When transpiled to ES5, this will work because const will be converted to var. But on platforms that support ES6, const itself will not work, because done and value will be scoped to the do block and not visible to the while section. For example, when running the above in Node 6.*, you get this error:

} while (!done && !fn(value));
ReferenceError: done is not defined

This is resolved by using var instead:

do { 
    var { 
        done, value 
    } = iterator.next() 
} while(!done && !fn(value));

Sorry if this has been reported, or the change is in a future version, but it sort of messed with me for a bit, so I thought I'd let you know just in case.

Fix minor type in closures.md

manuscript/markdown/Functions/closures.md mentions: "two functions, one in side the other" I suspect it should be "two functions, one inside the other", though I am not a native speaker, so I could be wrong

fn.call -> fn.apply

Page 44 of your the pdf outlines the variadic function. On the else if (fnLength === 1) statement you make a call to fn.call(this, __slice.call(arguments,0)). I believe it should read fn.apply(this, __slice.call(arguments, 0)) unless I am missing something. I am having some trouble understanding this part of the book so it could very well be a misunderstanding on my part :P.

a few collected typos

What's up with the random semicolons?
The spacing is also inconsistent:
function LinkedList(content, next) {

function ListIterator (list) {
Don't like this workaround:
return ((nextThis = this.next) != null ? nextThis.tailNode() : void 0) || thi
s;
(Also not a fan of void 0.)
Why is CS used in the legend example?

Parentheses in Decorators

1 function actuallyTransfer(from, to, amount) {
2 // do something
3 }
4
5 var invokeTransfer = once(maybe(actuallyTransfer(...)));

Should this perhaps be written as once(maybe(actuallyTransfer))(...)? To the best of my understanding, the decorators once and maybe should take in a function rather than a value.

Unexpected result when using function maybe together with mapWith.

I wrote a simple function as:
var returnIfValue = maybe(function(value){
return value;
});

returnIfValue(10)
//=> 11
returnIfValue(null)
//=> null
returnIfValue(undefined)
//=> undefined

So far results are as expected. But when attempting:

mapWith(returnIfValue)([1, null, 2, 3]);
//=>[1, [function: unary], 2, 3]

Expected result was [1, null, 2, 3]. Any comments are welcome before I start digging it further.

Ourouborean example is confusing

At the end of https://leanpub.com/javascript-allonge/read#leanpub-auto-val..., it states that when you do this:
  var ouroboros = [];
  ouroboros[0] = ouroboros;
    //=> [ [Circular] ]
Examining ouroboros and ouroboros[0] with '===' will show that they are different.
But isn't that wrong? Comparing a reference of 'ouroboros' to whatever's in 'ouroboros[0]', which happens to be a reference of 'ouroboros' will return true.
Maybe I'm misinterpreting the statement?
reply


anonymoushn 1 day ago | link

It looks like this text is about the section slightly above:
  [2-1, 2, 2+1] === [1,2,3]
  [1,2,3] === [1, 2, 3]
  [1, 2, 3] === [1, 2, 3]
reply


ajanuary 1 day ago | link

Aah, rereading it, it looks like it is. The ouroboros section is an aside about how confusing combining arrays and references can be.
reply


toki5 1 day ago | link

Just a guess -- perhaps
    ouroborous[0] = ouroboros;
creates a new reference to ouroboros and stores that in ouroboros[0], so comparing ouroboros and ouroboros[0] with === would claim they're the same type but not the same value.
Not an expert though, so I could be wrong, but that'd explain the behavior to me.
reply


roryokane 1 day ago | link

Yes, I don’t understand what he means either.
    ouroboros[0] === ouroboros
evaluates to `true`.
reply

Queue implementation memory leak?

I'm talking about the Queue implementation that is featured multiple times throughout the book.

var QueueMaker = function () {
    var queue = {
        array: [],
        head: 0,
        tail: -1,
        pushTail: function (value) {
            return queue.array[queue.tail += 1] = value
        },
        pullHead: function () {
            var value;
            if (queue.tail >= queue.head) {
                value = queue.array[queue.head];
                queue.array[queue.head] = void 0;
                queue.head += 1;
                return value
            }
        },
        isEmpty: function () {
            return queue.tail < queue.head
        }
    };
    return queue
};

The idea behind pullHead seems to be, instead of constantly splicing the array, just move the head pointer forward and delete the old element, creating a sparse array. Unfortunately, that's not what this line: queue.array[queue.head] = void 0; is doing. It just creates a reference to undefined and adds it to array.

What you probably wanted was this:

delete queue.array[queue.head];

Tested in Chrome like this:

q = QueueMaker();
function times(n, fn) { for (var i = 0; i < n; i++) fn(); }
function push() { q.pushTail(Math.random()); }
function pull() { q.pullHead(); }
function stress() { times(100, push); times(100, pull); }
setInterval(stress, 1);

In one tab, pasted the code above. In other, fixed with delete instead of assignment.

After ~ 15-20 minutes:

The first tab is the unpatched code.

Many chapters missing on Leanpub

The following chapters and sections of the book are not on Leanpub:

  • Most of "References and Rebinding", including recipes (except for one section on var)
  • All of "Objects, Mutation, and State" (e.g. Issue #7), including recipes
  • The recipes from "Instances and Classes"

Include "poor man's PDF" in the README

git clone https://github.com/raganwald/javascript-allonge.git
cd manuscript
grep -v "^\s*$" Book.txt | grep -e "^\s" | sed 's/^ */"/g' | sed 's/ *$/"/g' | xargs pandoc --from=markdown_str

named functions incorrect syntax?

in https://leanpub.com/javascript-allonge/read#leanpub-auto-limits

limits

Named function expressions have limits. Here’s one such limit: You can do simple recursion, but not mutual recursion. For example:

var even = function (num) even { return (num === 0) || odd( num - 1) };
var odd  = function (num) odd  { return (num  >  0) && even(num - 1) };

shouldn't those functions be

var even = function even (num) { return (num === 0) || odd( num - 1) };
var odd  = function odd (num) { return (num  >  0) && even(num - 1) };

Typo: bar -> blitz

In the "loose use" section, the line:

"Since bar is scoped to the function foo

should be:

"Since blitz is scoped to the function foo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.