Генератор для перебора бесконечных ветвящихся неповторяющихся последовательностей (неслучайных чисел с шагом 1).

module.exports = (function(){

    var self = {}

    self.constructor = function()
    {
        if(!(this instanceof self.constructor))
        {
            return new (Function.prototype.bind.apply(self.constructor, [null].concat(Array.prototype.slice.call(arguments))))
        }
        this.pointer = -1
        this.sequence = []
        this.exhausted = false
        this.roundcount = 0
    }

    self.debug = function()
    {
        console.log(JSON.stringify([this.exhausted,this.sequence,this.pointer,this.roundcount]))
    }

    self.currentRound = function()
    {
        return this.roundcount
    }

    self.currentValue = function()
    {
        return this.sequence[this.pointer]
    }

    self.nextValue = function(min,max)
    {
        this.pointer++
        if(this.sequence[this.pointer] == null)
        {
            this.sequence[this.pointer] = { max : max, min : min, val : min }
        }
        return this.sequence[this.pointer].val
    }

    self.nextRound = function()
    {
        if(this.sequence[this.pointer] != null 
        && ++this.sequence[this.pointer].val > this.sequence[this.pointer].max)
        {
            this.sequence.splice(this.pointer,1)
            this.pointer--
            if(this.pointer == -1)
            {
                this.exhausted = true
            }
            else
            {
                this.nextRound()
            }
        }
        this.pointer = -1
        this.roundcount++
        return
    }

    self.constructor.prototype = self
    return self.constructor

})()
NotRand = require('./NotRand.js')

var i = 0;
var a = NotRand()
while(!a.exhausted)
{
    var b = []
    b.push(a.nextValue(1,1))
    b.push(a.nextValue(1,4))
    if(b[1] == 3)
    {
        b.push(a.nextValue(1,3))
        b.push(a.nextValue(1,3))
    }
    else
    {
        b.push(a.nextValue(1,2))
    }
    a.nextRound()
    console.log(b)
}
console.log(a.currentRound())
$ node pereborjs.js 
[ 1, 1, 1 ]
[ 1, 1, 2 ]
[ 1, 2, 1 ]
[ 1, 2, 2 ]
[ 1, 3, 1, 1 ]
[ 1, 3, 1, 2 ]
[ 1, 3, 1, 3 ]
[ 1, 3, 2, 1 ]
[ 1, 3, 2, 2 ]
[ 1, 3, 2, 3 ]
[ 1, 3, 3, 1 ]
[ 1, 3, 3, 2 ]
[ 1, 3, 3, 3 ]
[ 1, 4, 1 ]
[ 1, 4, 2 ]
23
module.exports = (function(){

    var prototype = {}
    var instances_counter = 0

    prototype.constructor = function()
    {
        if(!(this instanceof prototype.constructor))
        {
            return new (Function.prototype.bind.apply(prototype.constructor, [null].concat(Array.prototype.slice.call(arguments))))
        }
        this.id = ++instances_counter
    }

    prototype.render = function()
    {
        console.log(this.id)
    }

    prototype.constructor.prototype = prototype
    return prototype.constructor

})()

http://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript
http://stackoverflow.com/questions/3914557/passing-arguments-forward-to-another-javascript-function

[ ]
 

str = ".htaccess"
str.replace(/^\./, '').split('.').slice(-2)[1] || ''

[ ]
 

Наиболее перспективен, на мой взгляд, JSONSelect поскольку всё остальное мало понятная неудобная хрень. Но json:select() ешё не доделан до конца, там не так много фич, поэтому мы будем страдать.

json:select() http://jsonselect.org/#tryit

 ".author .drinkPref :first-child"

{
  "author": {
    "name": {
      "first": "Lloyd",
      "last": "Hilaiel"
    },
    "drinkPref": [
      "whiskey",
      "beer",
      "wine"
    ],
  },
  "thing": "JSONSelect site",
  "license": "(cc) BY-SA"
}

Result: "whiskey"

JSONSelect = require("JSONSelect")
JSONSelect.forEach(".points_to_delete .id",args,function(){
    result.push(arguments)
})

jsel https://github.com/dragonworx/jsel

dom.select('count(//*)') === 5;
dom.select('@title') === 'abc';
dom.select('//children/*[1]/@foo') === 'bar';
dom.select('count(//@foo)') === 2;
dom.select('//@foo[2]') === 555;
dom.select('count(//children//*)') === 2;
dom.select('//children/*[2]') === 'val';
dom.select('name(//children/*[2])') === 'string';
dom.select('name(*/*[2])') === 'subData';
dom.select('*/children/*[2]/text()') === 'val';
dom.selectAll('//@foo') === ['bar', 555];

