<commit_before>var Position = require('./position.js');

/* import pieces */
var Rook = require('./pieces/rook.js');
var Pawn = require('./pieces/pawn.js');
var Knight = require('./pieces/knight.js');
var Bishop = require('./pieces/bishop.js');
var Queen = require('./pieces/queen.js');
var King = require('./pieces/king.js');

var Board = function() {
    this.squares = {
        'a': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'b': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'c': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'd': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'e': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'f': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'g': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'h': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''}
    }
    this.status = '';
    this.check = '';
    this.kingPosition = {black: null, white: null};
    this.moveCount = 0;
}
Board.prototype.getStatus = function() {
    return this.status;
}
Board.prototype.getKingPosition = function(set) {
    if(set !== 'white' && set !== 'black') {
        return null;
    } else {
        return this.kingPosition[set];
    }
}
Board.prototype.toString = function() {
    var s = "\n";

    s += '   ___a___|___b___|___c___|___d___|___e___|___f___|___g___|___h___   \n';

    for(var keyRow in this.squares['a']) {
        s += keyRow + ' |'
        for(var keyCol in this.squares) {
            var oppositeRow = 9 - keyRow;
            var piece = this.getPieceAt(new Position(keyCol, oppositeRow));

            if(piece === '') {
                s += '_______|';
            } else {
                s += (piece.set === "white") ? '+' : '*';
                s += normalizeName(piece.name) + '|'
            }
        }
        s += ' ' + keyRow + '\n';
    }

    s += '   ___a___|___b___|___c___|___d___|___e___|___f___|___g___|___h___   \n';
    s += '\n';
    s += '   + = white piece   \n';
    s += '   * = black piece   \n';

    return s;
}

function normalizeName(name) {
    if(name.length <= 4) {
        return ' ' + name + ' ';
    } else if (name.length === 5) {
        return name + ' ';
    } else if (name.length >= 6) {
        return name;
    }
}

Board.prototype.setup = function() {
    //set up white pieces
    this.squares['a']['1'] = new Rook('white');
    this.squares['b']['1'] = new Knight('white');
    this.squares['c']['1'] = new Bishop('white');
    this.squares['d']['1'] = new Queen('white');
    this.squares['e']['1'] = new King('white');
    this.squares['f']['1'] = new Bishop('white');
    this.squares['g']['1'] = new Knight('white');
    this.squares['h']['1'] = new Rook('white');
    for(var column in this.squares) {
        this.squares[column]['2'] = new Pawn('white');
    }

    //set up black pieces
    this.squares['a']['8'] = new Rook('black');
    this.squares['b']['8'] = new Knight('black');
    this.squares['c']['8'] = new Bishop('black');
    this.squares['d']['8'] = new Queen('black');
    this.squares['e']['8'] = new King('black');
    this.squares['f']['8'] = new Bishop('black');
    this.squares['g']['8'] = new Knight('black');
    this.squares['h']['8'] = new Rook('black');
    for(var column in this.squares) {
        this.squares[column]['7'] = new Pawn('black');
    }

    this.status = 'setup';

    this.kingPosition = {
        black: new Position('e',8),
        white: new Position('e',1)
    }
}
Board.prototype.getPieceAt = function(position) {
    var coords = position.getCoordinates();
    var piece = this.squares[coords.column][coords.row];
    return piece || '';
}

Board.prototype.movePiece = function(origin, destination) {

    var oPiece = this.getPieceAt(origin);

    if(oPiece === '') {
        return { success: false, message: 'There was no piece in this position'};
    } else {
        var result = oPiece.canMoveTo(origin, destination, this);
        result.isCapture = false;
        if(result.success) {
            //we move the piece
            var dPiece = this.getPieceAt(destination);

            if(oPiece.name === 'king') {
                // we move the king and check if it's in check after moving
                this.squares[destination.getColumn()][destination.getRow()] = oPiece;
                this.squares[origin.getColumn()][origin.getRow()] = '';
                // Update King's position
                this.kingPosition[oPiece.set] = destination;

                var isCheck = this.isCheck(oPiece.set);

                if(isCheck.result) {    //if it's check we'll move back the piece to its original position
                    result.success = false;
                    result.message = "Invalid movement: the " + oPiece.set + " king would be in check";
                    this.squares[destination.getColumn()][destination.getRow()] = dPiece;
                    this.squares[origin.getColumn()][origin.getRow()] = oPiece;
                    // put king on the original position
                    this.kingPosition[oPiece.set] = origin;

                } else {
                    result.isCapture = dPiece !== '';   //the piece in origin has captured the piece in the destination
                    this.moveCount++;
                    if(this.moveCount >= 2) this.status = 'playing';
                }

            } else {
                result.isCapture = dPiece !== '';   //the piece in origin has captured the piece in the destination
                this.squares[destination.getColumn()][destination.getRow()] = oPiece;
                this.squares[origin.getColumn()][origin.getRow()] = '';

                var nowIsCheck = this.isCheck(oPiece.set);
                if(nowIsCheck.result) {
                    //we have moved and we're in check. The movement is invalid
                    result.success = false;
                    result.message = "Invalid movement: the " + oPiece.set + " king would be in check";
                    this.squares[destination.getColumn()][destination.getRow()] = dPiece;
                    this.squares[origin.getColumn()][origin.getRow()] = oPiece;
                } else {
                    var complementarySet = (oPiece.set === 'white') ? 'black' : 'white';
                    var nextIsCheck = this.isCheck(complementarySet);

                    if(nextIsCheck.result) {
                        this.check = complementarySet;
                        this.status = complementarySet + ' check'
                    }

                    this.moveCount++;
                    if(this.moveCount >= 2) this.status = 'playing';
                }
            }

            return result;

        } else {
            return result;
        }
    }
}
Board.prototype.isCheck = function(set) {
    if (set !== 'white' || set !== 'black') {
        var kingPosition = this.getKingPosition(set);

        var output = {
            result: false,
            message: 'The ' + set + ' king is not in check'
        }

        var queenThreat = this.isQueenThreat(kingPosition,set);
        if(queenThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to queen on ' + queenThreat.position;
        }
        var knightThreat = this.isKnightThreat(kingPosition,set);
        if(knightThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to knight on ' + knightThreat.position;
        }
        var rookThreat = this.isRookThreat(kingPosition,set);
        if(rookThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to rook on ' + rookThreat.position;
        }
        var bishopThreat = this.isBishopThreat(kingPosition,set);
        if(bishopThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to bishop on ' + bishopThreat.position;
        }
        var pawnThreat = this.isPawnThreat(kingPosition,set);
        if(pawnThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to pawn on ' + pawnThreat.position;
        }
        var kingThreat = this.isKingThreat(kingPosition,set);
        if(kingThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to king on ' + kingThreat.position;
        }

        return output;
    }
}

