<commit_before>import postcss from 'postcss';
import test    from 'ava';

import plugin from './';

function run(t, input, output, opts = { }) {
    return postcss([ plugin(opts) ]).process(input)
        .then( result => {
            t.deepEqual(result.css, output);
            t.deepEqual(result.warnings().length, 0);
        });
}

test('Chain ancestor in a simple case', t => {
    return run( t,
                '.a{ &:hover{ ^&-b{} } }',
                '.a{ &:hover{ .a-b{} } }',
                { }
    );
});

test('Prepend ancestor in a simple case', t => {
    return run( t,
                '.a{ &:hover{ ^& .b{} } }',
                '.a{ &:hover{ .a .b{} } }',
                { }
    );
});

test('Chain 2 ancestors in double selector', t => {
    return run( t,
                '.a{ &:hover{ ^&-b, ^&-c{} } }',
                '.a{ &:hover{ .a-b, .a-c{} } }',
                { }
    );
});

test('Prepend 2 ancestors in double selector', t => {
    return run( t,
                '.a{ &:hover{ ^& .b, ^& .c{} } }',
                '.a{ &:hover{ .a .b, .a .c{} } }',
                { }
    );
});

test('Replace declaration values if replaceValues is true', t => {
    return run( t,
                '.a{ background: red; &:hover {&::before { content: "^&"; }}}',
                '.a{ background: red; &:hover {&::before { content: ".a"; }}}',
                { replaceValues: true }
    );
});

test('Take into account pseudo classes if pseudoClasses is true', t => {
    return run( t,
                '.a{ background: red; &:hover {&::before ' +
                '{ content: "^&"; }}}',
                '.a{ background: red; &:hover {&::before ' +
                '{ content: ".a:hover"; }}}',
                { replaceValues: true, pseudoClasses: true }
    );
});

test('Replace ancestors at different nesting levels', t => {
    return run( t,
                '.a{ &:hover{ ^&-b{} } .c{ .d{ ^&-e{} } } .z{} }',
                '.a{ &:hover{ .a-b{} } .c{ .d{ .a .c-e{} } } .z{} }',
                { }
    );
});

test('Replace ancestors with 3 different hierarchy levels', t => {
    return run( t,
                '.a{ &-b{ &-c{ ^&-d,^&-d{} ^^&-d{} ^^^&-d{}} } }',
                '.a{ &-b{ &-c{ .a-b-d,.a-b-d{} .a-d{} -d{}} } }',
                { }
    );
});

test('Process 2 nested ancestors', t => {
    return run( t,
                '.a{ &-b{ &-c{ ^^&-d{ &-e{ ^^^^&-f{ } } } } } }',
                '.a{ &-b{ &-c{ .a-d{ &-e{ .a-f{ } } } } } }',
                { }
    );
});

test('Process nested ancestor near to > \, + and ~ selectors', t => {
    return run( t,
                '.a{ &-b{ > ^&-c{} + ^&-d{} ~ ^&-e{} } }',
                '.a{ &-b{ > .a-c{} + .a-d{} ~ .a-e{} } }',
                { }
    );
});

test('Return empty string when pointing to a non-existent ancestor', t => {
    return run( t,
                '.a{ &-b{ &-c{ ^^^^&-d{} } } }',
                '.a{ &-b{ &-c{ -d{} } } }',
                { }
    );
});

test('Replace default ancestor selector with \"£%\"', t => {
    return run( t,
                '.a{ &-b{ &-c{ ££%-d{ £££%-f{ } } } } }',
                '.a{ &-b{ &-c{ .a-d{ .a-f{ } } } } }',
                { placeholder: '£%' }
    );
});

test('Replace default ancestor with custom levelSymbol and parentSymbol', t => {
    return run( t,
                '.a{ &-b{ &-c{ foofoobar-d{ foofoofoobar-f{ } } } } }',
                '.a{ &-b{ &-c{ .a-d{ .a-f{ } } } } }',
                { levelSymbol: 'foo', parentSymbol: 'bar' }
    );
});
<commit_msg>Normalize tests<commit_after>import postcss from 'postcss';
import test    from 'ava';

import plugin from './';

function run(t, input, output, opts = { }) {
    return postcss([ plugin(opts) ]).process(input)
        .then( result => {
            t.deepEqual(result.css, output);
            t.deepEqual(result.warnings().length, 0);
        });
}

test('Chain ancestor in a simple case', t => {
    return run( t,
                '.a{ &:hover{ ^&-b{} } }',
                '.a{ &:hover{ .a-b{} } }',
                { }
    );
});

test('Prepend ancestor in a simple case', t => {
    return run( t,
                '.a{ &:hover{ ^& .b{} } }',
                '.a{ &:hover{ .a .b{} } }',
                { }
    );
});

test('Chain 2 ancestors in double selector', t => {
    return run( t,
                '.a{ &:hover{ ^&-b, ^&-c{} } }',
                '.a{ &:hover{ .a-b, .a-c{} } }',
                { }
    );
});

test('Prepend 2 ancestors in double selector', t => {
    return run( t,
                '.a{ &:hover{ ^& .b, ^& .c{} } }',
                '.a{ &:hover{ .a .b, .a .c{} } }',
                { }
    );
});

test('Replace declaration values if replaceValues is true', t => {
    return run( t,
                '.a{ &:hover { &:before { content: "^&"; } } }',
                '.a{ &:hover { &:before { content: ".a"; } } }',
                { replaceValues: true }
    );
});

test('Take into account pseudo classes if pseudoClasses is true', t => {
    return run( t,
                '.a{ &:hover { &:before { content: "^&"; } } }',
                '.a{ &:hover { &:before { content: ".a:hover"; } } }',
                { replaceValues: true, pseudoClasses: true }
    );
});

test('Replace ancestors at different nesting levels', t => {
    return run( t,
                '.a{ &:hover{ ^&-b{} } .c{ .d{ ^&-e{} } } .z{} }',
                '.a{ &:hover{ .a-b{} } .c{ .d{ .a .c-e{} } } .z{} }',
                { }
    );
});

test('Replace ancestors with 3 different hierarchy levels', t => {
    return run( t,
                '.a{ &-b{ &-c{ ^&-d,^&-d{} ^^&-d{} ^^^&-d{}} } }',
                '.a{ &-b{ &-c{ .a-b-d,.a-b-d{} .a-d{} -d{}} } }',
                { }
    );
});

test('Process 2 nested ancestors', t => {
    return run( t,
                '.a{ &-b{ &-c{ ^^&-d{ &-e{ ^^^^&-f{ } } } } } }',
                '.a{ &-b{ &-c{ .a-d{ &-e{ .a-f{ } } } } } }',
                { }
    );
});

test('Process nested ancestor close to > \, + and ~ selectors', t => {
    return run( t,
                '.a{ &-b{ > ^&-c{} + ^&-d{} ~ ^&-e{} } }',
                '.a{ &-b{ > .a-c{} + .a-d{} ~ .a-e{} } }',
                { }
    );
});

test('Return empty string when pointing to a non-existent ancestor', t => {
    return run( t,
                '.a{ &-b{ &-c{ ^^^^&-d{} } } }',
                '.a{ &-b{ &-c{ -d{} } } }',
                { }
    );
});

test('Replace default ancestor selector with \"£%\"', t => {
    return run( t,
                '.a{ &-b{ &-c{ ££%-d{ £££%-f{ } } } } }',
                '.a{ &-b{ &-c{ .a-d{ .a-f{ } } } } }',
                { placeholder: '£%' }
    );
});