JSPath https://github.com/dfilatov/jspath

 Quick example

JSPath.apply(
    '.automobiles{.maker === "Honda" && .year > 2009}.model',
    {
        "automobiles" : [
            { "maker" : "Nissan", "model" : "Teana", "year" : 2011 },
            { "maker" : "Honda", "model" : "Jazz", "year" : 2010 },
            { "maker" : "Honda", "model" : "Civic", "year" : 2007 },
            { "maker" : "Toyota", "model" : "Yaris", "year" : 2008 },
            { "maker" : "Honda", "model" : "Accord", "year" : 2011 }
        ],
        "motorcycles" : [{ "maker" : "Honda", "model" : "ST1300", "year" : 2012 }]
    });

Result will be:

['Jazz', 'Accord']

JsonPath http://goessner.net/articles/JsonPath/

$['store']['book'][0]['title']
$.store.book[*].author
$..author
$.store.*
$.store..price
$..book[2]
$..book[(@.length-1)]
$..book[-1:]
$..book[0,1]
$..book[:2]
$..book[?(@.isbn)]
$..book[?(@.price<10)]
$..* 

jLinq http://hugoware.net/Projects/jLinq

//select records
jlinq.from(data.source)
  .starts('first', 'a')
  .select();
 
//complex queries - no need to repeat names
//when querying the same field
jlinq.from(data.source)
    .starts('first', 'a')
    .or('b')
    .or('c')
    .sort('last')
    .select();
 
//sorting - multiple field
jlinq.from(data.source)
  .greater('age', 40)
  .sort('age', 'name');
  .select();
[ ]
 

http://espadrine.github.io/New-In-A-Spec/es6/

EcmaScript Sixth Edition

let, const (define block-local vars), function in block scope

destructuring: let {x, y} = pt; let [s, v, o] = triple(); (assuming let pt = {x:2, y:-5}, for instance).

parameter default values: function f(x, y=1, z=0) {⋯}

rest: function g(i, j, ...r) { return r.slice(i, j); } (instead of using arguments like a madman).

spread: let a = [0,1,2,3], o = new Something(...a);

proxies: let obj = Proxy.create(handler, proto). Long story short: ~ operator overloading with object-like elements.

weak map: let map = new WeakMap. Use it if you have circular references in it.

generators: function* gen() { yield 1; yield 2; } Actually, gen() returns ~ an object with a next() function property.

iterators: for (var [key, val] of items(x)) { alert(key + ',' + val); }. Iterators can be generators or proxies.

array and generator comprehension: [a+b for (a in A) for (b in B)] (array comprehension), (x for (x of generateValues()) if (x.color === 'blue')) (generator expression).

binary data: const Pixel = new StructType({x:uint32, y:uint32, color:Color}) (if Color is itself a StructType), new ArrayType(Pixel, 3).

class syntax, with extends, prototype, and super:

class Point extends Base {
constructor(x,y) {
super();
this[px] = x, this[py] = y;
this.r = function() { return Math.sqrt(x*x + y*y); }
}
get x() { return this[px]; }
get y() { return this[py]; }
proto_r() { return Math.sqrt(this[px] * this[px] +
this[py] * this[py]); }
equals(p) { return this[px] === p[px] &&
this[py] === p[py]; }
}

modules:

module math {
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
}

import {sum, pi} from math;
alert(sum(pi,pi));

quasis: multiline, substitution-ready strings with extensibility. `You are ${age} years old.`.

// The following regexp spans multiple lines.
re`line1: (words )*
line2: \w+`

// It desugars to:
re({raw:'line1: (words )*\nline2: \w+',
cooked:'line1: (words )*\nline2: \w+'})

[ ]
 

Запишу сюда, вдруг понадобится. Один раз уже пригодилось. Работающий пример javascript прокси.