Board.prototype.isPawnThreat = function(kingPosition, kingSet) {
    var oppositeSet = (kingSet === 'white') ? 'black' : 'white';
    var vector = (kingSet === 'white') ? 1 : -1;
    var destinations = [
        {col: kingPosition.getIntColumn() + 1, row: kingPosition.getRow() + vector},
        {col: kingPosition.getIntColumn() - 1, row: kingPosition.getRow() + vector}
    ];

    for(var i = 0; i < 2; i++) {
        var pawnPosition = new Position(destinations[i].col, destinations[i].row);
        var piece = this.getPieceAt(pawnPosition);
        if(piece !== '' && piece.name === 'pawn' && piece.set === oppositeSet) {
            return {isThreat: true, position: pawnPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isRookThreat = function(kingPosition, kingSet) {
    var tempRook = new Rook(kingSet);
    var destinations = tempRook.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var rookPosition = new Position(col, row);
        var piece = this.getPieceAt(rookPosition);
        if(piece !== '' && piece.name === 'rook') {
            return {isThreat: true, position: rookPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isKnightThreat = function(kingPosition, kingSet) {
    var tempKnight = new Knight(kingSet);
    var destinations = tempKnight.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        knightPosition = new Position(col, row);
        var piece = this.getPieceAt(knightPosition);
        if(piece !== '' && piece.name === 'knight') {
            return {isThreat: true, position: knightPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isBishopThreat = function(kingPosition, kingSet) {
    var tempBishop = new Bishop(kingSet);
    var destinations = tempBishop.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var bishopPosition = new Position(col, row);
        var piece = this.getPieceAt(bishopPosition);
        if(piece !== '' && piece.name === 'bishop') {
            return {isThreat: true, position: bishopPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isQueenThreat = function(kingPosition, kingSet) {
    var tempQueen = new Queen(kingSet);
    var destinations = tempQueen.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var queenPosition = new Position(col, row)
        var piece = this.getPieceAt(queenPosition);
        if(piece !== '' && piece.name === 'queen') {
            return {isThreat: true, position: queenPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}
Board.prototype.isKingThreat = function(kingPosition, kingSet) {
    var tempKing = new King(kingSet);
    var destinations = tempKing.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var kingPosition = new Position(col, row)
        var piece = this.getPieceAt(kingPosition);
        if(piece !== '' && piece.name === 'king') {
            return {isThreat: true, position: kingPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

//test cases for testing check
Board.prototype.setupCheck = function(testCase) {
    for(var keyCol in this.squares) {
        for(var keyRow in this.squares[keyCol]) {
            this.squares[keyCol][keyRow] = '';
        }
    }

    switch(testCase) {
        case 1:
            this.squares['d'][6] = new King('black');
            this.squares['f'][6] = new Bishop('black');
            this.squares['h'][5] = new Knight('black');
            this.squares['g'][3] = new Bishop('white');
            this.squares['f'][3] = new King('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 2:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['d'][1] = new Rook('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 3:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['c'][6] = new Bishop('black');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 4:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['c'][6] = new Queen('black');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 5:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['c'][4] = new Knight('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 6:
            this.squares['d'][6] = new King('black');
            this.squares['d'][5] = new King('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('d',5)
            }
            break;
    }
}

Board.prototype.isCheckMate = function() {
    //to develop
}

exports = module.exports = Board;<commit_msg>v1.0.7 - modified algorithm to move pieces<commit_after>var Position = require('./position.js');

/* import pieces */
var Rook = require('./pieces/rook.js');
var Pawn = require('./pieces/pawn.js');
var Knight = require('./pieces/knight.js');
var Bishop = require('./pieces/bishop.js');
var Queen = require('./pieces/queen.js');
var King = require('./pieces/king.js');

var Board = function() {
    this.squares = {
        'a': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'b': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'c': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'd': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'e': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'f': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'g': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''},
        'h': {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': ''}
    }
    this.status = '';
    this.check = '';
    this.kingPosition = {black: null, white: null};
    this.moveCount = 0;
}
Board.prototype.getStatus = function() {
    return this.status;
}
Board.prototype.getKingPosition = function(set) {
    if(set !== 'white' && set !== 'black') {
        return null;
    } else {
        return this.kingPosition[set];
    }
}
Board.prototype.toString = function() {
    var s = "\n";

    s += '   ___a___|___b___|___c___|___d___|___e___|___f___|___g___|___h___   \n';

    for(var keyRow in this.squares['a']) {
        s += (9 - keyRow) + ' |'
        for(var keyCol in this.squares) {
            var oppositeRow = 9 - keyRow;
            var piece = this.getPieceAt(new Position(keyCol, oppositeRow));

            if(piece === '') {
                s += '_______|';
            } else {
                s += (piece.set === "white") ? '+' : '*';
                s += normalizeName(piece.name) + '|'
            }
        }
        s += ' ' + (9 - keyRow) + '\n';
    }

    s += '   ___a___|___b___|___c___|___d___|___e___|___f___|___g___|___h___   \n';
    s += '\n';
    s += '   + = white piece   \n';
    s += '   * = black piece   \n';

    return s;
}

function normalizeName(name) {
    if(name.length <= 4) {
        return ' ' + name + ' ';
    } else if (name.length === 5) {
        return name + ' ';
    } else if (name.length >= 6) {
        return name;
    }
}

Board.prototype.setup = function() {
    //set up white pieces
    this.squares['a']['1'] = new Rook('white');
    this.squares['b']['1'] = new Knight('white');
    this.squares['c']['1'] = new Bishop('white');
    this.squares['d']['1'] = new Queen('white');
    this.squares['e']['1'] = new King('white');
    this.squares['f']['1'] = new Bishop('white');
    this.squares['g']['1'] = new Knight('white');
    this.squares['h']['1'] = new Rook('white');
    for(var column in this.squares) {
        this.squares[column]['2'] = new Pawn('white');
    }

    //set up black pieces
    this.squares['a']['8'] = new Rook('black');
    this.squares['b']['8'] = new Knight('black');
    this.squares['c']['8'] = new Bishop('black');
    this.squares['d']['8'] = new Queen('black');
    this.squares['e']['8'] = new King('black');
    this.squares['f']['8'] = new Bishop('black');
    this.squares['g']['8'] = new Knight('black');
    this.squares['h']['8'] = new Rook('black');
    for(var column in this.squares) {
        this.squares[column]['7'] = new Pawn('black');
    }

    this.status = 'setup';

    this.kingPosition = {
        black: new Position('e',8),
        white: new Position('e',1)
    }
}
Board.prototype.getPieceAt = function(position) {
    var coords = position.getCoordinates();
    var piece = this.squares[coords.column][coords.row];
    return piece || '';
}

Board.prototype.movePiece = function(origin, destination) {

    var oPiece = this.getPieceAt(origin);

    if(oPiece === '') {
        return { success: false, message: 'There was no piece in this position'};
    } else {
        var result = oPiece.canMoveTo(origin, destination, this);
        result.isCapture = false;
        if(result.success) {
            //we move the piece
            var dPiece = this.getPieceAt(destination);

            if(oPiece.name === 'king') {
                // we move the king and check if it's in check after moving
                this.squares[destination.getColumn()][destination.getRow()] = oPiece;
                this.squares[origin.getColumn()][origin.getRow()] = '';
                // Update King's position
                this.kingPosition[oPiece.set] = destination;

                var isCheck = this.isCheck(oPiece.set);

                if(isCheck.result) {    //if it's check we'll move back the piece to its original position
                    result.success = false;
                    result.message = "Invalid movement: the " + oPiece.set + " king would be in check";
                    this.squares[destination.getColumn()][destination.getRow()] = dPiece;
                    this.squares[origin.getColumn()][origin.getRow()] = oPiece;
                    // put king on the original position
                    this.kingPosition[oPiece.set] = origin;

                } else {
                    result.isCapture = dPiece !== '';   //the piece in origin has captured the piece in the destination

                    var complementarySet = (oPiece.set === 'white') ? 'black' : 'white';
                    var nextIsCheck = this.isCheck(complementarySet);

                    if(nextIsCheck.result) {
                        this.check = complementarySet;
                        this.status = complementarySet + ' check'
                    }

                    this.moveCount++;
                    if(this.moveCount === 1) this.status = 'started';
                    if(this.moveCount >= 2) this.status = 'playing';
                }

            } else {
                result.isCapture = dPiece !== '';   //the piece in origin has captured the piece in the destination
                this.squares[destination.getColumn()][destination.getRow()] = oPiece;
                this.squares[origin.getColumn()][origin.getRow()] = '';

                var nowIsCheck = this.isCheck(oPiece.set);
                if(nowIsCheck.result) {
                    //we have moved and we're in check. The movement is invalid
                    result.success = false;
                    result.message = "Invalid movement: the " + oPiece.set + " king would be in check";
                    this.squares[destination.getColumn()][destination.getRow()] = dPiece;
                    this.squares[origin.getColumn()][origin.getRow()] = oPiece;
                    result.isCapture = false;
                } else {
                    var complementarySet = (oPiece.set === 'white') ? 'black' : 'white';
                    var nextIsCheck = this.isCheck(complementarySet);

                    if(nextIsCheck.result) {
                        this.check = complementarySet;
                        this.status = complementarySet + ' check'
                    }

                    this.moveCount++;
                    if(this.moveCount === 1) this.status = 'started';
                    if(this.moveCount >= 2) this.status = 'playing';
                }
            }

            return result;

        } else {
            return result;
        }
    }
}
Board.prototype.isCheck = function(set) {
    if (set !== 'white' || set !== 'black') {
        var kingPosition = this.getKingPosition(set);

        var output = {
            result: false,
            message: 'The ' + set + ' king is not in check'
        }

        var queenThreat = this.isQueenThreat(kingPosition,set);
        if(queenThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to queen on ' + queenThreat.position;
        }
        var knightThreat = this.isKnightThreat(kingPosition,set);
        if(knightThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to knight on ' + knightThreat.position;
        }
        var rookThreat = this.isRookThreat(kingPosition,set);
        if(rookThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to rook on ' + rookThreat.position;
        }
        var bishopThreat = this.isBishopThreat(kingPosition,set);
        if(bishopThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to bishop on ' + bishopThreat.position;
        }
        var pawnThreat = this.isPawnThreat(kingPosition,set);
        if(pawnThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to pawn on ' + pawnThreat.position;
        }
        var kingThreat = this.isKingThreat(kingPosition,set);
        if(kingThreat.isThreat) {
            output.result = true;
            output.message = 'The ' + set + ' king is in check due to king on ' + kingThreat.position;
        }

        return output;
    }
}

Board.prototype.isPawnThreat = function(kingPosition, kingSet) {
    var oppositeSet = (kingSet === 'white') ? 'black' : 'white';
    var vector = (kingSet === 'white') ? 1 : -1;
    var destinations = [
        {col: kingPosition.getIntColumn() + 1, row: kingPosition.getRow() + vector},
        {col: kingPosition.getIntColumn() - 1, row: kingPosition.getRow() + vector}
    ];

    for(var i = 0; i < 2; i++) {
        var pawnPosition = new Position(destinations[i].col, destinations[i].row);
        var piece = this.getPieceAt(pawnPosition);
        if(piece !== '' && piece.name === 'pawn' && piece.set === oppositeSet) {
            return {isThreat: true, position: pawnPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isRookThreat = function(kingPosition, kingSet) {
    var tempRook = new Rook(kingSet);
    var destinations = tempRook.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var rookPosition = new Position(col, row);
        var piece = this.getPieceAt(rookPosition);
        if(piece !== '' && piece.name === 'rook') {
            return {isThreat: true, position: rookPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isKnightThreat = function(kingPosition, kingSet) {
    var tempKnight = new Knight(kingSet);
    var destinations = tempKnight.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        knightPosition = new Position(col, row);
        var piece = this.getPieceAt(knightPosition);
        if(piece !== '' && piece.name === 'knight') {
            return {isThreat: true, position: knightPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isBishopThreat = function(kingPosition, kingSet) {
    var tempBishop = new Bishop(kingSet);
    var destinations = tempBishop.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var bishopPosition = new Position(col, row);
        var piece = this.getPieceAt(bishopPosition);
        if(piece !== '' && piece.name === 'bishop') {
            return {isThreat: true, position: bishopPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

Board.prototype.isQueenThreat = function(kingPosition, kingSet) {
    var tempQueen = new Queen(kingSet);
    var destinations = tempQueen.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var queenPosition = new Position(col, row)
        var piece = this.getPieceAt(queenPosition);
        if(piece !== '' && piece.name === 'queen') {
            return {isThreat: true, position: queenPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}
Board.prototype.isKingThreat = function(kingPosition, kingSet) {
    var tempKing = new King(kingSet);
    var destinations = tempKing.getDestinations(kingPosition, this);
    for(var dest in destinations) {
        var col = dest[0];
        var row = dest[1];
        var kingPosition = new Position(col, row)
        var piece = this.getPieceAt(kingPosition);
        if(piece !== '' && piece.name === 'king') {
            return {isThreat: true, position: kingPosition.toString()};
        }
    }
    return {isThreat: false, position: ''};
}

//test cases for testing check
Board.prototype.setupCheck = function(testCase) {
    for(var keyCol in this.squares) {
        for(var keyRow in this.squares[keyCol]) {
            this.squares[keyCol][keyRow] = '';
        }
    }

    switch(testCase) {
        case 1:
            this.squares['d'][6] = new King('black');
            this.squares['f'][6] = new Bishop('black');
            this.squares['h'][5] = new Knight('black');
            this.squares['g'][3] = new Bishop('white');
            this.squares['f'][3] = new King('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 2:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['d'][1] = new Rook('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 3:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['c'][6] = new Bishop('black');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 4:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['c'][6] = new Queen('black');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 5:
            this.squares['d'][6] = new King('black');
            this.squares['f'][3] = new King('white');
            this.squares['c'][4] = new Knight('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('f',3)
            }
            break;
        case 6:
            this.squares['d'][6] = new King('black');
            this.squares['d'][5] = new King('white');
            this.kingPosition = {
                black: new Position('d',6),
                white: new Position('d',5)
            }
            break;
    }
}

Board.prototype.isCheckMate = function() {
    //to develop
}

exports = module.exports = Board;<|endoftext|>


<commit_before>export const THRESHOLD_MUL_TOOM22 = 10 ;
<commit_msg>:rocket: perf: Change TOOM22 threshold to 16.<commit_after>export const THRESHOLD_MUL_TOOM22 = 16 ;
<|endoftext|>


<commit_before>var assert = require('assert'),
	TaskManager = require(__dirname+'/../');

var testOKResult = [
	['hello world!'],
	['users subscribed', [ 1 ]],
	['completed', 'task'],
	['users subscribed', [ 1, 2 ]],
	['global completed', 'Task Example']
];

var testOKResultGlobals = [
	['global completed', '1'],
	['global completed', '2']
];

describe("Generic main tests", function() {

	it("Global events", function(){

		TaskManager().on('done', function(){

			this.a++;

			assert.strictEqual(3, this.a);

		});

		TaskManager(1).addTask(function(){

			this.done();

		}).settings(function(){

			this.a = 1;

		}).on('done', function(){

			this.a++;

		}).start();

	});

	it("Set Settings as Object", function(){

		TaskManager(2).addTask(function(){

			this.__settings.a++;

			this.done();

		}).settings({a: 2}).on('done', function(){

			assert.strictEqual(3, this.get('a'));

		}).start();

	});

	it("Collection output correct values and sorting", function() {

		var userId = 1; // user id, will be subscribed at the start

		var output = [];

		TaskManager().on('done', function(){

			output.push(['global completed', this.name]);

			assert.strictEqual(testOKResult, output);

		});

		// Get TaskManager Environment By UserID
		// And create task with some calculations
		TaskManager(userId).addTask(function(){

			var self = this; // save link to Task instance

			this.trigger('test', {hello: 'hello world!'}); // trigger test event

			// emulate long process work
			setTimeout(function(){

				self.done(); // call task done

			}, 3000);

			this.subscribe(2); // subscribe new user id before done

		}).settings(function(){

			this.some = 'task';

			this.name = 'Task Example';

		}).on('done', function(){

			output.push(['completed', this.some]); // completed task

			output.push(['users subscribed', this.getSubscribers()]); // get subscribers at end

			this.remove(); // set removed task's property and remove from stack

		}).on('test',function(context){

			output.push([context.hello]); // hello world!

			output.push(['users subscribed', this.getSubscribers()]); // get subscribers at any event

		}).start(); // Run task

	});

	it("Additions Global Events", function(){
		var userId = 1;
		var output = [];

		TaskManager(0).on('done', function(){

			output.push(['global completed', '1']);

		});

		TaskManager(userId).addTask(function(){
			var self = this;

			setTimeout(function(){
				self.done();
			}, 1000);

		}).on('done', function(){

			output.push(['completed', 'self']);

			console.log(output);

			assert.strictEqual(testOKResultGlobals, output);

		}).start();

		TaskManager(0).on('done', function(){
			output.push(['global completed', '2']);
		});

	});

});

<commit_msg>Add test Info TODO Async<commit_after>var assert = require('assert'),
	TaskManager = require(__dirname+'/../');

// Node Describe do not work here
// @todo Async Testing

var testOKResult = [
	['hello world!'],
	['users subscribed', [ 1 ]],
	['completed', 'task'],
	['users subscribed', [ 1, 2 ]],
	['global completed', 'Task Example']
];

var testOKResultGlobals = [
	['global completed', '1'],
	['completed', 'self'],
	['global completed', '2']
];

describe("Generic main tests", function() {

	it("Global events", function(){

		TaskManager().on('done', function(){

			this.a++;

			assert.strictEqual(3, this.a);

		});

		TaskManager(1).addTask(function(){

			this.done();

		}).settings(function(){

			this.a = 1;

		}).on('done', function(){

			this.a++;

		}).start();

	});

	it("Set Settings as Object", function(){

		TaskManager(2).addTask(function(){

			this.__settings.a++;

			this.done();

		}).settings({a: 2}).on('done', function(){

			assert.strictEqual(3, this.get('a'));

		}).start();

	});

	it("Collection output correct values and sorting", function() {

		var userId = 1; // user id, will be subscribed at the start

		var output = [];

		TaskManager().on('done', function(){

			output.push(['global completed', this.name]);

			assert.strictEqual(testOKResult, output);

		});

		// Get TaskManager Environment By UserID
		// And create task with some calculations
		TaskManager(userId).addTask(function(){

			var self = this; // save link to Task instance

			this.trigger('test', {hello: 'hello world!'}); // trigger test event

			// emulate long process work
			setTimeout(function(){

				self.done(); // call task done

			}, 3000);

			this.subscribe(2); // subscribe new user id before done

		}).settings(function(){

			this.some = 'task';

			this.name = 'Task Example';

		}).on('done', function(){

			output.push(['completed', this.some]); // completed task

			output.push(['users subscribed', this.getSubscribers()]); // get subscribers at end

			this.remove(); // set removed task's property and remove from stack

		}).on('test',function(context){

			output.push([context.hello]); // hello world!

			output.push(['users subscribed', this.getSubscribers()]); // get subscribers at any event

		}).start(); // Run task

	});

	it("Additions Global Events", function(){
		var userId = 1;
		var output = [];

		TaskManager(0).on('done', function(){
			output.push(['global completed', '1']);
		});

		TaskManager(userId).addTask(function(){
			var self = this;

			this.step(function(){
				self.done();
			});

		}).on('done', function(){

			output.push(['completed', 'self']);

			assert.deepEqual(testOKResultGlobals, output);

		}).start();

		TaskManager(0).on('done', function(){
			output.push(['global completed', '2']);
		});

	});

});

<|endoftext|>


<commit_before>'use strict';

var chalk = require('chalk');
var yeoman = require('yeoman-generator');
var genUtils = require('../util');

var BangularGenerator = yeoman.generators.NamedBase.extend({

  prompting: function () {
    var done = this.async();

    this.instanceName = this._.camelize(this.name);
    this.instancesName = this._.camelize(this.name) + 's';

    this.fileName = this._.dasherize(this.name.substr(0, 1).toLowerCase() + this.name.substr(1));
    this.routeName = this.fileName + 's';

    this.objectName = this.name.substr(0, 1).toUpperCase() + this._.camelize(this.name).substr(1);
    this.objectsName = this.objectName + 's';

    var prompts = [{
      type: 'input',
      name: 'url',
      message: 'On which url do you want to attach the ' + chalk.red(this.objectName) + ' endpoint? ',
      default: '/api/' + this.routeName
    }];

    var filters = this.config.get('filters');

    if (filters && filters.ngResource) {
      prompts.push({
        type: 'confirm',
        name: 'resource',
        message: 'Do you want to generate the associated $resource?',
        default: false
      });
    }

    if (filters && filters.sockets && filters.backend === 'mongo') {
      prompts.push({
        type: 'confirm',
        name: 'sockets',
        message: 'Do you want to generate sockets integration for this model?',
        default: true
      });
    }

    this.prompt(prompts, function (props) {
      this.url = props.url;
      this.sockets = props.sockets;
      this.resource = props.resource;
      done();
    }.bind(this));
  },

  writing: function () {

    var filters = this.config.get('filters');
    var filesByBackendType = {
      mongo: ['controller.js', 'model.js', 'spec.js'],
      json: ['controller.js', 'data.json'],
      restock: ['controller.js']
    };

    this.template('index.js', 'server/api/' + this.fileName + '/index.js');

    filesByBackendType[filters.backend].forEach(function (file) {
      this.template(filters.backend + '/' + file, 'server/api/' + this.fileName + '/' + this.fileName + '.' + file);
    }.bind(this));

    genUtils.rewriteFile({
      file: 'server/routes.js',
      needle: '// API',
      splicable: [
        'app.use(\'' + this.url + '\', require(\'./api/' + this.fileName + '\'));'
      ]
    });

    if (this.resource) {
      this.template('service.js', 'client/services/' + this.fileName + '/' + this.fileName + '.resource.js');
    }

    if (this.sockets) {
      this.template('mongo/socket.js', 'server/api/' + this.fileName + '/' + this.fileName + '.socket.js');

      genUtils.rewriteFile({
        file: 'server/config/sockets.js',
        needle: '// sockets insert',
        splicable: [
          'require(\'../api/' + this.fileName + '/' + this.fileName + '.socket.js\').register(socket);'
        ]
      });
    }
  }
});

module.exports = BangularGenerator;
<commit_msg>fix(api): `No` by default for socket file creation<commit_after>'use strict';

var chalk = require('chalk');
var yeoman = require('yeoman-generator');
var genUtils = require('../util');

var BangularGenerator = yeoman.generators.NamedBase.extend({

  prompting: function () {
    var done = this.async();

    this.instanceName = this._.camelize(this.name);
    this.instancesName = this._.camelize(this.name) + 's';

    this.fileName = this._.dasherize(this.name.substr(0, 1).toLowerCase() + this.name.substr(1));
    this.routeName = this.fileName + 's';

    this.objectName = this.name.substr(0, 1).toUpperCase() + this._.camelize(this.name).substr(1);
    this.objectsName = this.objectName + 's';

    var prompts = [{
      type: 'input',
      name: 'url',
      message: 'On which url do you want to attach the ' + chalk.red(this.objectName) + ' endpoint? ',
      default: '/api/' + this.routeName
    }];

    var filters = this.config.get('filters');

    if (filters && filters.ngResource) {
      prompts.push({
        type: 'confirm',
        name: 'resource',
        message: 'Do you want to generate the associated $resource?',
        default: false
      });
    }

    if (filters && filters.sockets && filters.backend === 'mongo') {
      prompts.push({
        type: 'confirm',
        name: 'sockets',
        message: 'Do you want to generate sockets integration for this model?',
        default: false
      });
    }

    this.prompt(prompts, function (props) {
      this.url = props.url;
      this.sockets = props.sockets;
      this.resource = props.resource;
      done();
    }.bind(this));
  },

  writing: function () {

    var filters = this.config.get('filters');
    var filesByBackendType = {
      mongo: ['controller.js', 'model.js', 'spec.js'],
      json: ['controller.js', 'data.json'],
      restock: ['controller.js']
    };

    this.template('index.js', 'server/api/' + this.fileName + '/index.js');

    filesByBackendType[filters.backend].forEach(function (file) {
      this.template(filters.backend + '/' + file, 'server/api/' + this.fileName + '/' + this.fileName + '.' + file);
    }.bind(this));

    genUtils.rewriteFile({
      file: 'server/routes.js',
      needle: '// API',
      splicable: [
        'app.use(\'' + this.url + '\', require(\'./api/' + this.fileName + '\'));'
      ]
    });

    if (this.resource) {
      this.template('service.js', 'client/services/' + this.fileName + '/' + this.fileName + '.resource.js');
    }

    if (this.sockets) {
      this.template('mongo/socket.js', 'server/api/' + this.fileName + '/' + this.fileName + '.socket.js');

      genUtils.rewriteFile({
        file: 'server/config/sockets.js',
        needle: '// sockets insert',
        splicable: [
          'require(\'../api/' + this.fileName + '/' + this.fileName + '.socket.js\').register(socket);'
        ]
      });
    }
  }
});

module.exports = BangularGenerator;
<|endoftext|>


<commit_before>"use strict";
var placesDetailRequest = require("./placesDetailRequest");
var infoWindowTemplate = require("./templates/infowindow-template.hbs");
var placelistTemplate = require("./templates/placelist-template.hbs");
var placelistHeader = require("./templates/placelist-header-template.hbs");
var $ = require ("jquery");
var ScrollTo = require("./vendor/jquery.scrollTo.min");
$.scrollTo = new ScrollTo();

module.exports = function Place (placeJSON, mapObject) {
  var that = this;
  this.marker = new google.maps.Marker({
    position: placeJSON.geometry.location,
    map: mapObject.map,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 3,
      strokeWeight: 1,
      fillOpacity: 1,
      fillColor: "red"
    }
  });
  this.element = placelistHeader(placeJSON);

  // add each place to the list display
  $(".list-display").append (this.element);

  this.detailRequest = function detailRequest (callback) {
    placesDetailRequest(placeJSON.reference, mapObject.map, callback);
  };

  // closes windows/placelist divs, makes detail request, calls other funcs
  function makeRequest(result) {
    $(".places_details").remove();
    if (mapObject.openInfoWindow!==null){
      mapObject.openInfoWindow.close();
    }
    that.detailRequest (function (result) {
      var website = result.website;
      if (website){
        result.short_website = shortenWebsite(website);
      }
      infoWindow(result);
      expandListPlace(result);
    });
  }

  // passes result into info template, opens info window
  function infoWindow(result) {
    that.infoWindow = new google.maps.InfoWindow({
      content: infoWindowTemplate(result)
    });
    mapObject.openInfoWindow = that.infoWindow;
    mapObject.openInfoWindow.open(mapObject.map, that.marker);
  }

  // passes result into placelist template, appends to DOM and scrolls to it
  function expandListPlace(result) {
    var place = $("#" + placeJSON.reference);
    place.after (placelistTemplate(result));
    $(".list-display").scrollTo(place, 1000);
  }

  // shorten (visible) url at first "/" after http://
  function shortenWebsite(website) {
    if (website.length > 30){
      var urlPieces = website.split("/");
      return urlPieces[2];
    }
    return website.substring(website.indexOf("//")+2, website.length-1);
  }

  // placelist listener
  $("#" + placeJSON.reference).click(makeRequest);
  // marker listener
  google.maps.event.addListener(this.marker, "click", makeRequest);
};
<commit_msg>fix infowindow placelist so clicking won't reload stuff that's already open<commit_after>"use strict";
var placesDetailRequest = require("./placesDetailRequest");
var infoWindowTemplate = require("./templates/infowindow-template.hbs");
var placelistTemplate = require("./templates/placelist-template.hbs");
var placelistHeader = require("./templates/placelist-header-template.hbs");
var $ = require ("jquery");
var ScrollTo = require("./vendor/jquery.scrollTo.min");
$.scrollTo = new ScrollTo();

module.exports = function Place (placeJSON, mapObject) {
  var that = this;
  this.marker = new google.maps.Marker({
    position: placeJSON.geometry.location,
    map: mapObject.map,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 3,
      strokeWeight: 1,
      fillOpacity: 1,
      fillColor: "red"
    }
  });
  this.element = placelistHeader(placeJSON);

  // add each place to the list display
  $(".list-display").append (this.element);

  // defines the detail place request
  this.detailRequest = function detailRequest (callback) {
    placesDetailRequest(placeJSON.reference, mapObject.map, callback);
  };

  // if the request placelist/infowindow is not already open
  // close windows/placelist divs, make detail request, call other funcs
  function makeRequest() {
    if(mapObject.openInfoWindow !== that.infoWindow){
      $(".places_details").remove();
      if (mapObject.openInfoWindow!==null){
        mapObject.openInfoWindow.close();
      }
      that.detailRequest (function (result) {
        var website = result.website;
        if (website){
          result.short_website = shortenWebsite(website);
        }
        infoWindow(result);
        expandListPlace(result);
      });
    }
  }

  // passes result into info template, opens info window
  function infoWindow(result) {
    that.infoWindow = new google.maps.InfoWindow({
      content: infoWindowTemplate(result)
    });
    mapObject.openInfoWindow = that.infoWindow;
    mapObject.openInfoWindow.open(mapObject.map, that.marker);
  }

  // passes result into placelist template, appends to DOM and scrolls to it
  function expandListPlace(result) {
    var place = $("#" + placeJSON.reference);
    place.after (placelistTemplate(result));
    $(".list-display").scrollTo(place, 1000);
  }

  // shorten (visible) url at first "/" after http://
  function shortenWebsite(website) {
    if (website.length > 30){
      var urlPieces = website.split("/");
      return urlPieces[2];
    }
    return website.substring(website.indexOf("//")+2, website.length-1);
  }

  // placelist listener
  $("#" + placeJSON.reference).click(makeRequest);
  // marker listener
  google.maps.event.addListener(this.marker, "click", makeRequest);
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/fast-link-to';

let { assert, get, inject, deprecate, ControllerMixin } = Ember;
let EmberComponent = Ember.Component;

let FastLinkComponent = EmberComponent.extend({
  layout: layout,

  tagName: 'a',

  /**
    Sets the `title` attribute of the `FastLinkComponent`'s HTML element.

    @property title
    @default null
    @public
  **/
  title: null,

  /**
    Sets the `rel` attribute of the `FastLinkComponent`'s HTML element.

    @property rel
    @default null
    @public
  **/
  rel: null,

  /**
    Sets the `tabindex` attribute of the `FastLinkComponent`'s HTML element.

    @property tabindex
    @default null
    @public
  **/
  tabindex: null,

  /**
    Sets the `target` attribute of the `FastLinkComponent`'s HTML element.

    @since 1.8.0
    @property target
    @default null
    @public
  **/
  target: null,

  /**
    The CSS class to apply to `FastLinkComponent`'s element when its `loading`
    property is `true`.

    @property loadingClass
    @type String
    @default loading
    @private
  **/
  loadingClass: 'loading',

  /**
    The CSS class to apply to a `FastLinkComponent`'s element when its `disabled`
    property is `true`.

    @property disabledClass
    @type String
    @default disabled
    @private
  **/
  disabledClass: 'disabled',
  _isDisabled: false,

  /**
    Determines whether the `FastLinkComponent` will trigger routing via
    the `replaceWith` routing strategy.

    @property replace
    @type Boolean
    @default false
    @public
  **/
  replace: false,

  /**
    By default the `{{fast-link-to}}` component will bind to the `href` and
    `title` attributes. It's discouraged that you override these defaults,
    however you can push onto the array if needed.

    @property attributeBindings
    @type Array | String
    @default ['title', 'rel', 'tabindex', 'target']
    @public
  */
  attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'],

  /**
    By default the `{{fast-link-to}}` component will bind to the `loading` and
    `disabled` classes. It is discouraged to override these directly.

    @property classNameBindings
    @type Array
    @default ['loading', 'disabled']
    @public
  */
  classNameBindings: ['loading', 'disabled'],

  /**
    By default the `{{fast-link-to}}` component responds to the `click` event. You
    can override this globally by setting this property to your custom
    event name.

    This is particularly useful on mobile when one wants to avoid the 300ms
    click delay using some sort of custom `tap` event.

    @property eventName
    @type String
    @default click
    @private
  */
  eventName: 'click',

  // this is doc'ed here so it shows up in the events
  // section of the API documentation, which is where
  // people will likely go looking for it.
  /**
    Triggers the `FastLinkComponent`'s routing behavior. If
    `eventName` is changed to a value other than `click`
    the routing behavior will trigger on that custom event
    instead.

    @event click
    @private
  */

  /**
    An overridable method called when `FastLinkComponent` objects are instantiated.

    Example:

    ```javascript
    App.MyLinkComponent = Ember.FastLinkComponent.extend({
      init: function() {
        this._super.apply(this, arguments);
        Ember.Logger.log('Event is ' + this.get('eventName'));
      }
    });
    ```

    NOTE: If you do override `init` for a framework class like `Ember.View`,
    be sure to call `this._super.apply(this, arguments)` in your
    `init` declaration! If you don't, Ember may not have an opportunity to
    do important setup work, and you'll see strange behavior in your
    application.

    @method init
    @private
  */
  init: Ember.LinkComponent.proto().init,

  _routing: inject.service('-routing'),

  disabled: Ember.LinkComponent.proto().disabled,

  /**
    Event handler that invokes the link, activating the associated route.

    @private
    @method _invoke
    @param {Event} event
    @private
  */
  _invoke: Ember.LinkComponent.proto()._invoke,

  queryParams: null,

  qualifiedRouteName: Ember.LinkComponent.proto().qualifiedRouteName,

  resolvedQueryParams: Ember.LinkComponent.proto().resolvedQueryParams,

  /**
    Sets the element's `href` attribute to the url for
    the `FastLinkComponent`'s targeted route.

    If the `FastLinkComponent`'s `tagName` is changed to a value other
    than `a`, this property will be ignored.

    @property href
    @private
  */
  href: Ember.LinkComponent.proto().href,

  loading: Ember.LinkComponent.proto().loading,

  _modelsAreLoaded: Ember.LinkComponent.proto()._modelsAreLoaded,

  _getModels(params) {
    let modelCount = params.length - 1;
    let models = new Array(modelCount);

    for (let i = 0; i < modelCount; i++) {
      let value = params[i + 1];

      while (ControllerMixin.detect(value)) {
        deprecate(
          'Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated. ' +
            (this.parentView ? 'Please update `' + this.parentView + '` to use `{{link-to "post" someController.model}}` instead.' : ''),
          false,
          { id: 'ember-routing-views.controller-wrapped-param', until: '3.0.0' }
        );
        value = value.get('model');
      }

      models[i] = value;
    }

    return models;
  },

  /**
    The default href value to use while a fast-link-to is loading.
    Only applies when tagName is 'a'

    @property loadingHref
    @type String
    @default #
    @private
  */
  loadingHref: '#',

  willRender() {
    let queryParams;

    // Do not mutate params in place
    let params = get(this, 'params').slice();

    assert('You must provide one or more parameters to the fast-link-to component.', params.length);

    // Process the positional arguments, in order.

    // 2. `targetRouteName` is now always at index 0.
    let owner = Ember.getOwner && Ember.getOwner(this);
    if (owner && owner.mountPoint) {
      let fullRouteName = owner.mountPoint + '.' + params[0];
      this.set('targetRouteName', fullRouteName);
    } else {
      this.set('targetRouteName', params[0]);
    }

    // 3. The last argument (if still remaining) is the `queryParams` object.
    let lastParam = params[params.length - 1];

    if (lastParam && lastParam.isQueryParams) {
      queryParams = params.pop();
    } else {
      queryParams = {};
    }
    this.set('queryParams', queryParams);

    // 4. Any remaining indices (excepting `targetRouteName` at 0) are `models`.
    if (params.length > 1) {
      this.set('models', this._getModels(params));
    } else {
      this.set('models', []);
    }
  }
});

FastLinkComponent.toString = function() { return 'FastLinkComponent'; };

FastLinkComponent.reopenClass({
  positionalParams: 'params'
});

export default FastLinkComponent;
<commit_msg>Add support for 1.13.<commit_after>import Ember from 'ember';
import layout from '../templates/components/fast-link-to';

let { assert, get, inject, deprecate, ControllerMixin } = Ember;
let EmberComponent = Ember.Component;

let FastLinkComponent = EmberComponent.extend({
  layout: layout,

  tagName: 'a',

  /**
    Sets the `title` attribute of the `FastLinkComponent`'s HTML element.

    @property title
    @default null
    @public
  **/
  title: null,

  /**
    Sets the `rel` attribute of the `FastLinkComponent`'s HTML element.

    @property rel
    @default null
    @public
  **/
  rel: null,

  /**
    Sets the `tabindex` attribute of the `FastLinkComponent`'s HTML element.

    @property tabindex
    @default null
    @public
  **/
  tabindex: null,

  /**
    Sets the `target` attribute of the `FastLinkComponent`'s HTML element.

    @since 1.8.0
    @property target
    @default null
    @public
  **/
  target: null,

  /**
    The CSS class to apply to `FastLinkComponent`'s element when its `loading`
    property is `true`.

    @property loadingClass
    @type String
    @default loading
    @private
  **/
  loadingClass: 'loading',

  /**
    The CSS class to apply to a `FastLinkComponent`'s element when its `disabled`
    property is `true`.

    @property disabledClass
    @type String
    @default disabled
    @private
  **/
  disabledClass: 'disabled',
  _isDisabled: false,

  /**
    Determines whether the `FastLinkComponent` will trigger routing via
    the `replaceWith` routing strategy.

    @property replace
    @type Boolean
    @default false
    @public
  **/
  replace: false,

  /**
    By default the `{{fast-link-to}}` component will bind to the `href` and
    `title` attributes. It's discouraged that you override these defaults,
    however you can push onto the array if needed.

    @property attributeBindings
    @type Array | String
    @default ['title', 'rel', 'tabindex', 'target']
    @public
  */
  attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'],

  /**
    By default the `{{fast-link-to}}` component will bind to the `loading` and
    `disabled` classes. It is discouraged to override these directly.

    @property classNameBindings
    @type Array
    @default ['loading', 'disabled']
    @public
  */
  classNameBindings: ['loading', 'disabled'],

  /**
    By default the `{{fast-link-to}}` component responds to the `click` event. You
    can override this globally by setting this property to your custom
    event name.

    This is particularly useful on mobile when one wants to avoid the 300ms
    click delay using some sort of custom `tap` event.

    @property eventName
    @type String
    @default click
    @private
  */
  eventName: 'click',

  // this is doc'ed here so it shows up in the events
  // section of the API documentation, which is where
  // people will likely go looking for it.
  /**
    Triggers the `FastLinkComponent`'s routing behavior. If
    `eventName` is changed to a value other than `click`
    the routing behavior will trigger on that custom event
    instead.

    @event click
    @private
  */

  /**
    An overridable method called when `FastLinkComponent` objects are instantiated.

    Example:

    ```javascript
    App.MyLinkComponent = Ember.FastLinkComponent.extend({
      init: function() {
        this._super.apply(this, arguments);
        Ember.Logger.log('Event is ' + this.get('eventName'));
      }
    });
    ```

    NOTE: If you do override `init` for a framework class like `Ember.View`,
    be sure to call `this._super.apply(this, arguments)` in your
    `init` declaration! If you don't, Ember may not have an opportunity to
    do important setup work, and you'll see strange behavior in your
    application.

    @method init
    @private
  */
  init: Ember.LinkComponent.proto().init,

  _routing: inject.service('-routing'),

  disabled: Ember.LinkComponent.proto().disabled,

  /**
    Event handler that invokes the link, activating the associated route.

    @private
    @method _invoke
    @param {Event} event
    @private
  */
  _invoke: Ember.LinkComponent.proto()._invoke,

  queryParams: null,

  /* These two exist to support 1.13. */
  _computeRouteNameWithQueryParams: Ember.LinkComponent.proto()._computeRouteNameWithQueryParams,

  _handleOnlyQueryParamsSupplied: Ember.LinkComponent.proto()._handleOnlyQueryParamsSupplied,

  qualifiedRouteName: Ember.LinkComponent.proto().qualifiedRouteName,

  resolvedQueryParams: Ember.LinkComponent.proto().resolvedQueryParams,

  /**
    Sets the element's `href` attribute to the url for
    the `FastLinkComponent`'s targeted route.

    If the `FastLinkComponent`'s `tagName` is changed to a value other
    than `a`, this property will be ignored.

    @property href
    @private
  */
  href: Ember.LinkComponent.proto().href,

  loading: Ember.LinkComponent.proto().loading,

  _modelsAreLoaded: Ember.LinkComponent.proto()._modelsAreLoaded,

  _getModels(params) {
    let modelCount = params.length - 1;
    let models = new Array(modelCount);

    for (let i = 0; i < modelCount; i++) {
      let value = params[i + 1];

      while (ControllerMixin.detect(value)) {
        deprecate(
          'Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated. ' +
            (this.parentView ? 'Please update `' + this.parentView + '` to use `{{link-to "post" someController.model}}` instead.' : ''),
          false,
          { id: 'ember-routing-views.controller-wrapped-param', until: '3.0.0' }
        );
        value = value.get('model');
      }

      models[i] = value;
    }

    return models;
  },

  /**
    The default href value to use while a fast-link-to is loading.
    Only applies when tagName is 'a'

    @property loadingHref
    @type String
    @default #
    @private
  */
  loadingHref: '#',

  willRender() {
    let queryParams;

    // Do not mutate params in place
    let params = get(this, 'params').slice();

    assert('You must provide one or more parameters to the fast-link-to component.', params.length);

    // Process the positional arguments, in order.

    // 2. `targetRouteName` is now always at index 0.
    let owner = Ember.getOwner && Ember.getOwner(this);
    if (owner && owner.mountPoint) {
      let fullRouteName = owner.mountPoint + '.' + params[0];
      this.set('targetRouteName', fullRouteName);
    } else {
      this.set('targetRouteName', params[0]);
    }

    // 3. The last argument (if still remaining) is the `queryParams` object.
    let lastParam = params[params.length - 1];

    if (lastParam && lastParam.isQueryParams) {
      queryParams = params.pop();
    } else {
      queryParams = {};
    }
    this.set('queryParams', queryParams);

    // 4. Any remaining indices (excepting `targetRouteName` at 0) are `models`.
    if (params.length > 1) {
      this.set('models', this._getModels(params));
    } else {
      this.set('models', []);
    }
  }
});

FastLinkComponent.toString = function() { return 'FastLinkComponent'; };

FastLinkComponent.reopenClass({
  positionalParams: 'params'
});

export default FastLinkComponent;
<|endoftext|>


<commit_before>'use strict'

exports.seed = function (knex, Promise) {
  return knex('tags').del()
    .then(() => knex('tags').insert([
      {id: 1, name: 'offer'},
      {id: 2, name: 'request'}
    ]))
}
<commit_msg>intention should also be in seeds file<commit_after>'use strict'

exports.seed = function (knex, Promise) {
  return knex('tags').del()
    .then(() => knex('tags').insert([
      {id: 1, name: 'offer'},
      {id: 2, name: 'request'},
      {id: 3, name: 'intention'}
    ]))
}
<|endoftext|>


<commit_before>import { expect }   from 'chai';
import { generate } from '..';
import { readFile } from 'fs';
import parser       from 'sqlite-parser';
import glob         from 'glob';
import * as _       from 'lodash';

describe('test suite', () => {
    // get all sql files in our test suite
    const files = glob.sync('test/sql/**/*.sql');

    // extract information from the filepath names
    const tests = _.groupBy(_.map(files, (file) => {
        let r = /^test\/sql\/([\s\S]*)\/([\s\S]*)\.sql/gi.exec(file);
        return {
            filePath : file,
            group : r[1],
            name : r[2]
        };
    }), 'group');

    // extract a list of the main areas under test
    let groups = _.keys(tests);

    // we dynamically generate the test suites from the above information
    _.map(groups, (group) => {

        describe(`${group} statements`, () => {

            _.map(tests[group], (test) => {
                it('generates ' + test.name, (done) => {
                    readFile(test.filePath, (err, data) => {
                        if (err) throw "Unable to read file";

                        const sql = data.toString();

                        const ast = parser(sql);

                        const regeneratedSQL = generate(ast);
                        console.log(regeneratedSQL);

                        const isParsible = parser(regeneratedSQL);

                        expect(isParsible).to.deep.equal(ast);
                        expect(standardiseString(regeneratedSQL)).to.equal(standardiseString(sql));
                        done();
                    });
                });
            });
        });
    });
});

function standardiseString(str){
    // We want to strip all optional items from strings before testing equality.
    // The strings could have different options for these items and they
    // interfere with the tests.
    return str.replace(/\s+/gi, '')
              .replace(/\(*/gi, '')
              .replace(/\)*/gi, '')
              .replace(/\`*/gi, '')
              .replace(/\;*/gi, '')
              .replace(/\"*/gi, '')
              .toLowerCase();
}<commit_msg>clean up tests<commit_after>import { expect }   from 'chai';
import { generate } from '..';
import { readFile } from 'fs';
import parser       from 'sqlite-parser';
import glob         from 'glob';
import * as _       from 'lodash';

describe('test suite', () => {
    // get all sql files in our test suite
    const files = glob.sync('test/sql/**/*.sql');

    // extract information from the filepath names
    const tests = _.groupBy(_.map(files, (file) => {
        let r = /^test\/sql\/([\s\S]*)\/([\s\S]*)\.sql/gi.exec(file);
        return {
            filePath : file,
            group : r[1],
            name : r[2]
        };
    }), 'group');

    // extract a list of the main areas under test
    let groups = _.keys(tests);

    // we dynamically generate the test suites from the above information
    _.map(groups, (group) => {

        describe(`${group} statements`, () => {

            _.map(tests[group], (test) => {
                it('generates ' + test.name, (done) => {
                    readFile(test.filePath, (err, data) => {
                        if (err) throw "Unable to read file";

                        const sql = data.toString();
                        const ast = parser(sql);
                        const regeneratedSQL = generate(ast);
                        const isParsible = parser(regeneratedSQL);

                        expect(isParsible).to.deep.equal(ast);
                        expect(standardiseString(regeneratedSQL)).to.equal(standardiseString(sql));
                        done();
                    });
                });
            });
        });
    });
});

function standardiseString(str){
    // We want to strip all optional items from strings before testing equality.
    // The strings could have different options for these items and they
    // interfere with the tests.
    return str.replace(/\s+/gi, '')
              .replace(/\(*/gi, '')
              .replace(/\)*/gi, '')
              .replace(/\`*/gi, '')
              .replace(/\;*/gi, '')
              .replace(/\"*/gi, '')
              .toLowerCase();
}<|endoftext|>


<commit_before>exports.register = function api(server, options, next) {
  server.register(
    [
      {
        register: require('./modules/users/routes')
      },
      {
        register: require('./modules/projects/routes')
      },
      {
        register: require('./modules/files/routes')
      },
      {
        register: require('./modules/publishedProjects/routes')
      },
      {
        register: require('./modules/publishedFiles/routes')
      }
    ], function(err) {
    if ( err ) {
      return next(err);
    }
    server.route({
      method: 'GET',
      path: '/',
      handler: function (request, reply) {
        reply(JSON.stringify(
          {
            'name': 'publish.webmaker.org',
            'description': 'the teach.org publishing service for goggles and thimble',
            'routes': {
              'users': '/users',
              'projects': '/projects',
              'files': '/files',
              'publishedProjects': '/publishedProjects',
              'publishedFiles': '/publishedFiles'
            }
          }, null, 2)
        );
      }
    });

    next();
  });
};

exports.register.attributes = {
  name: 'publish-webmaker-api',
  version: '0.0.0'
};
<commit_msg>Fix #202 - Add /healthcheck route<commit_after>exports.register = function api(server, options, next) {
  server.register(
    [
      {
        register: require('./modules/users/routes')
      },
      {
        register: require('./modules/projects/routes')
      },
      {
        register: require('./modules/files/routes')
      },
      {
        register: require('./modules/publishedProjects/routes')
      },
      {
        register: require('./modules/publishedFiles/routes')
      }
    ], function(err) {
    if ( err ) {
      return next(err);
    }
    server.route([{
      method: 'GET',
      path: '/',
      config: {
        auth: false
      },
      handler: function (request, reply) {
        return reply(request.generateResponse({
          name: 'publish.webmaker.org',
          description: 'the teach.org publishing service for goggles and thimble',
          routes: {
            users: '/users',
            projects: '/projects',
            files: '/files',
            publishedProjects: '/publishedProjects',
            publishedFiles: '/publishedFiles'
          }
        })
        .code(200));
      }
    }, {
      method: 'GET',
      path: '/healthcheck',
      config: {
        auth: false
      },
      handler: function (request, reply) {
        return reply(request.generateResponse({
          http: 'okay'
        })
        .code(200));
      }
    }]);

    next();
  });
};

exports.register.attributes = {
  name: 'publish-webmaker-api',
  version: '0.0.0'
};
<|endoftext|>


<commit_before>
var root = '/api/v1';

module.exports = function(app) {

  // REST API v1.0 ===========================================

  app.get(root + '/time', function(req, res) {
    res.set('Content-Type', 'application/json');
    res.send(JSON.stringify({time: new Date().getTime() }));
  });

  app.get(root + '/hello', function(req,res) {
    res.send('HELLO WORLD');
  });

  app.get(root + '/hello/:id/:name', function(req,res) {
    res.send('HELLO '+ req.params.name + ' ('+req.params.id+')');
  });

  app.delete(root+'/hello/:id', function(req,res) {
    res.send('GOODBYE ' + req.params.id);
  });
};
<commit_msg>get adelaide weather rss feed<commit_after>var request = require('request');

var root = '/api/v1';

module.exports = function(app) {

  // REST API v1.0 ===========================================

  app.get(root + '/time', function(req, res) {
    res.set('Content-Type', 'application/json');
    res.send(JSON.stringify({time: new Date().getTime() }));
  });

  app.get(root + '/weather', function(req, res) {
    req.pipe(request('http://rss.weatherzone.com.au/?u=12994-1285&lt=aploc&lc=12495&obs=1&fc=1&warn=0')).pipe(res);
  });

  app.get(root + '/hello', function(req,res) {
    res.send('HELLO WORLD');
  });

  app.get(root + '/hello/:id/:name', function(req,res) {
    res.send('HELLO '+ req.params.name + ' ('+req.params.id+')');
  });

  app.delete(root+'/hello/:id', function(req,res) {
    res.send('GOODBYE ' + req.params.id);
  });
};
<|endoftext|>


<commit_before>import Ember from 'ember';

const FormControl = Ember.Component.extend({
  intl: Ember.inject.service(),

  showErrors: false,

  classNames: "form-field",

  classNameBindings: ['hasErrors:has-errors'],

  inputId: Ember.computed("elementId", {
    get() {
      return `${this.get("elementId")}-input`;
    }
  }),

  label: Ember.computed("data", "field", {
    get() {
      let modelName =
        this.get("data.content.constructor.modelName") ||
        this.get("data.constructor.modelName");

      if (!modelName) {
        return;
      }

      let fieldName = this.get("field");

      if (!fieldName) {
        return;
      }

      modelName = Ember.String.underscore(modelName);
      fieldName = Ember.String.underscore(fieldName);

      return this.get("intl").t(
        `models.attributes.${modelName}.${fieldName}`);
    }
  }),

  init() {
    this._super(...arguments);

    this.hasErrors = Ember.computed.notEmpty(
      `data.validations.attrs.${this.get('field')}.errors`);
  }
});

FormControl.reopenClass({
  positionalParams: ["field"]
});

export default FormControl;
<commit_msg>Add class when an input receives focus<commit_after>import Ember from 'ember';

const FormControl = Ember.Component.extend({
  intl: Ember.inject.service(),
  classNames: "form-field",
  classNameBindings: ['hasErrors:has-errors', 'focused'],

  showErrors: false,

  focusIn() {
    this.set('focused', true);
  },

  focusOut() {
    this.set('focused', false);
  },

  inputId: Ember.computed("elementId", {
    get() {
      return `${this.get("elementId")}-input`;
    }
  }),

  label: Ember.computed("data", "field", {
    get() {
      let modelName =
        this.get("data.content.constructor.modelName") ||
        this.get("data.constructor.modelName");

      if (!modelName) {
        return;
      }

      let fieldName = this.get("field");

      if (!fieldName) {
        return;
      }

      modelName = Ember.String.underscore(modelName);
      fieldName = Ember.String.underscore(fieldName);

      return this.get("intl").t(
        `models.attributes.${modelName}.${fieldName}`);
    }
  }),

  init() {
    this._super(...arguments);

    this.hasErrors = Ember.computed.notEmpty(
      `data.validations.attrs.${this.get('field')}.errors`);
  }
});

FormControl.reopenClass({
  positionalParams: ["field"]
});

export default FormControl;
<|endoftext|>


<commit_before>var assert = require("assert"),
    form = require("../index"),
    filter = form.filter,
    validate = form.validator;

module.exports = {

  'validate : isEmail': function() {
    // Skip validating empty values
    var request = { body: {} };
    var formValidator = form(validate("field").isEmail());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);

    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isEmail());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid email");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isEmail("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "me@dandean.com" }};
    var formValidator = form(validate("field").isEmail());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isUrl': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUrl());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid URL");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUrl("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "http://www.google.com" }};
    var formValidator = form(validate("field").isUrl());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isIP': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isIP());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid IP");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isIP("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "0.0.0.0" }};
    var formValidator = form(validate("field").isIP());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isAlpha': function() {
    // Failure.
    var request = { body: { field: "123456" }};
    var formValidator = form(validate("field").isAlpha());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "123456" }};
    var formValidator = form(validate("field").isAlpha("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "abcde" }};
    var formValidator = form(validate("field").isAlpha());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isAlphanumeric': function() {
    // Failure.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isAlphanumeric());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isAlphanumeric("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "abc123" }};
    var formValidator = form(validate("field").isAlphanumeric());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isNumeric': function() {
    // Failure.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isNumeric());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid number");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isNumeric("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success Int
    var request = { body: {
      integer: "123456",
      floating: "123456.45",
      negative: "-123456.45",
      positive: "+123456.45",
      padded: "000045.343"
    }};
    var formValidator = form(
      validate("integer").isNumeric(),
      validate("floating").isNumeric(),
      validate("negative").isNumeric(),
      validate("positive").isNumeric(),
      validate("padded").isNumeric()
    );
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isInt': function() {
    // Failure.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isInt());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid integer");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isInt("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "50" }};
    var formValidator = form(validate("field").isInt());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isLowercase': function() {
    // Failure.
    var request = { body: { field: "FAIL" }};
    var formValidator = form(validate("field").isLowercase());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "FAIL" }};
    var formValidator = form(validate("field").isInt("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "win" }};
    var formValidator = form(validate("field").isLowercase());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isUppercase': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUppercase());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUppercase("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "WIN" }};
    var formValidator = form(validate("field").isUppercase());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isFloat': function() {
    // Failure.
    var request = { body: { field: "5000" }};
    var formValidator = form(validate("field").isFloat());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid decimal");

    // Failure w/ custom message.
    var request = { body: { field: "5000" }};
    var formValidator = form(validate("field").isFloat("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "5000.00" }};
    var formValidator = form(validate("field").isFloat());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : notNull': function() {
    // Failure.
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").notNull());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").notNull("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "win" }};
    var formValidator = form(validate("field").notNull());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isNull': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isNull());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isNull("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").isNull());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validation : required': function() {
    // Failure
    var request = { body: {}};
    var formValidator = form(validate("a_number").required());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "a_number is a required field");

    // Failure w/ custom message and placeholder value.
    var request = { body: { a_number: "a_value" }};
    var formValidator = form(validate("a_number").required("a_value", "!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! a_number !!!");

    // Success
    var request = { body: { a_number: "5000" }};
    var formValidator = form(validate("a_number").required("a_value", "!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  '1. configuration': function() {
  },

  '2. list users': function() {
  },

  '3. create user': function() {
  },

  '4. get user': function() {
  },

  '5. modify user': function() {
  }
};<commit_msg>Unit tests of isNull and notNull.<commit_after>var assert = require("assert"),
    form = require("../index"),
    filter = form.filter,
    validate = form.validator;

module.exports = {

  'validate : isEmail': function() {
    // Skip validating empty values
    var request = { body: {} };
    var formValidator = form(validate("field").isEmail());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);

    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isEmail());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid email");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isEmail("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "me@dandean.com" }};
    var formValidator = form(validate("field").isEmail());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isUrl': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUrl());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid URL");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUrl("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "http://www.google.com" }};
    var formValidator = form(validate("field").isUrl());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isIP': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isIP());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid IP");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isIP("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "0.0.0.0" }};
    var formValidator = form(validate("field").isIP());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isAlpha': function() {
    // Failure.
    var request = { body: { field: "123456" }};
    var formValidator = form(validate("field").isAlpha());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "123456" }};
    var formValidator = form(validate("field").isAlpha("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "abcde" }};
    var formValidator = form(validate("field").isAlpha());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isAlphanumeric': function() {
    // Failure.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isAlphanumeric());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isAlphanumeric("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "abc123" }};
    var formValidator = form(validate("field").isAlphanumeric());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isNumeric': function() {
    // Failure.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isNumeric());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid number");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isNumeric("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success Int
    var request = { body: {
      integer: "123456",
      floating: "123456.45",
      negative: "-123456.45",
      positive: "+123456.45",
      padded: "000045.343"
    }};
    var formValidator = form(
      validate("integer").isNumeric(),
      validate("floating").isNumeric(),
      validate("negative").isNumeric(),
      validate("positive").isNumeric(),
      validate("padded").isNumeric()
    );
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isInt': function() {
    // Failure.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isInt());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid integer");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    var formValidator = form(validate("field").isInt("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "50" }};
    var formValidator = form(validate("field").isInt());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isLowercase': function() {
    // Failure.
    var request = { body: { field: "FAIL" }};
    var formValidator = form(validate("field").isLowercase());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "FAIL" }};
    var formValidator = form(validate("field").isInt("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "win" }};
    var formValidator = form(validate("field").isLowercase());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isUppercase': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUppercase());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isUppercase("!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "WIN" }};
    var formValidator = form(validate("field").isUppercase());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isFloat': function() {
    // Failure.
    var request = { body: { field: "5000" }};
    var formValidator = form(validate("field").isFloat());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid decimal");

    // Failure w/ custom message.
    var request = { body: { field: "5000" }};
    var formValidator = form(validate("field").isFloat("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "5000.00" }};
    var formValidator = form(validate("field").isFloat());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : notNull': function() {
    // Failure.
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").notNull());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").notNull("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "win" }};
    var formValidator = form(validate("field").notNull());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : isNull': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isNull());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    var formValidator = form(validate("field").isNull("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").isNull());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validate : notEmpty': function() {
    // Failure.
    var request = { body: { field: "  \t" }};
    var formValidator = form(validate("field").notEmpty());
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "  \t" }};
    var formValidator = form(validate("field").notEmpty("!!! %s !!!"));
    formValidator(request, {});
    assert.ok(Array.isArray(request.form.errors));
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "" }};
    var formValidator = form(validate("field").notEmpty());
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  'validation : required': function() {
    // Failure
    var request = { body: {}};
    var formValidator = form(validate("a_number").required());
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "a_number is a required field");

    // Failure w/ custom message and placeholder value.
    var request = { body: { a_number: "a_value" }};
    var formValidator = form(validate("a_number").required("a_value", "!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! a_number !!!");

    // Success
    var request = { body: { a_number: "5000" }};
    var formValidator = form(validate("a_number").required("a_value", "!!! %s !!!"));
    formValidator(request, {});
    assert.equal(request.form.errors, undefined);
  },

  '1. configuration': function() {
  },

  '2. list users': function() {
  },

  '3. create user': function() {
  },

  '4. get user': function() {
  },

  '5. modify user': function() {
  }
};<|endoftext|>