test('Replace default ancestor with custom levelSymbol and parentSymbol', t => {
    return run( t,
                '.a{ &-b{ &-c{ foofoobar-d{ foofoofoobar-f{ } } } } }',
                '.a{ &-b{ &-c{ .a-d{ .a-f{ } } } } }',
                { levelSymbol: 'foo', parentSymbol: 'bar' }
    );
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-12-4 02:19:59<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var Lexer = module.exports = function Lexer(str) {
  this.tokens = [];
  this.line = 1;
  this.indented = 0;
  this.str = str
    .trim()
    .replace(/\r\n|\r|\n *\n/g, '\n');
}

Lexer.prototype = {

  exec: function () {
    while (this.str.length) {
      this.next();
    }
    return this.tokens;
  },

  token: function (type, line, match, value) {
    return {
      type: type
      , line: line
      , match: match
      , value: value
    }
  },

  push: function (type, line, match, value) {
    this.tokens.push(this.token(type, line, match, value));
  },

  scan: function (regexp, type, callback) {
    var captures
      , token;
    if (captures = regexp.exec(this.str)) {
      this.str = this.str.substr(captures[0].length);
      if (typeof callback == 'function') {
        callback.call(this, captures);
      } else {
        this.push(type, this.line, captures[0], captures[1]);
      }
      return true;
    }
  },

  next: function () {
    return this.scan(/^\n( *)(?! *-#)/, 'indent', this.indent)
      || this.scan(/^\- *block (\w+)*/, 'block')
      || this.scan(/^\{(.*)\}/, 'attrs')
      || this.scan(/^([a-zA-Z][a-zA-Z0-9:]*)/, 'tag')
      || this.scan(/^\.([\w\-]+)/, 'class')
      || this.scan(/^\#([\w\-]+)/, 'id')
      || this.scan(/^([^\n]+)/, 'text')
  },

  indent: function (captures) {
    var indents = captures[1].length / 2;
    this.line++;
    if (indents % 1) {
      throw(new Error('indentation line ' + this.line));
    } else if (this.indented > indents) {
      while (this.indented-- > indents) {
        this.push("outdent", this.line);
      }
    } else if (this.indented !== indents) {
      this.push("indent", this.line);
    }
    this.indented = indents;
  }

}
<commit_msg>newline support<commit_after>var Lexer = module.exports = function Lexer(str) {
  this.tokens = [];
  this.line = 1;
  this.indented = 0;
  this.str = str
    .trim()
    .replace(/\r\n|\r|\n *\n/g, '\n');
}

Lexer.prototype = {

  exec: function () {
    while (this.str.length) {
      this.next();
    }
    return this.tokens;
  },

  token: function (type, line, match, value) {
    return {
      type: type
      , line: line
      , match: match
      , value: value
    }
  },

  push: function (type, line, match, value) {
    this.tokens.push(this.token(type, line, match, value));
  },

  scan: function (regexp, type, callback) {
    var captures
      , token;
    if (captures = regexp.exec(this.str)) {
      this.str = this.str.substr(captures[0].length);
      if (typeof callback == 'function') {
        callback.call(this, captures);
      } else {
        this.push(type, this.line, captures[0], captures[1]);
      }
      return true;
    }
  },

  next: function () {
    return this.scan(/^\n( *)(?! *-#)/, 'indent', this.indent)
      || this.scan(/^\- *block (\w+)*/, 'block')
      || this.scan(/^\{(.*)\}/, 'attrs')
      || this.scan(/^([a-zA-Z][a-zA-Z0-9:]*)/, 'tag')
      || this.scan(/^\.([\w\-]+)/, 'class')
      || this.scan(/^\#([\w\-]+)/, 'id')
      || this.scan(/^([^\n]+)/, 'text')
  },

  indent: function (captures) {
    var indents = captures[1].length / 2;
    this.line++;
    if (indents % 1) {
      throw(new Error('indentation line ' + this.line));
    } else if (this.indented > indents) {
      while (this.indented-- > indents) {
        this.push("outdent", this.line);
      }
    } else if (this.indented !== indents) {
      this.push("indent", this.line);
    } else {
      this.push("newline", this.line);
    }
    this.indented = indents;
  }

}
<|endoftext|>


<commit_before>import postcss from 'postcss';
import test    from 'ava';

import plugin from './';

function run(t, input, output) {
    return postcss([ plugin ]).process(input)
        .then( result => {
            t.is(result.css, output);
            t.is(result.warnings().length, 0);
        });
}

test('adds blur to html', t => {
    run(t, 'html {}',
           'html { color: transparent; text-shadow: 0 0 5px rgba(0,0,0,1) }');
});
<commit_msg>Update test<commit_after>import postcss from 'postcss';
import test    from 'ava';

import plugin from './';

function run(t, input, output) {
    return postcss([ plugin ]).process(input)
        .then( result => {
            t.is(result.css, output);
            t.is(result.warnings().length, 0);
        });
}

test('adds blur to html', t => {
    run(t, 'a { color: pink; }',
           'a { color: transparent; text-shadow: 0 0 5px rgba(0,0,0,0.5) }');
});
<|endoftext|>


<commit_before>module.exports = function (code, ast, opts) {
  var gen = new CodeGenerator(code, ast, opts);
  return gen.generate();
};

module.exports.CodeGenerator = CodeGenerator;

var sourceMap = require("source-map");
var assert    = require("assert");
var util      = require("./util");
var t         = require("./types");
var _         = require("lodash");

function CodeGenerator(code, ast, opts) {
  opts = opts || {}

  this.tabWidth = 2;
  this.opts     = opts;
  this.ast      = ast;
  this.buf      = "";

  this.line    = 1;
  this.column  = 0;
  this._indent = 0;

  if (opts.sourceMap) {
    this.map = new sourceMap.SourceMapGenerator({
      file: opts.sourceMapName
    });

    this.map.setSourceContent(opts.sourceFileName, code);
  } else {
    this.map = null;
  }
}

CodeGenerator.prototype.mark = function (node, locType) {
  var loc = node.loc;
  if (!loc) return; // no locaiton info

  var map = this.map;
  if (!map) return; // no source map

  map.addMapping({
    source: this.opts.sourceFileName,
    generated: {
      line: this.line,
      column: this.column
    },
    original: loc[locType]
  });
};

CodeGenerator.prototype.newline = function () {
  this.buf += "\n";
  this.line++;
};

CodeGenerator.prototype.semicolon = function () {
  this.buf += ";";
  this.column++;
};

CodeGenerator.prototype.keyword = function (name) {
  this.push(name);
  this.push(" ");
};

CodeGenerator.prototype.push = function (str) {
  if (this._indent) {
    // we have an indent level and we aren't pushing a newline
    var indent = this.getIndent();

    // replace all newlines with newlines with the indentation
    str = str.replace(/\n/g, "\n" + indent);

    // we've got a newline before us so prepend on the indentation
    if (this.isLast("\n")) str = indent + str;
  }

  var self = this;

  _.each(str, function (cha) {
    if (cha === "\n") {
      self.line++;
      self.column = 0;
    } else {
      self.column++;
    }
  });

  this.buf += str;
};

CodeGenerator.prototype.isLast = function (cha) {
  return _.last(this.buf) === cha;
};

CodeGenerator.prototype.getIndent = function () {
  return util.repeat(this._indent * this.tabWidth);
};

CodeGenerator.prototype.indent = function () {
  this._indent++;
};

CodeGenerator.prototype.dedent = function () {
  this._indent--;
};

CodeGenerator.prototype.generate = function () {
  var ast = this.ast;

  this.print(ast);

  var map = this.map;
  if (map) map = map.toJSON();

  return {
    map:  map,
    ast:  ast,
    code: this.buf
  };
};

CodeGenerator.prototype.buildPrint = function (parent) {
  var self = this;

  var print = function (node) {
    return self.print(node, parent);
  };

  print.sequence = function (nodes) {
    return self.printJoin(print, nodes);
  };

  return print;
};

CodeGenerator.prototype.print = function (node, parent) {
  if (!node) return "";

  if (this[node.type]) {
    this.printLeadingComments(node);
    this.mark(node, "start");

    var needsParans = t.needsParans(node, parent);
    if (needsParans) this.push("(");
    this[node.type](node, this.buildPrint(node), parent);
    if (needsParans) this.push(")");

    this.mark(node, "end");
    this.printTrailingComments(node);
  } else {
    throw new ReferenceError("unknown node " + node.type + " " + JSON.stringify(node));
  }
};

CodeGenerator.prototype.generateComment = function (comment) {
  var val = comment.value;
  if (comment.type === "Line") {
    if (_.last(val) !== "\n") {
      val += "\n";
    }
    return "//" + val;
  } else {
    return "/*" + val + "*/\n";
  }
};

CodeGenerator.prototype.printTrailingComments = function (node) {
  var self = this;
  _.each(node.trailingComments, function (comment) {
    self.push(self.generateComment(comment));
  });
};

CodeGenerator.prototype.printLeadingComments = function (node) {
  var self = this;
  _.each(node.leadingComments, function (comment) {
    self.push(self.generateComment(comment));
  });
};

CodeGenerator.prototype.printJoin = function (print, nodes, sep, opts) {
  opts = opts || {};
  sep  = sep || "\n";

  var self = this;
  var len  = nodes.length;

  if (opts.indent) self.indent();

  _.each(nodes, function (node, i) {
    if (opts.iterator) {
      opts.iterator(node, i);
    } else {
      print(node);
    }

    if (i < len - 1) {
      self.push(sep);
    }
  });

  if (opts.indent) self.dedent();
};

CodeGenerator.generators = {
  arrayComprehensions: require("./generators/array-comprehensions"),
  templateLiterals:    require("./generators/template-literals"),
  expressions:         require("./generators/expressions"),
  statements:          require("./generators/statements"),
  classes:             require("./generators/classes"),
  methods:             require("./generators/methods"),
  modules:             require("./generators/modules"),
  types:               require("./generators/types"),
  base:                require("./generators/base"),
  jsx:                 require("./generators/jsx")
};

_.each(CodeGenerator.generators, function (generator) {
  _.extend(CodeGenerator.prototype, generator);
});
<commit_msg>generator: add intelligent whitespace based on tokens on nodes in a sequence<commit_after>module.exports = function (code, ast, opts) {
  var gen = new CodeGenerator(code, ast, opts);
  return gen.generate();
};

module.exports.CodeGenerator = CodeGenerator;

var sourceMap = require("source-map");
var assert    = require("assert");
var util      = require("./util");
var t         = require("./types");
var _         = require("lodash");

function CodeGenerator(code, ast, opts) {
  opts = opts || {}

  this.tabWidth = 2;
  this.code     = code;
  this.opts     = opts;
  this.ast      = ast;
  this.buf      = "";

  this.line    = 1;
  this.column  = 0;
  this._indent = 0;

  if (opts.sourceMap) {
    this.map = new sourceMap.SourceMapGenerator({
      file: opts.sourceMapName
    });

    this.map.setSourceContent(opts.sourceFileName, code);
  } else {
    this.map = null;
  }
}

CodeGenerator.prototype.mark = function (node, locType) {
  var loc = node.loc;
  if (!loc) return; // no location info

  var map = this.map;
  if (!map) return; // no source map

  map.addMapping({
    source: this.opts.sourceFileName,
    generated: {
      line: this.line,
      column: this.column
    },
    original: loc[locType]
  });
};

CodeGenerator.prototype.newline = function () {
  this.buf = this.buf.replace(/\n(\s+)$/, "\n");
  this.buf += "\n";
  this.line++;
};

CodeGenerator.prototype.semicolon = function () {
  this.buf += ";";
  this.column++;
};

CodeGenerator.prototype.keyword = function (name) {
  this.push(name);
  this.push(" ");
};

CodeGenerator.prototype.push = function (str) {
  if (this._indent) {
    // we have an indent level and we aren't pushing a newline
    var indent = this.getIndent();

    // replace all newlines with newlines with the indentation
    str = str.replace(/\n/g, "\n" + indent);

    // we've got a newline before us so prepend on the indentation
    if (this.isLast("\n")) str = indent + str;
  }

  var self = this;

  _.each(str, function (cha) {
    if (cha === "\n") {
      self.line++;
      self.column = 0;
    } else {
      self.column++;
    }
  });

  this.buf += str;
};

CodeGenerator.prototype.isLast = function (cha) {
  return _.last(this.buf) === cha;
};

CodeGenerator.prototype.getIndent = function () {
  return util.repeat(this._indent * this.tabWidth);
};

CodeGenerator.prototype.indent = function () {
  this._indent++;
};

CodeGenerator.prototype.dedent = function () {
  this._indent--;
};

CodeGenerator.prototype.generate = function () {
  var ast = this.ast;

  this.print(ast);

  var map = this.map;
  if (map) map = map.toJSON();

  return {
    map:  map,
    ast:  ast,
    code: this.buf
  };
};

CodeGenerator.prototype.buildPrint = function (parent) {
  var self = this;

  var print = function (node, opts) {
    return self.print(node, parent, opts);
  };

  print.sequence = function (nodes, opts) {
    return self.printSequence(print, nodes, opts);
  };

  return print;
};

CodeGenerator.prototype.printSequence = function (print, nodes, opts) {
  var comments = this.ast.comments;
  var tokens   = this.ast.tokens;

  var self = this;
  opts = opts || {};

  // calculate the whitespace between two tokens
  var hasWhitespaceBetween = function (startToken, endToken) {
    if (!startToken) return false;

    var whitespace = false;

    var start = startToken.end;
    var end   = endToken.start;

    var sep = self.code.slice(start, end);

    var lines = 0;
    lines--; // take off the current line

    // remove comments
    _.each(comments, function (comment) {
      // this comment is after the last token or befor ethe first
      if (comment.end > end || comment.start < start) return;

      var length = comment.end - comment.start;

      // compute the relative positions of the comment within the sliced node
      // string
      var startRelative = comment.start - start;
      var endRelative = comment.end - start;

      // remove the line this comment ends with
      if (comment.type === "Line") lines--;

      // remove comment
      sep = sep.slice(0, startRelative) + util.repeat(length) + sep.slice(endRelative);
    });

    // check if there was a newline between the two nodes
    lines += _.size(sep.match(/\n/g));
    return lines > 0;
  };

  var needsNewlineBefore = function (node) {
    var startToken;
    var endToken;

    _.each(tokens, function (token, i) {
      // this is the token this node starts with
      if (node.start === token.start) {
        startToken = tokens[i - 1];
        endToken = token;
        return false;
      }
    });

    return hasWhitespaceBetween(startToken, endToken);
  };

  var needsNewlineAfter = function (node) {
    var startToken;
    var endToken;

    _.each(tokens, function (token, i) {
      // this is the token this node ends with
      if (node.end === token.end) {
        startToken = token;
        endToken = tokens[i + 1];
        return false;
      }
    });

    return hasWhitespaceBetween(startToken, endToken);
  };

  opts.print = function (node, i) {
    print(node, node && node.start != null && {
      before: function () {
        if (needsNewlineBefore(node)) self.newline();
      },

      after: function () {
        if (needsNewlineAfter(node)) self.newline();
      }
    });
  };

  return this.printJoin(print, nodes, "\n", opts);
};

CodeGenerator.prototype.print = function (node, parent, opts) {
  if (!node) return "";

  opts = opts || {};

  if (this[node.type]) {
    this.printLeadingComments(node);
    this.mark(node, "start");

    if (opts.before) opts.before();
    var needsParans = t.needsParans(node, parent);
    if (needsParans) this.push("(");
    this[node.type](node, this.buildPrint(node), parent);
    if (needsParans) this.push(")");
    if (opts.after) opts.after();

    this.mark(node, "end");
    this.printTrailingComments(node);
  } else {
    throw new ReferenceError("unknown node " + node.type + " " + JSON.stringify(node));
  }
};

CodeGenerator.prototype.generateComment = function (comment) {
  var val = comment.value;
  if (comment.type === "Line") {
    if (_.last(val) !== "\n") val += "\n";
    return "//" + val;
  } else {
    return "/*" + val + "*/\n";
  }
};

CodeGenerator.prototype.printTrailingComments = function (node) {
  var self = this;
  _.each(node.trailingComments, function (comment) {
    self.push(self.generateComment(comment));
  });
};

CodeGenerator.prototype.printLeadingComments = function (node) {
  var self = this;
  _.each(node.leadingComments, function (comment) {
    self.push(self.generateComment(comment));
  });
};

CodeGenerator.prototype.printJoin = function (print, nodes, sep, opts) {
  opts = opts || {};
  sep  = sep || "\n";

  var self = this;
  var len  = nodes.length;

  if (opts.indent) self.indent();

  _.each(nodes, function (node, i) {
    if (opts.print) {
      opts.print(node, i);
    } else {
      print(node);
    }

    if (opts.iterator) {
      opts.iterator(node, i);
    }

    if (i < len - 1) {
      self.push(sep);
    }
  });

  if (opts.indent) self.dedent();
};

CodeGenerator.generators = {
  arrayComprehensions: require("./generators/array-comprehensions"),
  templateLiterals:    require("./generators/template-literals"),
  expressions:         require("./generators/expressions"),
  statements:          require("./generators/statements"),
  classes:             require("./generators/classes"),
  methods:             require("./generators/methods"),
  modules:             require("./generators/modules"),
  types:               require("./generators/types"),
  base:                require("./generators/base"),
  jsx:                 require("./generators/jsx")
};

_.each(CodeGenerator.generators, function (generator) {
  _.extend(CodeGenerator.prototype, generator);
});
<|endoftext|>


<commit_before>var fs		= require('fs');
var path	= require('path');
var sys		= require('sys');

exports.mounts = function( ){
	var returnObj = Array( );
	var currentMounts	= fs.readFileSync( "/etc/mtab", 'utf8' ).replace( RegExp( '\n$' ), '' ).split( "\n" );
	for( var x=0; x<currentMounts.length; x++ ){
		var currentMountParts	= currentMounts[x].split( " " );
		returnObj[x]		= new Array( );
		returnObj[x].device	= currentMountParts[0];		// This dot is ugly, and could potentially cause problems.
		returnObj[x].mountpoint	= currentMountParts[1].replace( RegExp( '.040' ), ' ' );
		returnObj[x].fs		= currentMountParts[2];
		returnObj[x].options	= currentMountParts[3];
	}

	return returnObj;
}

exports.ps = function( ){
	var returnArray	= Array( );
	try{
		var procContents	= fs.readdirSync( "/proc" );
		for( var x=0; x<procContents.length; x++ ){
			if( parseInt( procContents[x] ) ){
				// procContents[x] is a pid number..
				returnArray.push( getPidDetails( procContents[x] ) );
			}
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.ps.pid	= function( pidToGet ){
	return getPidDetails( pidToGet );
}

function getPidDetails( pidNumber ){
	var returnArray = Array( );
	try{
		var statusLines	= fs.readFileSync( "/proc/" + pidNumber + "/status", 'utf8').split( "\n" );
		for( var x=0; x<statusLines.length; x++ ){
			var tmpSplit		= statusLines[x].split( ":" );
			// This if statement takes care of trailing \n's
			if( tmpSplit.length > 1 ){
				var tmpKey		= tmpSplit[0].toLowerCase( );
				// The status gives more number than we care about, seperated by tabs.. remove them.
				if( tmpKey == 'uid' || tmpKey == 'gid' ){
					returnArray[tmpKey]	= tmpSplit[1].trim().replace( RegExp( "\t.*" ), '' );
				}else{
					returnArray[tmpKey]	= tmpSplit[1].trim( );
				}
			}
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.acpi	= function( ){

}

exports.acpi.batteries = function( ){
	var returnArray	= Array( );
	try{
		var batteries	= fs.readdirSync( "/proc/acpi/battery/", 'utf8' );
		for( var x=0; x<batteries.length; x++ ){
			var batteryName		= batteries[x];
			returnArray[x]		= new Array( );

			var batteryDetails	= getBatteryDetails( batteryName );
			batteryDetails['name']	= batteryName;

			returnArray[x]	= batteryDetails;
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.acpi.battery = function( batteryName ){
	return getBatteryDetails( batteryName );
}

function getBatteryDetails( batteryName ){
	var returnArray	= Array( );
	try{
		var batteryStateLines	= fs.readFileSync( "/proc/acpi/battery/" + batteryName + "/state", 'utf8' ).split( "\n" );
		for( var x=0; x<batteryStateLines.length; x++ ){
			var tmpSplit	= batteryStateLines[x].split( ":" );
			if( tmpSplit.length > 1 ){
				var tmpKey		= tmpSplit[0].replace( RegExp( " " ), "_" ).trim( );
				returnArray[tmpKey]	= tmpSplit[1].trim( );
			}
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.sysctl = function( args ){
	var returnArray	= Array( );
	try{
		return recurseDirReturnObj( "/proc/sys/" );

	}catch( err ){
		console.log( "ERROR: " + err );
		return false;
	}
}

function recurseDirReturnObj( directoryToRecurse ){
	var returnArray	= Array( );
	try{
		var directoryContents	= fs.readdirSync( directoryToRecurse, 'utf8' );
		for( var x=0; x<directoryContents.length; x++ ){
			var tmpStatObj	= fs.lstatSync( path.join( directoryToRecurse, directoryContents[x] ) );
			if( tmpStatObj.isDirectory() ){
				returnArray[directoryContents[x].replace( RegExp( '-', 'g' ), '_' )]	= recurseDirReturnObj( path.join( directoryToRecurse, directoryContents[x] ) );
			}else{
				// Open the file for reading..
				var tmpFileContent	= fs.readFileSync( path.join( directoryToRecurse, directoryContents[x] ), 'utf8' );
				returnArray[directoryContents[x].replace( RegExp( '-', 'g' ), '_' )] = tmpFileContent.replace( RegExp( '\n$', 'g' ), '' );
			}
		}

		return returnArray;
	}catch( err ){
		return false;
	}
}
<commit_msg>Working with function - need to add getter by default..<commit_after>var fs		= require('fs');
var path	= require('path');

exports.mounts = function( ){
	var returnObj = Array( );
	var currentMounts	= fs.readFileSync( "/etc/mtab", 'utf8' ).replace( RegExp( '\n$' ), '' ).split( "\n" );
	for( var x=0; x<currentMounts.length; x++ ){
		var currentMountParts	= currentMounts[x].split( " " );
		returnObj[x]		= new Array( );
		returnObj[x].device	= currentMountParts[0];		// This dot is ugly, and could potentially cause problems.
		returnObj[x].mountpoint	= currentMountParts[1].replace( RegExp( '.040' ), ' ' );
		returnObj[x].fs		= currentMountParts[2];
		returnObj[x].options	= currentMountParts[3];
	}

	return returnObj;
}

exports.ps = function( ){
	var returnArray	= Array( );
	try{
		var procContents	= fs.readdirSync( "/proc" );
		for( var x=0; x<procContents.length; x++ ){
			if( parseInt( procContents[x] ) ){
				// procContents[x] is a pid number..
				returnArray.push( getPidDetails( procContents[x] ) );
			}
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.ps.pid	= function( pidToGet ){
	return getPidDetails( pidToGet );
}

function getPidDetails( pidNumber ){
	var returnArray = Array( );
	try{
		var statusLines	= fs.readFileSync( "/proc/" + pidNumber + "/status", 'utf8').split( "\n" );
		for( var x=0; x<statusLines.length; x++ ){
			var tmpSplit		= statusLines[x].split( ":" );
			// This if statement takes care of trailing \n's
			if( tmpSplit.length > 1 ){
				var tmpKey		= tmpSplit[0].toLowerCase( );
				// The status gives more number than we care about, seperated by tabs.. remove them.
				if( tmpKey == 'uid' || tmpKey == 'gid' ){
					returnArray[tmpKey]	= tmpSplit[1].trim().replace( RegExp( "\t.*" ), '' );
				}else{
					returnArray[tmpKey]	= tmpSplit[1].trim( );
				}
			}
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.acpi	= function( ){

}

exports.acpi.batteries = function( ){
	var returnArray	= Array( );
	try{
		var batteries	= fs.readdirSync( "/proc/acpi/battery/", 'utf8' );
		for( var x=0; x<batteries.length; x++ ){
			var batteryName		= batteries[x];
			returnArray[x]		= new Array( );

			var batteryDetails	= getBatteryDetails( batteryName );
			batteryDetails['name']	= batteryName;

			returnArray[x]	= batteryDetails;
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.acpi.battery = function( batteryName ){
	return getBatteryDetails( batteryName );
}

function getBatteryDetails( batteryName ){
	var returnArray	= Array( );
	try{
		var batteryStateLines	= fs.readFileSync( "/proc/acpi/battery/" + batteryName + "/state", 'utf8' ).split( "\n" );
		for( var x=0; x<batteryStateLines.length; x++ ){
			var tmpSplit	= batteryStateLines[x].split( ":" );
			if( tmpSplit.length > 1 ){
				var tmpKey		= tmpSplit[0].replace( RegExp( " " ), "_" ).trim( );
				returnArray[tmpKey]	= tmpSplit[1].trim( );
			}
		}
	}catch( err ){
		return false;
	}

	return returnArray;
}

exports.sysctl = function( args ){
	var returnArray	= Array( );
	try{
		return recurseDirReturnObj( "/proc/sys/" );

	}catch( err ){
		console.log( "ERROR: " + err );
		return false;
	}
}

function sysctlSet( path, value ){
	console.log( "DEBUG: got path of '" + path + "' and value of '" + value + "'" );
}

function recurseDirReturnObj( directoryToRecurse ){
	var returnArray	= Array( );
	try{
		var directoryContents	= fs.readdirSync( directoryToRecurse, 'utf8' );
		for( var x=0; x<directoryContents.length; x++ ){
			var tmpStatObj	= fs.lstatSync( path.join( directoryToRecurse, directoryContents[x] ) );
			if( tmpStatObj.isDirectory() ){
				returnArray[directoryContents[x].replace( RegExp( '-', 'g' ), '_' )]	= recurseDirReturnObj( path.join( directoryToRecurse, directoryContents[x] ) );
			}else{
				// Open the file for reading..
				var tmpFileContent	= fs.readFileSync( path.join( directoryToRecurse, directoryContents[x] ), 'utf8' );
				returnArray[directoryContents[x].replace( RegExp( '-', 'g' ), '_' )] = function( args ){
					if( !args ){
						return tmpFileContent.replace( RegExp( '\n$', 'g' ), '' );
					}else{
						// Make a call to a setter here..
					}
				};
			}
		}

		return returnArray;
	}catch( err ){
		return false;
	}
}
<|endoftext|>


<commit_before>var css = require('./')
var test = require('tape')
var prefix = require('prefix-style')

test('handles multiple', function (t) {
  var div = document.createElement('div')
  css(div, {
    'background-color': 'blue',
    marginTop: '10px',
    width: 20,
    height: 20,
    position: 'absolute',
    top: 20,
    left: 20,
    zIndex: 45,
    opacity: 0.5,
    'font-smoothing': 'none'
  })

  document.body.appendChild(div)

  var style = window.getComputedStyle(div, null)
  t.equal(style.backgroundColor, 'rgb(0, 0, 255)', 'converts dash to camel case')
  t.equal(style.width, '20px', 'injects px for standard properties')
  t.equal(style.opacity, '0.5', 'avoids px for unitless CSS properties')
  t.equal(style.zIndex, '45', 'avoids px for unitless CSS properties')
  t.equal(style.marginTop, '10px', 'accepts camel case props')

  var prefixed = prefix('fontSmoothing')
  if (prefixed) { // webkit only test
    t.equal(style[prefixed], 'none', 'hanldes prefixing')
  }

  css(div, 'marginTop', 20)
  css(div, 'width', '') // clears a style
  style = window.getComputedStyle(div, null)
  t.equal(style.marginTop, '20px', 'single property version works')
  t.equal(style.width, '0px', 'empty string clears style')

  document.body.removeChild(div)
  t.end()
})

test('transforms', function (t) {
  var div = document.body.appendChild(document.createElement('div'))
  css(div, {
    position: 'absolute',
    top: 0,
    left: 0,
    width: 100,
    display: 'inline-block',
    height: 100,
    background: 'blue',
    padding: 0,
    margin: 0
  })

  // if transforms are supported
  if (prefix('transform')) {
    var width = div.getBoundingClientRect().width
    t.equal(width, 100, 'starts with 100px')

    css(div, 'transform', 'translateZ(10px)')
    width = div.getBoundingClientRect().width
    t.equal(width, 100, 'still 100px after translateZ')

    // apply the 3D effect to parent
    css(document.body, {
      transformStyle: 'preserve-3d',
      perspective: 1000
    })

    css(div, 'transform', 'rotateY(90deg) translateZ(10px)')
    width = div.getBoundingClientRect().width
    t.ok(width < 100, 'shrinks after 3d perspective')
  }

  css(div, 'left', '50%')

  document.body.removeChild(div)
  t.end()
})

test('get / set exports', function (t) {
  var div = document.createElement('div')
  css.set(div, {
    marginTop: 10,
    width: 20
  })

  document.body.appendChild(div)

  t.equal(css.get(div), div.style['foo-barcacha'], 'handles missing props')
  t.equal(css.get(div, undefined), div.style['foo-barcacha'], 'handles missing props')
  t.deepEqual(css.get(div, []), {}, 'handles missing props')

  t.equal(css.get(div, 'width'), '20px', 'single value')
  t.deepEqual(
    css.get(div, ['width', 'marginTop']),
    { width: '20px', marginTop: '10px' },
    'multiple values'
  )

  document.body.removeChild(div)
  t.end()
})

test('string argument', function (t) {
  var div = document.createElement('div')

  css.set(div, `
    margin-top: 10px;
    position: absolute;
  `)

  document.body.appendChild(div)

  var style = window.getComputedStyle(div)
  t.equal(style.marginTop, '10px')
  t.equal(style.position, 'absolute')

  // empty string clears style
  css(div, '')

  style = window.getComputedStyle(div, null)
  t.equal(style.marginTop, '0px', 'single property version works')
  t.equal(style.position, 'static', 'empty string clears style')

  document.body.removeChild(div)
  t.end()
})
<commit_msg>use es5 strings for test<commit_after>var css = require('./')
var test = require('tape')
var prefix = require('prefix-style')

test('handles multiple', function (t) {
  var div = document.createElement('div')
  css(div, {
    'background-color': 'blue',
    marginTop: '10px',
    width: 20,
    height: 20,
    position: 'absolute',
    top: 20,
    left: 20,
    zIndex: 45,
    opacity: 0.5,
    'font-smoothing': 'none'
  })

  document.body.appendChild(div)

  var style = window.getComputedStyle(div, null)
  t.equal(style.backgroundColor, 'rgb(0, 0, 255)', 'converts dash to camel case')
  t.equal(style.width, '20px', 'injects px for standard properties')
  t.equal(style.opacity, '0.5', 'avoids px for unitless CSS properties')
  t.equal(style.zIndex, '45', 'avoids px for unitless CSS properties')
  t.equal(style.marginTop, '10px', 'accepts camel case props')

  var prefixed = prefix('fontSmoothing')
  if (prefixed) { // webkit only test
    t.equal(style[prefixed], 'none', 'hanldes prefixing')
  }

  css(div, 'marginTop', 20)
  css(div, 'width', '') // clears a style
  style = window.getComputedStyle(div, null)
  t.equal(style.marginTop, '20px', 'single property version works')
  t.equal(style.width, '0px', 'empty string clears style')

  document.body.removeChild(div)
  t.end()
})

test('transforms', function (t) {
  var div = document.body.appendChild(document.createElement('div'))
  css(div, {
    position: 'absolute',
    top: 0,
    left: 0,
    width: 100,
    display: 'inline-block',
    height: 100,
    background: 'blue',
    padding: 0,
    margin: 0
  })

  // if transforms are supported
  if (prefix('transform')) {
    var width = div.getBoundingClientRect().width
    t.equal(width, 100, 'starts with 100px')

    css(div, 'transform', 'translateZ(10px)')
    width = div.getBoundingClientRect().width
    t.equal(width, 100, 'still 100px after translateZ')

    // apply the 3D effect to parent
    css(document.body, {
      transformStyle: 'preserve-3d',
      perspective: 1000
    })

    css(div, 'transform', 'rotateY(90deg) translateZ(10px)')
    width = div.getBoundingClientRect().width
    t.ok(width < 100, 'shrinks after 3d perspective')
  }

  css(div, 'left', '50%')

  document.body.removeChild(div)
  t.end()
})

test('get / set exports', function (t) {
  var div = document.createElement('div')
  css.set(div, {
    marginTop: 10,
    width: 20
  })

  document.body.appendChild(div)

  t.equal(css.get(div), div.style['foo-barcacha'], 'handles missing props')
  t.equal(css.get(div, undefined), div.style['foo-barcacha'], 'handles missing props')
  t.deepEqual(css.get(div, []), {}, 'handles missing props')

  t.equal(css.get(div, 'width'), '20px', 'single value')
  t.deepEqual(
    css.get(div, ['width', 'marginTop']),
    { width: '20px', marginTop: '10px' },
    'multiple values'
  )

  document.body.removeChild(div)
  t.end()
})

test('string argument', function (t) {
  var div = document.createElement('div')

  // in new versions of Node/Browser this might be
  // a template string :)
  css.set(div, [
    'margin-top: 10px;',
    'position: absolute;'
  ].join('\n'))

  document.body.appendChild(div)

  var style = window.getComputedStyle(div)
  t.equal(style.marginTop, '10px')
  t.equal(style.position, 'absolute')

  // empty string clears style
  css(div, '')

  style = window.getComputedStyle(div, null)
  t.equal(style.marginTop, '0px', 'single property version works')
  t.equal(style.position, 'static', 'empty string clears style')

  document.body.removeChild(div)
  t.end()
})
<|endoftext|>


<commit_before>var test = require('tape');
var sample = require('./');
var featureCollection = require('turf-featurecollection');
var point = require('turf-point');

test('remove', function(t){
  var points = featureCollection(
    [point(1,2, {team: 'Red Sox'}),
    point(2,1, {team: 'Yankees'}),
    point(3,1, {team: 'Nationals'}),
    point(2,2, {team: 'Yankees'}),
    point(2,3, {team: 'Red Sox'}),
    point(4,2, {team: 'Yankees'})]);

  newFC = sample(points, 4);

  t.equal(newFC.features.length, 4, 'should sample 4 features');
  t.end();
});<commit_msg>Fix test<commit_after>var test = require('tape');
var sample = require('./');
var featureCollection = require('turf-featurecollection');
var point = require('turf-point');

test('remove', function(t){
  var points = featureCollection(
    [point([1,2], {team: 'Red Sox'}),
    point([2,1], {team: 'Yankees'}),
    point([3,1], {team: 'Nationals'}),
    point([2,2], {team: 'Yankees'}),
    point([2,3], {team: 'Red Sox'}),
    point([4,2], {team: 'Yankees'})]);

  newFC = sample(points, 4);

  t.equal(newFC.features.length, 4, 'should sample 4 features');
  t.end();
});
<|endoftext|>


<commit_before>/*
WHAT: Test and then benchmark
USAGE: Run this file in node

HOW TO WRITE TESTS:
      target         ...matches...               after null must not match
test('APPLES',      'app', 'l', 'E',               null,     'xxx')
               matches must not get better
*/

setTimeout(async function() {
  await tests()

  if(assert.count==0) console.log('testing disabled!')
  else if(!assert.failed) console.log('all tests passed')

  if(isNode) bench() // Only bench on node. Don't want the demo to freeze
})

async function tests() {
  test('APPLES', 'app', 'l', 'E')
  test('C:/users/farzher/dropbox/someotherfolder/pocket rumble refactor/Run.bat', 'po', 'p', 'po ru', 'pr', 'prrun', 'ocket umble')
  test('123abc', '12', '1', 'a', null, 'cc')

  test('Thoug ht', 'ht', 'hh')

  test('az bx cyy y', 'az', 'ab', 'ay', 'ax', 'ayy')
  testSimple('aab x', 'ab') // this could cause a to get pushed forward then strict match ab in the middle
  testSimple('sax saxax', 'sx') // this is caused if isConsec gets messedup
  testSimple('aabb b', 'abb') // this is cause if isConsec gets messedup
  testSimple('aabb b b b', 'abbbb')

  // typos
  testStrict('abc', 'acb')
  testStrict('abcefg', 'acbefg')
  testStrict('a ac acb', 'abc')
  testStrict('MeshRendering.h', 'mrnederh')
  testStrict('MMommOMMommO', 'moom')
  testNomatch('AndroidRuntimeSettings.h', 'nothing')
  testNomatch('atsta', 'atast')

  test('noodle monster', 'nomon', null, 'qrs')
  test('noodle monster '.repeat(100), null, 'a')

  // typoPenalty
  assert(fuzzysort.single('acb', 'abc').score===20, 'typoPenalty strict')
  assert(fuzzysort.single('acb', 'axbxc').score===6022, 'typoPenalty simple')

  var tmp = fuzzysort.go('a', ['ba', 'bA', 'a', 'bA', 'xx', 'ba'])
  assert(tmp[0].score===0, 'go sorting')
  assert(tmp.length===5, 'go sorting length')
  assert(tmp.total===5, 'go sorting total')

  var tmp = await fuzzysort.goAsync('a', ['ba', 'bA', 'a', 'bA', 'xx', 'ba'])
  assert(tmp[0].score===0, 'goAsync sorting')
  assert(tmp.length===5, 'goAsync sorting length')
  assert(tmp.total===5, 'goAsync sorting total')
}

const isNode = typeof require !== 'undefined' && typeof window === 'undefined'
if(isNode) fuzzysort = require('./fuzzysort')

// Config
  // fuzzysort.highlightMatches = false
  // fuzzysort.noMatchLimit = 100000
  fuzzysort.noMatchLimit = 50
  fuzzysort.limit = 100
  // fuzzysort.allowTypo = false
  // fuzzysort.threshold = 999
  // fuzzysort.searchIsLower = true
  const benchmark_duration = 2

if(isNode) testdata = require('./testdata')
var testdata_rawstring = testdata; testdata = {}
for(var key of Object.keys(testdata_rawstring)) {
  testdata[key] = new Array(testdata_rawstring[key].length)
  for(var i = testdata_rawstring[key].length-1; i>=0; i-=1) {
    testdata[key][i] = fuzzysort.prepare(testdata_rawstring[key][i])
    // testdata[key][i] = testdata_rawstring[key][i]
  }
}

function bench() {
  if(isNode) Benchmark = require('benchmark')
  Benchmark.options.maxTime = benchmark_duration
  const suite = new Benchmark.Suite

  suite.add('go prepared', function() {
    fuzzysort.go('nnnne', testdata.ue4_filenames)
    fuzzysort.go('e', testdata.ue4_filenames)
    fuzzysort.go('mrender.h', testdata.ue4_filenames)
  })
  suite.add('go str', function() {
    fuzzysort.go('nnnne', testdata_rawstring.ue4_filenames)
    fuzzysort.go('e', testdata_rawstring.ue4_filenames)
    fuzzysort.go('mrender.h', testdata_rawstring.ue4_filenames)
  })

  // suite.add('goKey', function() {
  //   fuzzysort.go('e', objects, {key:'target'})
  //   fuzzysort.go('a', objects, {key:'target'})
  //   fuzzysort.go('mrender.h', objects, {key:'target'})

  //   // objs = [{str:'naytunfwuyt', str2:'nautfn'}, {str:'pant', str2:'tunntuftf889323'}, {str:'tame', str2:'n&*(*&o'}]
  //   // fuzzysort.go('t', objs, {keys:['str', 'str2'], scoreFn:metas=> (metas[0]&&metas[0].score||1000) + (metas[1]&&metas[1].score||1000) })
  // })

  // suite.add('goKeys', function() {
  //   fuzzysort.go('e', objects, {key:['target']})
  //   fuzzysort.go('a', objects, {key:['target']})
  //   fuzzysort.go('mrender.h', objects, {key:['target']})

  //   // objs = [{str:'naytunfwuyt', str2:'nautfn'}, {str:'pant', str2:'tunntuftf889323'}, {str:'tame', str2:'n&*(*&o'}]
  //   // fuzzysort.go('t', objs, {keys:['str', 'str2'], scoreFn:metas=> (metas[0]&&metas[0].score||1000) + (metas[1]&&metas[1].score||1000) })
  // })

  suite.add('goAsync', function(deferred) {
    var count = 0
    fuzzysort.goAsync('e', testdata.ue4_filenames).then(()=>{count+=1; if(count===3)deferred.resolve()})
    fuzzysort.goAsync('a', testdata.ue4_filenames).then(()=>{count+=1; if(count===3)deferred.resolve()})
    fuzzysort.goAsync('mrender.h', testdata.ue4_filenames).then(()=>{count+=1; if(count===3)deferred.resolve()})
  }, {defer:true})

  // suite.add('goAsync.cancel()', function(deferred) {
  //   const p = fuzzysort.goAsync('e', testdata.ue4_filenames)
  //   p.then(()=>{deferred.resolve()}, ()=>{deferred.resolve()})
  //   p.cancel()
  // }, {defer:true})

  suite.add('huge nomatch', function() {
    fuzzysort.single('xxx', 'noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster')
  })

  suite.add('tricky', function() {
    fuzzysort.single('prrun', 'C:/users/farzher/dropbox/someotherfolder/pocket rumble refactor/Run.bat')
  })

  suite.add('small', function() {
    fuzzysort.single('al', 'alexstrasa')
  })

  suite.add('somematch', function() {
    fuzzysort.single('texxx', 'template/index')
  })

  suite.on('cycle', function(e) {
    console.log(String(e.target))
  })

  console.log('now benching')
  suite.run()
}

// helper function nonsense
function assert(b, m=undefined) {
  if(!b) {
  console.log(assert.count, 'ASSERTION FAILED!!!!!!!', m)
  assert.failed = true
  } else {
  // console.log(assert.count, 'test passed')
  }

  assert.count += 1
}
assert.count = 0

function test(target, ...searches) {
  var last_score = -1
  var needs_to_fail = false
  for (var i = 0; i < searches.length; i++) {

    var search = searches[i]
    if(search === null) {
      needs_to_fail = true
      continue
    }

    const result = fuzzysort.single(searches[i], target)
    assertResultIntegrity(result)
    var score = undefined
    if(result) score = result.score

    var info = {score, last_score, target, search}
    if(needs_to_fail) {
      assert(score===undefined, info)
    } else {
      assert(score!==undefined, info)
      assert(score>=last_score, info)
      last_score = score
    }
  }
}
function testStrict(target, ...searches) {
  for(const search of searches) {
    const result = fuzzysort.single(search, target)
    assert(result && result.score<1000, {search, result})
    assert(result && result.indexes.length === search.length)
    assertResultIntegrity(result)
  }
}
function testSimple(target, ...searches) {
  for(const search of searches) {
    const result = fuzzysort.single(search, target)
    assert(result && result.score>=1000, {search, result})
    assert(result && result.indexes.length === search.length)
    assertResultIntegrity(result)
  }
}
function testNomatch(target, ...searches) {
  for(const search of searches) {
    const result = fuzzysort.single(search, target)
    assert(result===null, {search, result})
  }
}
function assertResultIntegrity(result) {
  if(result === null) return true
  if(result.indexes) {
    var lastMatchI = null
    for(const matchI of result.indexes) {
      if(lastMatchI === null) {
        lastMatchI = matchI
      } else {
        if(lastMatchI >= matchI) {
          assert(false, result)
          return false
        }
        lastMatchI = matchI
      }
    }
  }
}

// function randomString(len, charSet) {
//     charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ,./\]["<>?:{}!@#$%^&*()_+=-';
//     var randomString = '';
//     for (var i = 0; i < len; i++) {
//         var randomPoz = Math.floor(seededRand() * charSet.length);
//         randomString += charSet.substring(randomPoz,randomPoz+1);
//     }
//     return randomString;
// }

// function seededRand(max=1, min=0) {
//   if(min) [max,min]=[min,max]
//   seededRand.seed = (seededRand.seed * 9301 + 49297) % 233280
//   var rnd = seededRand.seed / 233280
//   return min + rnd * (max - min)
// }
// seededRand.seed = 0
<commit_msg>tests<commit_after>// fuzzysort = require('./fuzzysort')
// Benchmark = require('benchmark')
// Benchmark.options.maxTime = 2
// const suite = new Benchmark.Suite
// Things = [1,2323,231,3123,131,313,124,124124,1421,2]
// function doit(x) { return x+1 }
// suite.add('go prepared', function() {
//   sum=0
//   for (var i = Things.length - 1; i >= 0; i--) {
//     sum+=Things[i]+Things[i]+Things[i]+Things[i]
//   }
//   return sum
// })
// suite.add('go prepared', function() {
//   sum=0
//   for (var i = Things.length - 1; i >= 0; i--) {
//     var thing = Things[i]
//     sum+=thing+thing+thing+thing
//   }
//   return sum
// })

// suite.on('cycle', function(e) {
//   console.log(String(e.target))
// })

// console.log('now benching')
// suite.run()
// process.exit()

/*
WHAT: Test and then benchmark
USAGE: Run this file in node

HOW TO WRITE TESTS:
      target         ...matches...               after null must not match
test('APPLES',      'app', 'l', 'E',               null,     'xxx')
               matches must not get better
*/

setTimeout(async function() {
  await tests()

  if(assert.count==0) console.log('testing disabled!')
  else if(!assert.failed) console.log('all tests passed')

  if(isNode) bench() // Only bench on node. Don't want the demo to freeze
})

async function tests() {
  test('APPLES', 'app', 'l', 'E')
  test('C:/users/farzher/dropbox/someotherfolder/pocket rumble refactor/Run.bat', 'po', 'p', 'po ru', 'pr', 'prrun', 'ocket umble')
  test('123abc', '12', '1', 'a', null, 'cc')

  test('Thoug ht', 'ht', 'hh')

  test('az bx cyy y', 'az', 'ab', 'ay', 'ax', 'ayy')
  testSimple('aab x', 'ab') // this could cause a to get pushed forward then strict match ab in the middle
  testSimple('sax saxax', 'sx') // this is caused if isConsec gets messedup
  testSimple('aabb b', 'abb') // this is cause if isConsec gets messedup
  testSimple('aabb b b b', 'abbbb')

  // typos
  testStrict('abc', 'acb')
  testStrict('abcefg', 'acbefg')
  testStrict('a ac acb', 'abc')
  testStrict('MeshRendering.h', 'mrnederh')
  testStrict('MMommOMMommO', 'moom')
  testNomatch('AndroidRuntimeSettings.h', 'nothing')
  testNomatch('atsta', 'atast')

  test('noodle monster', 'nomon', null, 'qrs')
  test('noodle monster '.repeat(100), null, 'a')

  // typoPenalty
  assert(fuzzysort.single('acb', 'abc').score===20, 'typoPenalty strict')
  assert(fuzzysort.single('acb', 'axbxc').score===6022, 'typoPenalty simple')

  var tmp = fuzzysort.go('a', ['ba', 'bA', 'a', 'bA', 'xx', 'ba'])
  assert(tmp[0].score===0, 'go sorting')
  assert(tmp.length===5, 'go sorting length')
  assert(tmp.total===5, 'go sorting total')

  var tmp = await fuzzysort.goAsync('a', ['ba', 'bA', 'a', 'bA', 'xx', 'ba'])
  assert(tmp[0].score===0, 'goAsync sorting')
  assert(tmp.length===5, 'goAsync sorting length')
  assert(tmp.total===5, 'goAsync sorting total')
}

const isNode = typeof require !== 'undefined' && typeof window === 'undefined'
if(isNode) fuzzysort = require('./fuzzysort')

// Config
  // fuzzysort.highlightMatches = false
  // fuzzysort.noMatchLimit = 100000
  fuzzysort.noMatchLimit = 50
  fuzzysort.limit = 100
  // fuzzysort.allowTypo = false
  // fuzzysort.threshold = 999
  // fuzzysort.searchIsLower = true
  const benchmark_duration = 2

if(isNode) testdata = require('./testdata')
var testdata_rawstring = testdata; testdata = {}
for(var key of Object.keys(testdata_rawstring)) {
  testdata[key] = new Array(testdata_rawstring[key].length)
  for(var i = testdata_rawstring[key].length-1; i>=0; i-=1) {
    testdata[key][i] = fuzzysort.prepare(testdata_rawstring[key][i])
    // testdata[key][i] = testdata_rawstring[key][i]
  }
}

function bench() {
  if(isNode) Benchmark = require('benchmark')
  Benchmark.options.maxTime = benchmark_duration
  const suite = new Benchmark.Suite

  suite.add('go prepared', function() {
    fuzzysort.go('nnnne', testdata.ue4_filenames)
    fuzzysort.go('e', testdata.ue4_filenames)
    fuzzysort.go('mrender.h', testdata.ue4_filenames)
  })
  suite.add('go str', function() {
    fuzzysort.go('nnnne', testdata_rawstring.ue4_filenames)
    fuzzysort.go('e', testdata_rawstring.ue4_filenames)
    fuzzysort.go('mrender.h', testdata_rawstring.ue4_filenames)
  })

  // suite.add('goKey', function() {
  //   fuzzysort.go('e', objects, {key:'target'})
  //   fuzzysort.go('a', objects, {key:'target'})
  //   fuzzysort.go('mrender.h', objects, {key:'target'})

  //   // objs = [{str:'naytunfwuyt', str2:'nautfn'}, {str:'pant', str2:'tunntuftf889323'}, {str:'tame', str2:'n&*(*&o'}]
  //   // fuzzysort.go('t', objs, {keys:['str', 'str2'], scoreFn:metas=> (metas[0]&&metas[0].score||1000) + (metas[1]&&metas[1].score||1000) })
  // })

  // suite.add('goKeys', function() {
  //   fuzzysort.go('e', objects, {key:['target']})
  //   fuzzysort.go('a', objects, {key:['target']})
  //   fuzzysort.go('mrender.h', objects, {key:['target']})

  //   // objs = [{str:'naytunfwuyt', str2:'nautfn'}, {str:'pant', str2:'tunntuftf889323'}, {str:'tame', str2:'n&*(*&o'}]
  //   // fuzzysort.go('t', objs, {keys:['str', 'str2'], scoreFn:metas=> (metas[0]&&metas[0].score||1000) + (metas[1]&&metas[1].score||1000) })
  // })

  suite.add('goAsync', function(deferred) {
    var count = 0
    fuzzysort.goAsync('e', testdata.ue4_filenames).then(()=>{count+=1; if(count===3)deferred.resolve()})
    fuzzysort.goAsync('a', testdata.ue4_filenames).then(()=>{count+=1; if(count===3)deferred.resolve()})
    fuzzysort.goAsync('mrender.h', testdata.ue4_filenames).then(()=>{count+=1; if(count===3)deferred.resolve()})
  }, {defer:true})

  // suite.add('goAsync.cancel()', function(deferred) {
  //   const p = fuzzysort.goAsync('e', testdata.ue4_filenames)
  //   p.then(()=>{deferred.resolve()}, ()=>{deferred.resolve()})
  //   p.cancel()
  // }, {defer:true})

  suite.add('huge nomatch', function() {
    fuzzysort.single('xxx', 'noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster noodle monster')
  })

  suite.add('tricky', function() {
    fuzzysort.single('prrun', 'C:/users/farzher/dropbox/someotherfolder/pocket rumble refactor/Run.bat')
  })

  suite.add('small', function() {
    fuzzysort.single('al', 'alexstrasa')
  })

  suite.add('somematch', function() {
    fuzzysort.single('texxx', 'template/index')
  })

  suite.on('cycle', function(e) {
    console.log(String(e.target))
  })

  console.log('now benching')
  suite.run()
}

// helper function nonsense
function assert(b, m=undefined) {
  if(!b) {
  console.log(assert.count, 'ASSERTION FAILED!!!!!!!', m)
  assert.failed = true
  } else {
  // console.log(assert.count, 'test passed')
  }

  assert.count += 1
}
assert.count = 0

function test(target, ...searches) {
  var last_score = -1
  var needs_to_fail = false
  for (var i = 0; i < searches.length; i++) {

    var search = searches[i]
    if(search === null) {
      needs_to_fail = true
      continue
    }

    const result = fuzzysort.single(searches[i], target)
    assertResultIntegrity(result)
    var score = undefined
    if(result) score = result.score

    var info = {score, last_score, target, search}
    if(needs_to_fail) {
      assert(score===undefined, info)
    } else {
      assert(score!==undefined, info)
      assert(score>=last_score, info)
      last_score = score
    }
  }
}
function testStrict(target, ...searches) {
  for(const search of searches) {
    const result = fuzzysort.single(search, target)
    assert(result && result.score<1000, {search, result})
    assert(result && result.indexes.length === search.length)
    assertResultIntegrity(result)
  }
}
function testSimple(target, ...searches) {
  for(const search of searches) {
    const result = fuzzysort.single(search, target)
    assert(result && result.score>=1000, {search, result})
    assert(result && result.indexes.length === search.length)
    assertResultIntegrity(result)
  }
}
function testNomatch(target, ...searches) {
  for(const search of searches) {
    const result = fuzzysort.single(search, target)
    assert(result===null, {search, result})
  }
}
function assertResultIntegrity(result) {
  if(result === null) return true
  if(result.indexes) {
    var lastMatchI = null
    for(const matchI of result.indexes) {
      if(lastMatchI === null) {
        lastMatchI = matchI
      } else {
        if(lastMatchI >= matchI) {
          assert(false, result)
          return false
        }
        lastMatchI = matchI
      }
    }
  }
}

// function randomString(len, charSet) {
//     charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ,./\]["<>?:{}!@#$%^&*()_+=-';
//     var randomString = '';
//     for (var i = 0; i < len; i++) {
//         var randomPoz = Math.floor(seededRand() * charSet.length);
//         randomString += charSet.substring(randomPoz,randomPoz+1);
//     }
//     return randomString;
// }

// function seededRand(max=1, min=0) {
//   if(min) [max,min]=[min,max]
//   seededRand.seed = (seededRand.seed * 9301 + 49297) % 233280
//   var rnd = seededRand.seed / 233280
//   return min + rnd * (max - min)
// }
// seededRand.seed = 0
<|endoftext|>


<commit_before>// @ts-check

"use strict";

const { addErrorContext, isBlankLine } = require("../helpers");
const { flattenedLists } = require("./cache");

const quotePrefixRe = /^[>\s]*/;

module.exports = {
  "names": [ "MD032", "blanks-around-lists" ],
  "description": "Lists should be surrounded by blank lines",
  "tags": [ "bullet", "ul", "ol", "blank_lines" ],
  "function": function MD032(params, onError) {
    const { lines } = params;
    flattenedLists().filter((list) => !list.nesting).forEach((list) => {
      const firstIndex = list.open.map[0];
      if (!isBlankLine(lines[firstIndex - 1])) {
        const line = lines[firstIndex];
        const quotePrefix = line.match(quotePrefixRe)[0].trimEnd();
        addErrorContext(
          onError,
          firstIndex + 1,
          line.trim(),
          null,
          null,
          null,
          {
            "insertText": `${quotePrefix}\n`
          });
      }
      const lastIndex = list.lastLineIndex - 1;
      if (!isBlankLine(lines[lastIndex + 1])) {
        const line = lines[lastIndex];
        const quotePrefix = line.match(quotePrefixRe)[0].trimEnd();
        addErrorContext(
          onError,
          lastIndex + 1,
          line.trim(),
          null,
          null,
          null,
          {
            "lineNumber": lastIndex + 2,
            "insertText": `${quotePrefix}\n`
          });
      }
    });
  }
};
<commit_msg>Replace string.trimEnd with string.trimRight for Node 8.<commit_after>// @ts-check

"use strict";

const { addErrorContext, isBlankLine } = require("../helpers");
const { flattenedLists } = require("./cache");

const quotePrefixRe = /^[>\s]*/;

module.exports = {
  "names": [ "MD032", "blanks-around-lists" ],
  "description": "Lists should be surrounded by blank lines",
  "tags": [ "bullet", "ul", "ol", "blank_lines" ],
  "function": function MD032(params, onError) {
    const { lines } = params;
    flattenedLists().filter((list) => !list.nesting).forEach((list) => {
      const firstIndex = list.open.map[0];
      if (!isBlankLine(lines[firstIndex - 1])) {
        const line = lines[firstIndex];
        const quotePrefix = line.match(quotePrefixRe)[0].trimRight();
        addErrorContext(
          onError,
          firstIndex + 1,
          line.trim(),
          null,
          null,
          null,
          {
            "insertText": `${quotePrefix}\n`
          });
      }
      const lastIndex = list.lastLineIndex - 1;
      if (!isBlankLine(lines[lastIndex + 1])) {
        const line = lines[lastIndex];
        const quotePrefix = line.match(quotePrefixRe)[0].trimRight();
        addErrorContext(
          onError,
          lastIndex + 1,
          line.trim(),
          null,
          null,
          null,
          {
            "lineNumber": lastIndex + 2,
            "insertText": `${quotePrefix}\n`
          });
      }
    });
  }
};
<|endoftext|>


<commit_before>if (!Function.prototype.bind) { // credit to Crockford for this bind function
    Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function () {},
            fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                    aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound; // NYC
    };
}

var TicTacToe = function() { // current function constructor
    this.init();
};
// this is the prototype obect associated with the above function constructor
TicTacToe.prototype = { // give all instances of TicTacToe class the following methods and values
    // every object linked to the prototype object which they inherit properties from
    // the prototype object is where inherited methods and values are deposited
    boardElem: null, // empty elements by setting them to null
    resetElem: null,
    resultElem: null,
    statusElem: null,
    xTurn: true,
    gameOver: false,
    moves: 0,
    boardArr: [],
    winCombo: [

        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]

    ],

    init: function() { // first function associated with the prototype
        // bind UI
        this.resetElem = document.getElementById("reset");
        this.boardElem = document.getElementById("game-board");
        this.resultElem = document.getElementById("results");
        this.statusElem = document.getElementById("status");
        this.resetGame();
        // current binded events on clicking resetGame and gameboard
        this.resetElem.onclick = function() {
            this.resetGame();
        }.bind(this); // this now bounded to the this parameter of the outer function
        // (bind() instead of writing var that = this
        this.boardElem.onclick = function(e) { // current click event handler (e is the event object passed as an arg)
            e = e || event; // event sometimes available through the global variable event (for IE)
            var source = e.boardElem || e.target; // event target is the object which
            // the event is associated
            this.updateGame(source.getAttribute("data-position")); // events bubble up the DOM Tree
            this.updateUI(source.getAttribute("data-position"));
        }.bind(this); // this now bounded to the this parameter of the outer function
    },

    resetGame: function() {
        for (var i = 0; i <= 8; i += 1) {
            this.boardArr[i] = null; // initialise all square values with null
        }
        this.moves = 0;
        this.gameOver = false;
        this.xTurn = true; // X is first player
    },

    checkForWinningMove: function() { // check all 8 winning combinations
        // check 3 rows, 3 columns and 2 diagonals
        for (var i = 0; i < this.winCombo.length; i += 1) {
            if (this.boardArr[this.winCombo[i][0]] === this.boardArr[this.winCombo[i][1]] && this.boardArr[this.winCombo[i][1]]
                === this.boardArr[this.winCombo[i][2]] && this.boardArr[this.winCombo[i][0]] !== null) {
                this.gameOver = true;
                return true;
            }
        }
    },

    updateUI: function(position) {
        var i, square = document.querySelectorAll("input[type='button']"); // returns an array of all buttons clicked
        for (i = 0; i < square.length; i += 1) {
            square[i].value = this.boardArr[position];
        }
    },

    // Updates the model
    updateGame: function(position) {
        var square;
        if (this.boardArr[position] === null && this.gameOver !== true) { // check board is empty and game is not over
            this.moves += 1; // increment game moves
            this.boardArr[position] = this.xTurn ? "X" : "O"; // current move
            this.xTurn = !this.xTurn; // current game turn
            this.updateUI();
            this.statusElem.innerHTML = "It is the turn of " + (this.xTurn ? "X" : "O"); // current game status
        }
        var outcome = this.checkForWinningMove(); // check if there is a winning move
        if (outcome === true) { // decide who won
            if (this.xTurn === false) { // when X wins, this.Xturn will be false
                alert("X wins");
                this.resetGame();
            } else {
                alert("O wins");
                this.resetGame();
            }
        }
    }
};

var playGame = new TicTacToe();
// Update UI (do it at home)
// AI - naive player (randomly)n
// AI
// naive computer player
// two in a row - fork try & win
// encode strategies from wiki
// advanced AI

<commit_msg>updateUI second<commit_after>if (!Function.prototype.bind) { // credit to Crockford for this bind function
    Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function () {},
            fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                    aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound; // NYC
    };
}

var TicTacToe = function() { // current function constructor
    this.init();
};
// this is the prototype obect associated with the above function constructor
TicTacToe.prototype = { // give all instances of TicTacToe class the following methods and values
    // every object linked to the prototype object which they inherit properties from
    // the prototype object is where inherited methods and values are deposited
    boardElem: null, // empty elements by setting them to null
    resetElem: null,
    resultElem: null,
    statusElem: null,
    xTurn: true,
    gameOver: false,
    moves: 0,
    boardArr: [],
    winCombo: [

        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]

    ],

    init: function() { // first function associated with the prototype
        // bind UI
        this.resetElem = document.getElementById("reset");
        this.boardElem = document.getElementById("game-board");
        this.resultElem = document.getElementById("results");
        this.statusElem = document.getElementById("status");
        this.resetGame();
        // current binded events on clicking resetGame and gameboard
        this.resetElem.onclick = function() {
            this.resetGame();
        }.bind(this); // this now bounded to the this parameter of the outer function
        // (bind() instead of writing var that = this
        this.boardElem.onclick = function(e) { // current click event handler (e is the event object passed as an arg)
            e = e || event; // event sometimes available through the global variable event (for IE)
            var source = e.boardElem || e.target; // event target is the object which
            // the event is associated
            this.updateGame(source.getAttribute("data-position")); // events bubble up the DOM Tree
            this.updateUI(source.getAttribute("data-position"), source);
        }.bind(this); // this now bounded to the this parameter of the outer function
    },

    resetGame: function() {
        for (var i = 0; i <= 8; i += 1) {
            this.boardArr[i] = null; // initialise all square values with null
        }
        this.moves = 0;
        this.gameOver = false;
        this.xTurn = true; // X is first player
    },

    checkForWinningMove: function() { // check all 8 winning combinations
        // check 3 rows, 3 columns and 2 diagonals
        for (var i = 0; i < this.winCombo.length; i += 1) {
            if (this.boardArr[this.winCombo[i][0]] === this.boardArr[this.winCombo[i][1]] && this.boardArr[this.winCombo[i][1]]
                === this.boardArr[this.winCombo[i][2]] && this.boardArr[this.winCombo[i][0]] !== null) {
                this.gameOver = true;
                return true;
            }
        }
    },

    updateUI: function(position, element) {
        var square = input.value;
        square = this.boardArr[position];
    },

    // Updates the model
    updateGame: function(position) {
        var square;
        if (this.boardArr[position] === null && this.gameOver !== true) { // check board is empty and game is not over
            this.moves += 1; // increment game moves
            this.boardArr[position] = this.xTurn ? "X" : "O"; // current move
            this.xTurn = !this.xTurn; // current game turn
            this.updateUI();
            this.statusElem.innerHTML = "It is the turn of " + (this.xTurn ? "X" : "O"); // current game status
        }
        var outcome = this.checkForWinningMove(); // check if there is a winning move
        if (outcome === true) { // decide who won
            if (this.xTurn === false) { // when X wins, this.Xturn will be false
                alert("X wins");
                this.resetGame();
            } else {
                alert("O wins");
                this.resetGame();
            }
        }
    }
};

var playGame = new TicTacToe();
// AI - naive player (randomly)n
// naive computer player
// two in a row - fork try & win
// encode strategies from wiki
// advanced AI

<|endoftext|>


<commit_before>var expect = require('chai').expect;
var SortedList = require('./');

describe('sorted-list', function(){
    var rawdata = [10, 5, 22, 2, -2, 0, 11, -1, 7, 2, 8, -3];

    it('validate order of the inserted elements', function(){
        var sorted = new SortedList();
        rawdata.forEach(function(d){sorted.insert(d);});

        expect(sorted.toArray()).to.eql([-3, -2, -1, 0, 2, 2, 5, 7, 8, 10, 11, 22]);
    });

    it('validate multiple instances of sorted list with different comparer', function(){
        var sorted = new SortedList();
        rawdata.forEach(function(d){sorted.insert(d);});

        var sorted2 = new SortedList(function(a,b){return a.key-b.key;});
        sorted2.insert({key: 10});
        sorted2.insert({key: 5});
        sorted2.insert({key: 22});
        sorted2.insert({key: 2});
        sorted2.insert({key: -2});
        sorted2.insert({key: 0});

        var sortedArray2 = sorted2.toArray().map(function(d){return d.key;});
        expect(sortedArray2).to.eql([-2, 0, 2, 5, 10, 22]);
    });

    it('validate length property counts correctly.', function(){
        var sorted = new SortedList();
        rawdata.forEach(function(d){sorted.insert(d);});

        expect(sorted.length).to.equal(rawdata.length);
    });

    var randomSize = 1000;
    it('validate '+randomSize+' random numbers.', function(){
        var raws = [];
        var sorted = new SortedList();

        for(var i = 0; i< randomSize; i++){
            var v = Math.random();
            raws.push(v);
            sorted.insert(v);
        }

        raws.sort();

        expect(sorted.toArray()).to.eql(raws);
    });

    it('validate cut function', function(){
        var sorted = new SortedList();
        sorted.insertBatch(rawdata);
        //sorted.print();

        var removed = sorted.cut(-1, 'left', true);
        expect(removed).to.eql([-3, -2, -1]);
        expect(sorted.toArray()).to.eql([0, 2, 2, 5, 7, 8, 10, 11, 22]);

        removed = sorted.cut(2, 'left', false);
        expect(removed).to.eql([0]);
        expect(sorted.toArray()).to.eql([2, 2, 5, 7, 8, 10, 11, 22]);

        removed = sorted.cut(2, 'left', true);
        expect(removed).to.eql([2,2]);
        expect(sorted.toArray()).to.eql([5, 7, 8, 10, 11, 22]);

        removed = sorted.cut(6, 'right', false);
        expect(removed).to.eql([7, 8, 10, 11, 22]);
        expect(sorted.toArray()).to.eql([5]);

        removed = sorted.cut(4, 'right', false);
        expect(removed).to.eql([5]);
        expect(sorted.toArray()).to.eql([]);
    });

});

<commit_msg>Output elapsed time in some tests and fixed a bug.<commit_after>var expect = require('chai').expect;
var SortedList = require('./');

describe('sorted-list', function(){
    var rawdata = [10, 5, 22, 2, -2, 0, 11, -1, 7, 2, 8, -3];

    it('validate order of the inserted elements', function(){
        var sorted = new SortedList();
        rawdata.forEach(function(d){sorted.insert(d);});

        expect(sorted.toArray()).to.eql([-3, -2, -1, 0, 2, 2, 5, 7, 8, 10, 11, 22]);
    });

    it('validate multiple instances of sorted list with different comparer', function(){
        var sorted = new SortedList();
        rawdata.forEach(function(d){sorted.insert(d);});

        var sorted2 = new SortedList(function(a,b){return a.key-b.key;});
        sorted2.insert({key: 10});
        sorted2.insert({key: 5});
        sorted2.insert({key: 22});
        sorted2.insert({key: 2});
        sorted2.insert({key: -2});
        sorted2.insert({key: 0});

        var sortedArray2 = sorted2.toArray().map(function(d){return d.key;});
        expect(sortedArray2).to.eql([-2, 0, 2, 5, 10, 22]);
    });

    it('validate length property counts correctly.', function(){
        var sorted = new SortedList();
        rawdata.forEach(function(d){sorted.insert(d);});

        expect(sorted.length).to.equal(rawdata.length);
    });

    var randomSize = 1000;
    it('validate '+randomSize+' random numbers.', function(){
        var raws = [];
        var sorted = new SortedList();

        for(var i = 0; i< randomSize; i++){
            var v = Math.random();
            raws.push(v);
        }

        console.time('insert-'+randomSize+'-random-number');
        sorted.insertBatch(raws);
        console.timeEnd('insert-'+randomSize+'-random-number');

        console.time('standard sorting of '+randomSize+' random number');
        raws.sort(function(a,b){return a-b;});
        console.timeEnd('standard sorting of '+randomSize+' random number');

        expect(sorted.toArray()).to.eql(raws);
    });

    it('validate cut function', function(){
        var sorted = new SortedList();
        sorted.insertBatch(rawdata);
        //sorted.print();

        console.time('Cut operation 1');
        var removed = sorted.cut(-1, 'left', true);
        console.timeEnd('Cut operation 1');
        expect(removed).to.eql([-3, -2, -1]);
        expect(sorted.toArray()).to.eql([0, 2, 2, 5, 7, 8, 10, 11, 22]);

        console.time('Cut operation 2');
        removed = sorted.cut(2, 'left', false);
        console.timeEnd('Cut operation 2');
        expect(removed).to.eql([0]);
        expect(sorted.toArray()).to.eql([2, 2, 5, 7, 8, 10, 11, 22]);

        console.time('Cut operation 3');
        removed = sorted.cut(2, 'left', true);
        console.timeEnd('Cut operation 3');
        expect(removed).to.eql([2,2]);
        expect(sorted.toArray()).to.eql([5, 7, 8, 10, 11, 22]);

        console.time('Cut operation 4');
        removed = sorted.cut(6, 'right', false);
        console.timeEnd('Cut operation 4');
        expect(removed).to.eql([7, 8, 10, 11, 22]);
        expect(sorted.toArray()).to.eql([5]);

        console.time('Cut operation 5');
        removed = sorted.cut(4, 'right', false);
        console.timeEnd('Cut operation 5');
        expect(removed).to.eql([5]);
        expect(sorted.toArray()).to.eql([]);
    });

});

<|endoftext|>


<commit_before>var Client = require("./client");
var fs = require("fs");
var superagent = require("superagent");
var errors = require("./errors");
var MEDIA_PATH = "media";

function sendFile(request, file, mediaType, callback) {
	var stream = null;
	request.buffer().type(mediaType || "application/octet-stream");
	if (typeof file === "string") {
		stream = fs.createReadStream(file);
	}
	else if (Buffer.isBuffer(file)) {
		request.set("Content-Length", file.length);
		request.write(file);
		request.end(callback);
		return;
	}
	else if (typeof file.pipe === "function" && typeof file.read === "function" && typeof file.on === "function") {
		stream = file;
	}
	if (stream) {
		//  request.on("response") sometimes could not be called
		request.req.on("response", function (res) {
			request.res = res;
			var response = new superagent.Response(request);
			callback(response);
		});
		stream.pipe(request);
		return;
	}

	callback({ statusCode: 400, text: "Invalid data to send", body: { message: "Invalid data to send" } });
}

module.exports = {
	/**
	 * Get a list of your media files
	 * @param client Client instance
	 * @param query query parameters
	 * @param callback callback function
	 * @example
	 * bandwidth.Media.list(client, function(err, list){});
	 */
	list: function (client, query, callback) {
		if (arguments.length === 1) {
			callback = client;
			client = new Client();
		}
		else if (arguments.length === 2) {
			callback = query;
			if (client instanceof Client) {
				query = {};
			}
			else {
				query = client;
				client = new Client();
			}
		}

		client.makeRequest("get", client.concatUserPath(MEDIA_PATH), query, callback);
	},

	/**
	 * Uploads a media file (or stream, or buffer) to the name you choose
	 * @param client Client instance
	 * @param name file name
	 * @param mediaTypr media type of file
	 * @param callback callback function
	 * @example
	 * bandwidth.Media.upload(client, "file.pdf", stream, "application/pdf", function(err){});
	 */
	upload: function (client, name, data, mediaType, callback) {
		if (arguments.length === 3) {
			callback = data;
			data = name;
			name = client;
			client = new Client();
			mediaType = null;
		}
		else if (arguments.length === 4) {
			callback = mediaType;
			if (client instanceof Client) {
				mediaType = null;
			}
			else {
				mediaType = data;
				data = name;
				name = client;
				client = new Client();
			}
		}

		var request = client.createRequest("put", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name));
		sendFile(request, data, mediaType, function (res) {
			client.checkResponse(res, callback);
		});
	},

	/**
	 * Downloads a media file you uploaded to given destination(file or stream)
	 * @param client Client instance
	 * @param name file name
	 * @param destination file name or stream to write downloaded file
	 * @returns request object
	 * @example
	 * bandwidth.Media.download(client, "file1.pdf", "/tmp/file1.pdf").end(function(err, res){});
	 */
	download: function (client, name, destination) {
		if (arguments.length <= 2) {
			if (client instanceof Client) {
				destination = null;
			}
			else {
				destination = name;
				name = client;
				client = new Client();
			}
		}

		var request = client.createRequest("get", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name));
		if (destination) {
			var stream = null;
			if (typeof destination === "string") {
				stream = fs.createWriteStream(destination);
			}
			else if (typeof destination.write === "function") {
				stream = destination;
			}

			if (stream) {
				return request.pipe(stream);
			}
		}

		return request;
	},

	/**
	 * Permanently deletes a media file you uploaded
	 * @param client Client instance
	 * @param name file name
	 * @param callback callback function
	 * @example
	 * bandwidth.delete(client, "file1.pdf", function(err){});
	 */
	delete: function (client, name, callback) {
		if (arguments.length === 2) {
			callback = name;
			name = client;
			client = new Client();
		}

		client.makeRequest("del", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name), callback);
	},

	/**
	 * Get information about a media file
	 * @param client Client instance
	 * @param name file name
	 * @param callback
	 * @example
	 * bandwidth.Media.getInfo(client, "file1.wav", function(err, res){});
	 */
	getInfo: function (client, name, callback) {
		if (arguments.length === 2) {
			callback = name;
			name = client;
			client = new Client();
		}

		var request = client.createRequest("head", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name));
		request.end(function (err, res) {
			if (res.ok) {
				return callback(null,
					{
						contentType: res.type,
						contentLength: res.header["content-length"]
					});
			}

			return callback(new errors.BandwidthError("Http code " + res.status, res.status));
		});
	},

	/**
	 * Get a media file binary contents
	 * @param client Client instance
	 * @param name file name
	 * @param callback
	 * @example
	 * bandwidth.Media.getContents(client, "file1.wav", function(err, res){});
	 */
	getContents: function (client, name, callback) {
		if (arguments.length === 2) {
			callback = name;
			name = client;
			client = new Client();
		}
		var path = client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name);
		client.rawGetRequest(path)
			.on("error", function (err) {
				callback(err, null);
			})
			.on("response", function (res) {
				var buf = [];
				res.on("data", function (chunk) {
					buf.push(chunk);
				});
				res.on("end", function () {
					var data = Buffer.concat(buf);
					callback(null, {
						contentType: res.headers["content-type"].split(";")[0],
						contentLength: data.length,
						contentBody: data
					});
				});
			});
	}
};
<commit_msg>Fixes in code format<commit_after>var Client = require("./client");
var fs = require("fs");
var superagent = require("superagent");
var errors = require("./errors");
var MEDIA_PATH = "media";

function sendFile(request, file, mediaType, callback) {
	var stream = null;
	request.buffer().type(mediaType || "application/octet-stream");
	if (typeof file === "string") {
		stream = fs.createReadStream(file);
	}
	else if (Buffer.isBuffer(file)) {
		request.set("Content-Length", file.length);
		request.write(file);
		request.end(callback);
		return;
	}
	else if (typeof file.pipe === "function" && typeof file.read === "function" && typeof file.on === "function") {
		stream = file;
	}
	if (stream) {
		//  request.on("response") sometimes could not be called
		request.req.on("response", function (res) {
			request.res = res;
			var response = new superagent.Response(request);
			callback(response);
		});
		stream.pipe(request);
		return;
	}

	callback({ statusCode : 400, text: "Invalid data to send", body : { message : "Invalid data to send" } });
}

module.exports = {
	/**
	 * Get a list of your media files
	 * @param client Client instance
	 * @param query query parameters
	 * @param callback callback function
	 * @example
	 * bandwidth.Media.list(client, function(err, list){});
	 */
	list : function (client, query, callback) {
		if (arguments.length === 1) {
			callback = client;
			client = new Client();
		}
		else if (arguments.length === 2) {
			callback = query;
			if (client instanceof Client) {
				query = {};
			}
			else {
				query = client;
				client = new Client();
			}
		}

		client.makeRequest("get", client.concatUserPath(MEDIA_PATH), query, callback);
	},

	/**
	 * Uploads a media file (or stream, or buffer) to the name you choose
	 * @param client Client instance
	 * @param name file name
	 * @param mediaTypr media type of file
	 * @param callback callback function
	 * @example
	 * bandwidth.Media.upload(client, "file.pdf", stream, "application/pdf", function(err){});
	 */
	upload : function (client, name, data, mediaType, callback) {
		if (arguments.length === 3) {
			callback = data;
			data = name;
			name = client;
			client = new Client();
			mediaType = null;
		}
		else if (arguments.length === 4) {
			callback = mediaType;
			if (client instanceof Client) {
				mediaType = null;
			}
			else {
				mediaType = data;
				data = name;
				name = client;
				client = new Client();
			}
		}

		var request = client.createRequest("put", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name));
		sendFile(request, data, mediaType, function (res) {
			client.checkResponse(res, callback);
		});
	},

	/**
	 * Downloads a media file you uploaded to given destination(file or stream)
	 * @param client Client instance
	 * @param name file name
	 * @param destination file name or stream to write downloaded file
	 * @returns request object
	 * @example
	 * bandwidth.Media.download(client, "file1.pdf", "/tmp/file1.pdf").end(function(err, res){});
	 */
	download : function (client, name, destination) {
		if (arguments.length <= 2) {
			if (client instanceof Client) {
				destination = null;
			}
			else {
				destination = name;
				name = client;
				client = new Client();
			}
		}

		var request = client.createRequest("get", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name));
		if (destination) {
			var stream = null;
			if (typeof destination === "string") {
				stream = fs.createWriteStream(destination);
			}
			else if (typeof destination.write === "function") {
				stream = destination;
			}

			if (stream) {
				return request.pipe(stream);
			}
		}

		return request;
	},

	/**
	 * Permanently deletes a media file you uploaded
	 * @param client Client instance
	 * @param name file name
	 * @param callback callback function
	 * @example
	 * bandwidth.delete(client, "file1.pdf", function(err){});
	 */
	delete : function (client, name, callback) {
		if (arguments.length === 2) {
			callback = name;
			name = client;
			client = new Client();
		}

		client.makeRequest("del", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name), callback);
	},

	/**
	 * Get information about a media file
	 * @param client Client instance
	 * @param name file name
	 * @param callback
	 * @example
	 * bandwidth.Media.getInfo(client, "file1.wav", function(err, res){});
	 */
	getInfo : function (client, name, callback) {
		if (arguments.length === 2) {
			callback = name;
			name = client;
			client = new Client();
		}

		var request = client.createRequest("head", client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name));
		request.end(function (err, res) {
			if (res.ok) {
				return callback(null,
					{
						contentType: res.type,
						contentLength: res.header["content-length"]
					});
			}

			return callback(new errors.BandwidthError("Http code " + res.status, res.status));
		});
	},

	/**
	 * Get a media file binary contents
	 * @param client Client instance
	 * @param name file name
	 * @param callback
	 * @example
	 * bandwidth.Media.getContents(client, "file1.wav", function(err, res){});
	 */
	getContents : function (client, name, callback) {
		if (arguments.length === 2) {
			callback = name;
			name = client;
			client = new Client();
		}
		var path = client.concatUserPath(MEDIA_PATH) + "/" + encodeURIComponent(name);
		client.rawGetRequest(path)
			.on("error", function (err) {
				callback(err, null);
			})
			.on("response", function (res) {
				var buf = [];
				res.on("data", function (chunk) {
					buf.push(chunk);
				});
				res.on("end", function () {
					var data = Buffer.concat(buf);
					callback(null, {
						contentType: res.headers["content-type"].split(";")[0],
						contentLength: data.length,
						contentBody: data
					});
				});
			});
	}
};
<|endoftext|>


<commit_before>/*!
 * write <https://github.com/jonschlinkert/write>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/* deps:mocha */
var fs = require('fs');
var del = require('delete');
var should = require('should');
var async = require('async');
var writeFile = require('./');

var files = ['tmp/a.md', 'tmp/b.md', 'tmp/c.md', 'tmp/d.md', 'tmp/e.md'];

describe('write :', function() {
  afterEach(function(cb) {
    async.each(files, function(file, next) {
      fs.exists(file, function(exists) {
        if (!exists) return cb(new Error('file does not exist:', file));
        del(file, function(err) {
          if (err) return cb(err);
          next();
        });
      });
    }, function(err) {
      if (err) return cb(err);
      cb();
    });
  });

  it('should write files asynchronously', function(cb) {
    async.each(files, function(file, next) {
      writeFile(file, 'content...', function(err) {
        if (!err) return next(err);
        next();
      });
    }, function(err) {
      if (err) return cb(err);
      cb();
    });
  });
});

describe('write sync:', function() {
  afterEach(function() {
    files.forEach(function(fp) {
      fs.existsSync(fp).should.be.true;
      try {
        del.sync(fp);
      } catch (err) {
        console.log(err);
      }
    });
  });

  it('should write files synchronously', function() {
    files.forEach(function(fp) {
      writeFile.sync(fp, '');
    });
  });
});

describe.only('write stream:', function() {
  afterEach(function() {
    fs.existsSync('a/b/c/foo.md').should.be.true;
    try {
      del.sync('a/');
    } catch (err) {
      console.log(err);
    }
  });

  it('should write files', function() {
    var file = fs.createReadStream('README.md')
      .pipe(writeFile.stream('a/b/c/foo.md'))
  });
});
<commit_msg>clean up tests<commit_after>/*!
 * write <https://github.com/jonschlinkert/write>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

require('mocha');
var assert = require('assert');
var exists = require('try-open');
var fs = require('fs');
var del = require('delete');
var should = require('should');
var async = require('async');
var writeFile = require('./');

var files = ['tmp/a.md', 'tmp/b.md', 'tmp/c.md', 'tmp/d.md', 'tmp/e.md'];

describe('write :', function() {
  afterEach(function(cb) {
    async.each(files, function(fp, next) {
      fs.stat(fp, next);
    }, function(err) {
      if (err) return cb(err);
      del('tmp', cb);
    });
  });

  it('should write files asynchronously', function(cb) {
    async.each(files, function(fp, next) {
      writeFile(fp, 'content...', next);
    }, cb);
  });
});

describe('write sync:', function() {
  afterEach(function() {
    files.forEach(function(fp) {
      assert(exists(fp));
    });

    del.sync('tmp');
  });

  it('should write files synchronously', function() {
    files.forEach(function(fp) {
      writeFile.sync(fp, '');
    });
  });
});

describe('write stream:', function() {
  afterEach(function(cb) {
    fs.stat('tmp/a/b/c/foo.md', function(err, stats) {
      if (err) return cb(err);
      del('tmp', cb);
    });
  });

  it('should write files', function() {
    var file = fs.createReadStream('README.md')
      .pipe(writeFile.stream('tmp/a/b/c/foo.md'))
  });
});
<|endoftext|>