function handlerMaker(obj) 
{
    return {

        getOwnPropertyDescriptor: function(name) 
        {
          console.log("getOwnPropertyDescriptor",name)
          var desc = Object.getOwnPropertyDescriptor(obj, name);
          // a trapping proxy's properties must always be configurable
          if (desc !== undefined) { desc.configurable = true; }
          return desc;
        },

        getPropertyDescriptor:  function(name) 
        {
            console.log("getPropertyDescriptor",name)
            var desc = Object.getPropertyDescriptor(obj, name); // not in ES5
            // a trapping proxy's properties must always be configurable
            if (desc !== undefined) { desc.configurable = true; }
            return desc;
        },

        getOwnPropertyNames: function()
        {
            console.log("getOwnPropertyNames")
            return Object.getOwnPropertyNames(obj);
        },

        getPropertyNames: function()
        {
            console.log("getPropertyNames")
            return Object.getPropertyNames(obj);                // not in ES5
        },

        defineProperty: function(name, desc) 
        {
            console.log("defineProperty", name, desc)
            Object.defineProperty(obj, name, desc);
        },

        delete: function(name) 
        {
            console.log("delete", name)
            return delete obj[name];
        },   

        fix: function() 
        {
            console.log("fix")
            if (Object.isFrozen(obj)) 
            {
                var result = {};
                Object.getOwnPropertyNames(obj).forEach(function(name) 
                {
                    result[name] = Object.getOwnPropertyDescriptor(obj, name);
                });
                return result;
            }
            // As long as obj is not frozen, the proxy won't allow itself to be fixed
            return undefined; // will cause a TypeError to be thrown
        },

        has: function(name) 
        { 
            console.log("has",name)
            return name in obj;
        },

        hasOwn: function(name) 
        { 
            console.log("hasOwn",name)
            return ({}).hasOwnProperty.call(obj, name); 
        },

        get: function(receiver, name) 
        { 
            console.log("get", receiver, name)
            return obj[name]; 
        },

        set: function(receiver, name, val) 
        { 
            console.log("set", receiver, name, val)
            obj[name] = val; 
            return true; 
        }, // bad behavior when set fails in non-strict mode

        enumerate: function() 
        {
            console.log("enumerate")
            var result = [];
            for (var name in obj) { result.push(name); };
            return result;
        },

        keys: function() 
        { 
            console.log("enumerate")
            return Object.keys(obj); 
        }

    }
}

var proxy = Proxy.create(handlerMaker({key:"asdf"}));

return proxy
[ ]
 

Delegating yield

The yield* operator delegates to another generator. This provides a convenient mechanism for composing generators.

The expression yield* <> is equivalent to:

let (g = <>) {
    let received = void 0, send = true, result = void 0;
    try {
        while (true) {
            let next = send ? g.send(received) : g.throw(received);
            try {
                received = yield next;
                send = true;
            } catch (e) {
                received = e;
                send = false;
            }
        }
    } catch (e) {
        if (!isStopIteration(e))
            throw e;
        result = e.value;
    } finally {
        try { g.close(); } catch (ignored) { }
    }
    result
}

This is similar to a for-in loop over the generator, except that it propagates exceptions thrown via the outer generator’s throw method into the delegated generator.

http://wiki.ecmascript.org/doku.php?id=harmony:generators

Delegating to another generator means the current generator stops producing values by itself, instead yielding the values produced by another generator until it exhausts it. It then resumes producing its own values, if any.

For instance, if secondGenerator() produces numbers from 10 to 15, and firstGenerator() produces numbers from 1 to 5 but delegates to secondGenerator() after producing 2, then the values produced by firstGenerator() will be:

1, 2, 10, 11, 12, 13, 14, 15, 3, 4, 5

http://stackoverflow.com/questions/17491779/delegated-yield-in-generator-functions

[ ]
 
var sqlite3 = require('sqlite3')

var sqlite3_Database_handler = (function(){ 

    var prototype = {}

    prototype.constructor = function(target)
    {
        this.target = target
    }

    prototype.get = function(receiver, name)
    {
        if(name == "all")
        {
            var target = this.target
            return function(query)
            {
                var deferred = require('q').defer()
                target.all(
                    query,
                    function(error,rows)
                    {
                        deferred.resolve({error:error,rows:rows})
                    }
                )
                return deferred.promise
            }
        }
        return this.target[name]; 
    }

    return prototype.constructor.prototype = prototype

})().constructor

var sqlite3_handler = (function(){ 

    var prototype = {}

    prototype.constructor = function(target)
    {
        this.target = target
    }

    prototype.get = function(receiver, name)
    {
        if(name == "Database")
        {
            var Database = this.target.Database
            return function()
            {
                return Proxy.create(
                    new sqlite3_Database_handler(
                        new (Database.bind.apply(
                            Database,
                            arguments
                        ))
                    )
                )
            }
        }
        return this.target[name]; 
    }

    return prototype.constructor.prototype = prototype

})().constructor

module.exports = Proxy.create(new sqlite3_handler(sqlite3))
var sqlite3 = require('sqlite3')

module.exports = Proxy.create(new((function(){ 

    var prototype = {}

    prototype.constructor = function(target)
    {
        this.target = target
    }

    prototype.get = function(receiver, name)
    {
        console.log("GET " + name)
        return this.target[name]; 
    }

    return prototype.constructor.prototype = prototype

})().constructor)(sqlite3))

Проблема заключалась в том, что если не возвращать true, Array.every прекращает свою работу.

[ ]