<commit_before>var should = require('chai').should(),
    foaas_module = require('../index');

var foaas = new foaas_module();

describe('#foaas', function() {

  it('returns the version details from the API', function() {
    foaas.getVersion({type: 'json'}).then(function(data) {
      data.should.equal('0.1.4');
    });
  });

  it('says fuck off to Tom, from Chris', function() {
    foaas.off('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck off, Tom - Chris');
    });
  });

  it('says fuck you to Tom, from Chris', function() {
    foaas.off('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck you, Tom - Chris');
    });
  });

  it('says fuck this, from Chris', function() {
    foaas.off('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck this. - Chris');
    });
  });

  it('says fuck that, from Chris', function() {
    foaas.off('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck that. - Chris');
    });
  });

  it('says fuck everything, from Chris', function() {
    foaas.everything('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck everything. - Chris');
    });
  });

  it('says fuck everyone, from Chris', function() {
    foaas.everyone('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Everyone can go and fuck off. - Chris');
    });
  });

  it('brings a donut into the equation', function() {
    foaas.donut('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Tom, go and take a flying fuck at a rolling donut. - Chris');
    });
  });

  it('gets Shakespearian', function() {
    foaas.shakespeare('Falstaff', 'Prince%20Henry', {type: 'json'}).then(function(data) {
      data.should.equal('Falstaff, Thou clay-brained guts, thou knotty-pated fool, thou whoreson obscene greasy tallow-catch! - Prince Henry');
    });
  });

  it('gets linus', function() {
    foaas.linus('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Tom, there aren\'t enough swear-words in the English language, so now I\'ll have to call you perkeleen vittupää just to express my disgust and frustration with this crap. - Chris');
    });
  });

  it('gets kingly', function() {
    foaas.king('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Oh fuck off, just really fuck off you total dickface. Christ Tom, you are fucking thick. - Chris');
    });
  });

  it('gets pink', function() {
    foaas.pink('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Well, Fuck me pink. - Tom');
    });
  });

  it('does not like life', function() {
    foaas.life('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck my life. - Tom');
    });
  });

  it('uses a chainsaw', function() {
    foaas.chainsaw('Chris', 'Heather', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck me gently with a chainsaw, Chris. Do I look like Mother Teresa? - Heather');
    });
  });

  it('takes it outside', function() {
    foaas.outside('BigBrother', 'TheWorld', {type: 'json'}).then(function(data) {
      data.should.equal('BigBrother, why don\'t you go outside and play hide-and-go-fuck-yourself? - TheWorld');
    });
  });

  it('takes whatever thing you give it', function() {
    foaas.thing('pineapples', '%E2%99%A5%20Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck pineapples. - ♥ Chris');
    });
  });

  it('thanks you', function() {
    foaas.thanks('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck you very much. - Tom');
    });
  });

  it('takes it flying', function() {
    foaas.flying('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('I don\t give a flying fuck. - Tom');
    });
  });

  it('finds it fascinating', function() {
    foaas.fascinating('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fascinating story, in what chapter do you shut the fuck up? - Tom');
    });
  });

  it('goes to madison', function() {
    foaas.madison('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('What you\'ve just said is one of the most insanely idiotic things I have ever heard, Tom. At no point in your rambling, incoherent response were you even close to anything that could be considered a rational thought. Everyone in this room is now dumber for having listened to it. I award you no points :name, and may God have mercy on your soul. - Chris');
    });
  });

  it('finds it cool', function() {
    foaas.cool('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Cool story, Bro - Tom');
    });
  });

  it('finds itself glancing over the field', function() {
    foaas.field('Tom', 'Chris', 'Anon', {type: 'json'}).then(function(data) {
      data.should.equal('And Tom said unto Chris, "Verily, cast thine eyes upon the field in which I grow my fucks", and Chris gave witness unto the field, and saw that it was barren. - Anon');
    });
  });

  it('uses nuggets', function() {
    foaas.nugget('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Well Tom, aren\'t you a shining example of a rancid fuck-nugget. - Chris');
    });
  });

  it('uses the force', function() {
    foaas.yoda('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck off, you must, Tom. - Chris');
    });
  });

  it('gets M$ on your ass', function() {
    foaas.ballmer('Tom', 'Chris', 'Apple', {type: 'json'}).then(function(data) {
      data.should.equal('Fucking Tom is a fucking pussy. I\'m going to fucking bury that guy, I have done it before, and I will do it again. I\'m going to fucking kill Apple. - Chris');
    });
  });

  it('asks what?', function() {
    foaas.what('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('What the fuck?!. - Tom');
    });
  });

  it('asks why?', function() {
    foaas.because('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Why? Beacuse Fuck you, that\'s why. - Tom');
    });
  });

  it('asks to borrow a tool', function() {
    foaas.caniuse('my laptop', 'Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Can you use my laptop? Fuck no! - Tom');
    });
  });

  it('says goodbye', function() {
    foaas.bye('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fuckity bye! - Tom');
    });
  });

  it('says something about diabetes', function() {
    foaas.diabetes('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('I\'d love to stop and chat to you but I\'d rather have type 2 diabetes. - Tom');
    });
  });

  it('says something about a bus', function() {
    foaas.diabetes('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Christ on a bendy-bus, Tom, don\'t be such a fucking faff-arse. - Chris');
    });
  });

  it('wishes you season\'s greetings', function() {
    foaas.xmas('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Merry Fucking Christmas, Tom. - Chris');
    });
  });

  it('says this is awesome', function() {
    foaas.awesome('Macklemore', {type: 'json'}).then(function(data) {
      data.should.equal('This is Fucking Awesome. - Macklemore');
    });
  });

  it('SHOUTS this is awesome', function() {
    foaas.awesome('Macklemore', {type: 'json', shoutcast: true}).then(function(data) {
      data.should.equal('THIS IS FUCKING AWESOME. - MACKLEMORE');
    });
  });

  it('says this is awesome in Spanish', function() {
    foaas.awesome('Macklemore', {type: 'json', i18n: 'es'}).then(function(data) {
      data.should.equal('Esto es jodidamente increíble. - Macklemore');
    });
  });

  it('SHOUTS this is awesome in Spanish', function() {
    foaas.awesome('Macklemore', {type: 'json', shoutcast: true, i18n: 'es'}).then(function(data) {
      data.should.equal('Esto es jodidamente increíble. - Macklemore');
    });
  });

});
<commit_msg>Fixed promise returns to mocha.<commit_after>var should = require('chai').should(),
    foaas_module = require('../index');

var foaas = new foaas_module();

describe('#foaas', function() {

  it('returns the version details from the API', function() {
    return foaas.getVersion({type: 'json'}).then(function(data) {
      data.should.equal('0.1.4');
    });
  });

  it('says fuck off to Tom, from Chris', function() {
    return foaas.off('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck off, Tom - Chris');
    });
  });

  it('says fuck you to Tom, from Chris', function() {
    return foaas.off('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck you, Tom - Chris');
    });
  });

  it('says fuck this, from Chris', function() {
    return foaas.off('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck this. - Chris');
    });
  });

  it('says fuck that, from Chris', function() {
    return foaas.off('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck that. - Chris');
    });
  });

  it('says fuck everything, from Chris', function() {
    return foaas.everything('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck everything. - Chris');
    });
  });

  it('says fuck everyone, from Chris', function() {
    return foaas.everyone('Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Everyone can go and fuck off. - Chris');
    });
  });

  it('brings a donut into the equation', function() {
    return foaas.donut('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Tom, go and take a flying fuck at a rolling donut. - Chris');
    });
  });

  it('gets Shakespearian', function() {
    return foaas.shakespeare('Falstaff', 'Prince%20Henry', {type: 'json'}).then(function(data) {
      data.should.equal('Falstaff, Thou clay-brained guts, thou knotty-pated fool, thou whoreson obscene greasy tallow-catch! - Prince Henry');
    });
  });

  it('gets linus', function() {
    return foaas.linus('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Tom, there aren\'t enough swear-words in the English language, so now I\'ll have to call you perkeleen vittupää just to express my disgust and frustration with this crap. - Chris');
    });
  });

  it('gets kingly', function() {
    return foaas.king('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Oh fuck off, just really fuck off you total dickface. Christ Tom, you are fucking thick. - Chris');
    });
  });

  it('gets pink', function() {
    return foaas.pink('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Well, Fuck me pink. - Tom');
    });
  });

  it('does not like life', function() {
    return foaas.life('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck my life. - Tom');
    });
  });

  it('uses a chainsaw', function() {
    return foaas.chainsaw('Chris', 'Heather', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck me gently with a chainsaw, Chris. Do I look like Mother Teresa? - Heather');
    });
  });

  it('takes it outside', function() {
    return foaas.outside('BigBrother', 'TheWorld', {type: 'json'}).then(function(data) {
      data.should.equal('BigBrother, why don\'t you go outside and play hide-and-go-fuck-yourself? - TheWorld');
    });
  });

  it('takes whatever thing you give it', function() {
    return foaas.thing('pineapples', '%E2%99%A5%20Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck pineapples. - ♥ Chris');
    });
  });

  it('thanks you', function() {
    return foaas.thanks('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck you very much. - Tom');
    });
  });

  it('takes it flying', function() {
    return foaas.flying('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('I don\t give a flying fuck. - Tom');
    });
  });

  it('finds it fascinating', function() {
    return foaas.fascinating('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fascinating story, in what chapter do you shut the fuck up? - Tom');
    });
  });

  it('goes to madison', function() {
    return foaas.madison('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('What you\'ve just said is one of the most insanely idiotic things I have ever heard, Tom. At no point in your rambling, incoherent response were you even close to anything that could be considered a rational thought. Everyone in this room is now dumber for having listened to it. I award you no points :name, and may God have mercy on your soul. - Chris');
    });
  });

  it('finds it cool', function() {
    return foaas.cool('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Cool story, Bro - Tom');
    });
  });

  it('finds itself glancing over the field', function() {
    return foaas.field('Tom', 'Chris', 'Anon', {type: 'json'}).then(function(data) {
      data.should.equal('And Tom said unto Chris, "Verily, cast thine eyes upon the field in which I grow my fucks", and Chris gave witness unto the field, and saw that it was barren. - Anon');
    });
  });

  it('uses nuggets', function() {
    return foaas.nugget('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Well Tom, aren\'t you a shining example of a rancid fuck-nugget. - Chris');
    });
  });

  it('uses the force', function() {
    return foaas.yoda('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Fuck off, you must, Tom. - Chris');
    });
  });

  it('gets M$ on your ass', function() {
    return foaas.ballmer('Tom', 'Chris', 'Apple', {type: 'json'}).then(function(data) {
      data.should.equal('Fucking Tom is a fucking pussy. I\'m going to fucking bury that guy, I have done it before, and I will do it again. I\'m going to fucking kill Apple. - Chris');
    });
  });

  it('asks what?', function() {
    return foaas.what('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('What the fuck?!. - Tom');
    });
  });

  it('asks why?', function() {
    return foaas.because('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Why? Beacuse Fuck you, that\'s why. - Tom');
    });
  });

  it('asks to borrow a tool', function() {
    return foaas.caniuse('my laptop', 'Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Can you use my laptop? Fuck no! - Tom');
    });
  });

  it('says goodbye', function() {
    return foaas.bye('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('Fuckity bye! - Tom');
    });
  });

  it('says something about diabetes', function() {
    return foaas.diabetes('Tom', {type: 'json'}).then(function(data) {
      data.should.equal('I\'d love to stop and chat to you but I\'d rather have type 2 diabetes. - Tom');
    });
  });

  it('says something about a bus', function() {
    return foaas.diabetes('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Christ on a bendy-bus, Tom, don\'t be such a fucking faff-arse. - Chris');
    });
  });

  it('wishes you season\'s greetings', function() {
    return foaas.xmas('Tom', 'Chris', {type: 'json'}).then(function(data) {
      data.should.equal('Merry Fucking Christmas, Tom. - Chris');
    });
  });

  it('says this is awesome', function() {
    return foaas.awesome('Macklemore', {type: 'json'}).then(function(data) {
      data.should.equal('This is Fucking Awesome. - Macklemore');
    });
  });

  it('SHOUTS this is awesome', function() {
    return foaas.awesome('Macklemore', {type: 'json', shoutcast: true}).then(function(data) {
      data.should.equal('THIS IS FUCKING AWESOME. - MACKLEMORE');
    });
  });

  it('says this is awesome in Spanish', function() {
    return foaas.awesome('Macklemore', {type: 'json', i18n: 'es'}).then(function(data) {
      data.should.equal('Esto es jodidamente increíble. - Macklemore');
    });
  });

  it('SHOUTS this is awesome in Spanish', function() {
    return foaas.awesome('Macklemore', {type: 'json', shoutcast: true, i18n: 'es'}).then(function(data) {
      data.should.equal('Esto es jodidamente increíble. - Macklemore');
    });
  });

});
<|endoftext|>


<commit_before>import React from 'react';

const Projects = () =>
Projects
;

export default Projects;
<commit_msg>Added content to the projects page<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Grid from '@material-ui/core/Grid';
import Hidden from '@material-ui/core/Hidden';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';

const styles = theme => ({
  projects: {
    margin: '80px 0px',
    [theme.breakpoints.down('sm')]: {
      margin: '40px 0px',
    },
  },
  link: {
    ...theme.typography.button,
    color: theme.palette.primary.main,
    textAlign: 'left',
    lineHeight: '2em',
  },
});

const Projects = ({ classes }) => (

    <Grid container spacing={0}>
      <Hidden mdUp>
        <Grid item xs={1} />
      </Hidden>
      <Grid item xs={10} md={12}>
        <Typography variant="h3">Projects</Typography>

            Dorian.js

          <Typography variant="body1">
            A simple blogging platform which converts user written markdown files into HTML. It is
            available via the MIT OpenSource License. One of the goals of this project is to provide
            a simple use-case for learning React and front-end web-development. The aim was to make
            a personal landing-page framework which was extensible while retaining simplicity.
          </Typography>

      </Grid>
      <Hidden mdUp>
        <Grid item xs={1} />
      </Hidden>
    </Grid>

);

Projects.propTypes = {
  classes: PropTypes.objectOf(PropTypes.string).isRequired,
};

export default withStyles(styles)(Projects);
<|endoftext|>


<commit_before>const puppeteer = require('puppeteer')
const expect = require("chai").expect
const pti = require('puppeteer-to-istanbul')

describe("fetch-test", function () {
    let browser = null

    before(async () => {
        browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
        const page = await browser.newPage();

        // Enable both JavaScript and CSS coverage
        await Promise.all([
            page.coverage.startJSCoverage(),
            page.coverage.startCSSCoverage()
        ]);

        await page.goto('http://localhost:3000/', { waitUntil: 'networkidle2' });
        await page.addScriptTag({
            path: "./dist/index.umd.js"
        })

        testDataGet = [{ id: 2, body: 'some comment', postId: 1 }]
        resultGet = await page.evaluate(async () => {
            return await _fetch.getJSON('http://localhost:3000/comments/', {
                id: 2
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        testDataJSONP = [{ id: 2, body: 'some comment', postId: 1 }]
        resultJSONP = await page.evaluate(async () => {
            return await _fetch.getJSONP('http://localhost:3000/comments/', {
                id: 2
            }, {
                callbackName: "callback"
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        testDataPost = { id: 3 }
        resultPost = await page.evaluate(async () => {
            return await _fetch.postJSON('http://localhost:3000/comments/', {
                id: 3
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        testDataDel = { id: 3 }
        resultDel = await page.evaluate(async () => {
            return await _fetch.deleteJSON('http://localhost:3000/comments/3', {
                id: 3
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        resultTimeout = await page.evaluate(async () => {
            return await _fetch.getJSON('http://localhost:3000/comments/1', {}, {
                timeout: 1
            }).then(res => {
                return res
            }, err => {
                return err.message
            })
        });

        resultError = await page.evaluate(async () => {
            return await _fetch.getJSON('http://localhost:3001/').then(res => {
                return res
            }, err => {
                return err.url
            })
        });

        // Disable JavaScript coverage
        const jsCoverage = await page.coverage.stopJSCoverage()
        pti.write(jsCoverage)
    })

    after(function () {
        browser.close();
    });

    it("fetch getJSON", function () {
        expect(JSON.stringify(testDataGet)).to.equal(JSON.stringify(resultGet))
    })

    it("fetch postJSON", function () {
        expect(JSON.stringify(testDataPost)).to.equal(JSON.stringify(resultPost))
    })

    it("fetch getJSONP", function () {
        expect(JSON.stringify(testDataJSONP)).to.equal(JSON.stringify(resultJSONP))
    })

    it("fetch timeout", function () {
        expect(resultTimeout).to.equal("http://localhost:3000/comments/1 timeout")
    })

    it("fetch error", function () {
        expect(resultError).to.equal("http://localhost:3001/")
    })
})
<commit_msg>fixed: ci timeout<commit_after>const puppeteer = require('puppeteer')
const expect = require("chai").expect
const pti = require('puppeteer-to-istanbul')

describe("fetch-test", function () {
    let browser = null

    before(async () => {
        this.enableTimeouts(false)
        browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
        const page = await browser.newPage();

        // Enable both JavaScript and CSS coverage
        await Promise.all([
            page.coverage.startJSCoverage(),
            page.coverage.startCSSCoverage()
        ]);

        await page.goto('http://localhost:3000/', { waitUntil: 'networkidle2' });
        await page.addScriptTag({
            path: "./dist/index.umd.js"
        })

        testDataGet = [{ id: 2, body: 'some comment', postId: 1 }]
        resultGet = await page.evaluate(async () => {
            return await _fetch.getJSON('http://localhost:3000/comments/', {
                id: 2
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        testDataJSONP = [{ id: 2, body: 'some comment', postId: 1 }]
        resultJSONP = await page.evaluate(async () => {
            return await _fetch.getJSONP('http://localhost:3000/comments/', {
                id: 2
            }, {
                callbackName: "callback"
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        testDataPost = { id: 3 }
        resultPost = await page.evaluate(async () => {
            return await _fetch.postJSON('http://localhost:3000/comments/', {
                id: 3
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        testDataDel = { id: 3 }
        resultDel = await page.evaluate(async () => {
            return await _fetch.deleteJSON('http://localhost:3000/comments/3', {
                id: 3
            }).then(res => {
                console.log(res)
                return res
            }, err => {
                console.log(err)
            })
        });

        resultTimeout = await page.evaluate(async () => {
            return await _fetch.getJSON('http://localhost:3000/comments/1', {}, {
                timeout: 1
            }).then(res => {
                return res
            }, err => {
                return err.message
            })
        });

        resultError = await page.evaluate(async () => {
            return await _fetch.getJSON('http://localhost:3001/').then(res => {
                return res
            }, err => {
                return err.url
            })
        });
        // Disable JavaScript coverage
        const jsCoverage = await page.coverage.stopJSCoverage()
        pti.write(jsCoverage)
    })

    after(function () {
        browser.close();
    });

    it("fetch getJSON", function () {
        expect(JSON.stringify(testDataGet)).to.equal(JSON.stringify(resultGet))
    })

    it("fetch postJSON", function () {
        expect(JSON.stringify(testDataPost)).to.equal(JSON.stringify(resultPost))
    })

    it("fetch getJSONP", function () {
        expect(JSON.stringify(testDataJSONP)).to.equal(JSON.stringify(resultJSONP))
    })

    it("fetch timeout", function () {
        expect(resultTimeout).to.equal("http://localhost:3000/comments/1 timeout")
    })

    it("fetch error", function () {
        expect(resultError).to.equal("http://localhost:3001/")
    })
})
<|endoftext|>


<commit_before>import fs from 'fs'

import test from 'ava'
import {transform} from '@babel/core'

function snapshot(t, fixture, presetOptions = {}, env = 'development') {
  process.env.BABEL_ENV = env
  const filename = `${__dirname}/fixtures/${fixture}.js`
  const input = fs.readFileSync(filename, 'utf8')
  const preset = require('..')
  const options = {presets: [[preset, presetOptions]], babelrc: false}
  const result = transform(input, options)
  t.snapshot(result.code)
}

test('transpiles ES2018+ syntax', snapshot, 'esnext')
test('transpiles ES2018+ syntax in test env', snapshot, 'esnext', undefined, 'test')
test(`transpiles ES2018+ syntax strictly when {loose: false}`, snapshot, 'esnext', {loose: false})

test('does not transpile ES modules', snapshot, 'esm')
test(`transpiles ES modules when {modules: 'commonjs'}`, snapshot, 'esm', {modules: 'commonjs'})
test(`transpiles ES modules in test env`, snapshot, 'esm', undefined, 'test')

test('does not use esm babel helpers when {modules: commonjs}', snapshot, 'esm-helpers', {
  modules: 'commonjs',
  runtime: true,
})
test('uses esm babel helpers when {modules: false}', snapshot, 'esm-helpers', {runtime: true})

test('cherry picks lodash modules', snapshot, 'lodash')
test('does not modify lodash imports when {lodash: false}', snapshot, 'lodash', {lodash: false})

test('wraps prop types', snapshot, 'prop-types')
test('removes prop types in production env', snapshot, 'prop-types', undefined, 'production')
<commit_msg>Set Babel environment more robustly in tests<commit_after>import fs from 'fs'

import test from 'ava'
import {transform} from '@babel/core'

function snapshot(t, fixture, presetOptions = {}, envName = 'development') {
  const filename = `${__dirname}/fixtures/${fixture}.js`
  const input = fs.readFileSync(filename, 'utf8')
  const preset = require('..')
  const options = {envName, presets: [[preset, presetOptions]], babelrc: false}
  const result = transform(input, options)
  t.snapshot(result.code)
}

test('transpiles ES2018+ syntax', snapshot, 'esnext')
test('transpiles ES2018+ syntax in test env', snapshot, 'esnext', undefined, 'test')
test(`transpiles ES2018+ syntax strictly when {loose: false}`, snapshot, 'esnext', {loose: false})

test('does not transpile ES modules', snapshot, 'esm')
test(`transpiles ES modules when {modules: 'commonjs'}`, snapshot, 'esm', {modules: 'commonjs'})
test(`transpiles ES modules in test env`, snapshot, 'esm', undefined, 'test')

test('does not use esm babel helpers when {modules: commonjs}', snapshot, 'esm-helpers', {
  modules: 'commonjs',
  runtime: true,
})
test('uses esm babel helpers when {modules: false}', snapshot, 'esm-helpers', {runtime: true})

test('cherry picks lodash modules', snapshot, 'lodash')
test('does not modify lodash imports when {lodash: false}', snapshot, 'lodash', {lodash: false})

test('wraps prop types', snapshot, 'prop-types')
test('removes prop types in production env', snapshot, 'prop-types', undefined, 'production')
<|endoftext|>


<commit_before>/* global describe:true, it:true, before:true, beforeEach:true, afterEach:true */
import assert from 'assert';
import Rekapi from '../src/main';
import { contains } from 'lodash';

describe('Rekapi', () => {
  const setupTestRekapi = () => new Rekapi();

  const setupTestActor = (rekapi, actorArgs) =>
    rekapi.addActor(new Rekapi.Actor(actorArgs)
  );

  let rekapi, actor, actor2;

  beforeEach(() => {
    rekapi = setupTestRekapi();
    actor = setupTestActor(rekapi);
  });

  afterEach(() => {
    rekapi = undefined;
    actor = undefined;
  });

  describe('constructor', () => {
    it('is a function', () => {
      assert.equal(typeof Rekapi, 'function');
    });
  });

  describe('#addActor', () => {
    it('adds actors', () => {
      assert.equal(rekapi._actors[actor.id], actor);
    });

    it('only adds actors once', () => {
      rekapi.addActor(actor);
      assert.equal(rekapi.getActorCount(), 1);
    });

    it('propagates arguments to instantiated actor', () => {
      const actorContext = {};
      rekapi = setupTestRekapi();
      actor = setupTestActor(rekapi, { context: actorContext });

      assert(actor instanceof Rekapi.Actor);
      assert.equal(actorContext, actor.context);
    });
  });

  describe('#getActor', () => {
    it('retrieves added actor', () => {
      assert.equal(rekapi.getActor(actor.id), actor);
    });
  });

  describe('#removeActor', () => {
    it('removes an actor', () => {
      rekapi.removeActor(actor);

      assert.equal(rekapi._actors[actor.id], undefined);

      // FIXME: This needs to be moved to canvas renderer tests
      //assert.equal(rekapi._renderOrder.indexOf(actor.id), -1);
    });
  });

  describe('removeAllActors', () => {
    it('removes all actors', () => {
      setupTestActor(rekapi);
      const removedActors = rekapi.removeAllActors();

      assert.equal(Object.keys(rekapi._actors).length, 0);
      assert.equal(
        removedActors.filter(actor => actor instanceof Rekapi.Actor).length,
        2
      );
    });
  });

  describe('#getActorIds', () => {
    it('gets actor ids', () => {
      actor2 = setupTestActor(rekapi);
      const ids = rekapi.getActorIds();

      assert.equal(ids.length, 2);
      assert(contains(ids, actor.id));
      assert(contains(ids, actor2.id));
    });
  });

  describe('#getAllActors', () => {
    it('gets all actors', () => {
      actor2 = setupTestActor(rekapi);
      const actors = rekapi.getAllActors();

      assert.equal(actors[actor.id], actor);
      assert.equal(actors[actor2.id], actor2);
    });
  });

  describe('#getActor', () => {
    it('gets an actor', () => {
      assert.equal(rekapi.getActor(actor.id), actor);
    });
  });
});
<commit_msg>Port getAnimationLength tests<commit_after>/* global describe:true, it:true, before:true, beforeEach:true, afterEach:true */
import assert from 'assert';
import Rekapi from '../src/main';
import { contains } from 'lodash';

describe('Rekapi', () => {
  const setupTestRekapi = () => new Rekapi();

  const setupTestActor = (rekapi, actorArgs) =>
    rekapi.addActor(new Rekapi.Actor(actorArgs)
  );

  let rekapi, actor, actor2;

  beforeEach(() => {
    rekapi = setupTestRekapi();
    actor = setupTestActor(rekapi);
  });

  afterEach(() => {
    rekapi = undefined;
    actor = undefined;
  });

  describe('constructor', () => {
    it('is a function', () => {
      assert.equal(typeof Rekapi, 'function');
    });
  });

  describe('#addActor', () => {
    it('adds actors', () => {
      assert.equal(rekapi._actors[actor.id], actor);
    });

    it('only adds actors once', () => {
      rekapi.addActor(actor);
      assert.equal(rekapi.getActorCount(), 1);
    });

    it('propagates arguments to instantiated actor', () => {
      const actorContext = {};
      rekapi = setupTestRekapi();
      actor = setupTestActor(rekapi, { context: actorContext });

      assert(actor instanceof Rekapi.Actor);
      assert.equal(actorContext, actor.context);
    });
  });

  describe('#getActor', () => {
    it('retrieves added actor', () => {
      assert.equal(rekapi.getActor(actor.id), actor);
    });
  });

  describe('#removeActor', () => {
    it('removes an actor', () => {
      rekapi.removeActor(actor);

      assert.equal(rekapi._actors[actor.id], undefined);

      // FIXME: This needs to be moved to canvas renderer tests
      //assert.equal(rekapi._renderOrder.indexOf(actor.id), -1);
    });
  });

  describe('removeAllActors', () => {
    it('removes all actors', () => {
      setupTestActor(rekapi);
      const removedActors = rekapi.removeAllActors();

      assert.equal(Object.keys(rekapi._actors).length, 0);
      assert.equal(
        removedActors.filter(actor => actor instanceof Rekapi.Actor).length,
        2
      );
    });
  });

  describe('#getActorIds', () => {
    it('gets actor ids', () => {
      actor2 = setupTestActor(rekapi);
      const ids = rekapi.getActorIds();

      assert.equal(ids.length, 2);
      assert(contains(ids, actor.id));
      assert(contains(ids, actor2.id));
    });
  });

  describe('#getAllActors', () => {
    it('gets all actors', () => {
      actor2 = setupTestActor(rekapi);
      const actors = rekapi.getAllActors();

      assert.equal(actors[actor.id], actor);
      assert.equal(actors[actor2.id], actor2);
    });
  });

  describe('#getActor', () => {
    it('gets an actor', () => {
      assert.equal(rekapi.getActor(actor.id), actor);
    });
  });

  describe('#getAnimationLength', () => {
    describe('single actor', () => {
      it('calculates correct animation length', () => {
        actor
          .keyframe(0, { x: 1 })
          .keyframe(1000, { x: 2 })
          .keyframe(2000, { x: 3 });

        assert.equal(rekapi.getAnimationLength(), 2000);
      });
    });

    describe('multiple actors', () => {
      it('calculates correct animation length', () => {
        actor
          .keyframe(0, { x: 1 })
          .keyframe(1000, { x: 2 })
          .keyframe(2000, { x: 3 });

        setupTestActor(rekapi)
          .keyframe(0, { x: 1 })
          .keyframe(5000, { x: 2 });

        assert.equal(rekapi.getAnimationLength(), 5000);
      });
    });
  });
});
<|endoftext|>


<commit_before>var Router = require('new_dashboard/router');
var $ = require('jquery');
var cdb = require('cartodb.js');
var MainView = require('new_dashboard/main_view');

/**
*  The Holy Dashboard
*/
$(function() {

  cdb.init(function() {
    cdb.templates.namespace = 'cartodb/';
    cdb.config.set(config); // import config
    if (cdb.config.isOrganizationUrl()) {
      cdb.config.set('url_prefix', cdb.config.organizationUrl());
    }

    var router = new Router();

    // Mixpanel test
    if (window.mixpanel) {
      new cdb.common.Mixpanel({
        user: user_data,
        token: mixpanel_token
      });
    }

    // Store JS errors
    new cdb.admin.ErrorStats({ user_data: user_data });

    // Main view
    var dashboard = new MainView({
      el:          document.body,
      user_data:   user_data,
      upgrade_url: upgrade_url,
      config:      config,
      router:      router
    });

    window.dashboard = dashboard;

    // History
    Backbone.history.start({
      pushState:  true,
      root:       cdb.config.prefixUrl() + '/' //cdb.config.prefixUrl() + '/dashboard/'
    });
  });

});
<commit_msg>Make the config dependency's origin<commit_after>var Router = require('new_dashboard/router');
var $ = require('jquery');
var cdb = require('cartodb.js');
var MainView = require('new_dashboard/main_view');

/**
*  The Holy Dashboard
*/
$(function() {

  cdb.init(function() {
    cdb.templates.namespace = 'cartodb/';
    cdb.config.set(window.config); // import config
    if (cdb.config.isOrganizationUrl()) {
      cdb.config.set('url_prefix', cdb.config.organizationUrl());
    }

    var router = new Router();

    // Mixpanel test
    if (window.mixpanel) {
      new cdb.common.Mixpanel({
        user: user_data,
        token: mixpanel_token
      });
    }

    // Store JS errors
    new cdb.admin.ErrorStats({ user_data: user_data });

    // Main view
    var dashboard = new MainView({
      el:          document.body,
      user_data:   user_data,
      upgrade_url: upgrade_url,
      config:      config,
      router:      router
    });

    window.dashboard = dashboard;

    // History
    Backbone.history.start({
      pushState:  true,
      root:       cdb.config.prefixUrl() + '/' //cdb.config.prefixUrl() + '/dashboard/'
    });
  });

});
<|endoftext|>


<commit_before>var
    esPhinx;

(function($, $module) {
    "use strict";

    var
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    $module.extend({
        selectors: {Select: {}}
    });

    $.Extender.extend($module.selectors.Select, true, {
        new: function(select, options) {
            var
                ConstructorReference = $module.selectors.Select.new,
                wrapper = $("

"),
                caption = $("

"),
                optionsPanel = $("

"),
                searchTextBox = $("<input></input>"),
                abstractSelect = $("

"),
                abstractOptions = [],
                captionText = $("

"),
                selectElement = $(select),
                optionElements = selectElement.find("option"),

                resolveArguments = function(options) {
                    if(!options) {
                        options = {};
                    }

                    if(!options.developmentMode ||
                       typeof options.developmentMode != "boolean") {
                        options.developmentMode = false;
                    }
                },

                selected = function(select) {
                    return $(select).find("option:checked");
                },

                toggleCaptionClass = function(caption) {
                    caption.toggleClass("expanded-arrow", "retracted-arrow");
                },

                attachFoundListEventListener = function(abstractOptions) {
                    var
                        callback = function(abstractOption) {
                            $(abstractOption.element()).off("click");
                            $(abstractOption.element()).on("click", function() {
                                abstractOption.select();
                            });
                        };

                    abstractOptions.forEach(callback);
                },

                composeOptions = function(optionElements) {
                    var
                        callback = function(option) {
                            var
                                optionObject = Option.new({
                                    option: option,
                                    select: selectElement,
                                    caption: caption,
                                    captionText: captionText,
                                    optionsPanel: optionsPanel,
                                    abstractSelect: abstractSelect
                                });

                            abstractSelect.append(optionObject.element());
                            abstractOptions.push(optionObject);
                        };

                    // debugger
                    optionElements.each(callback);
                    attachFoundListEventListener(abstractOptions);
                    abstractOptions = [];
                },

                compose = function() {
                    if (!options.developmentMode) {
                        selectElement.hide();
                    }

                    wrapper.insertAfter(selectElement);
                    captionText.text(selected(selectElement).text());
                    caption.append(captionText);
                    wrapper.prepend(caption);
                    wrapper.append(optionsPanel);
                    optionsPanel.append(abstractSelect);

                    var

                        composeSearchTextBox = function() {
                            searchTextBox.attribute("type", "text");
                            optionsPanel.prepend(searchTextBox);
                            // debugger
                            $.ui.panels.autocomplete.new(searchTextBox,
                                                         abstractSelect,
                                                         options.autocomplete,
                                function(found) {
                                    // debugger
                                    composeOptions(found);
                                }
                            );
                        };

                    wrapper.addClass(CSS_CLASS + " select");
                    caption.addClass("caption retracted-arrow");
                    optionsPanel.addClass("options-panel");
                    captionText.addClass("text");

                    // toggle on click on caption
                    caption.on("click", function() {
                        optionsPanel.toggle();
                        toggleCaptionClass($(this));
                    });

                    if (typeof options.searchTextBox == "boolean" &&
                        options.searchTextBox) {
                        composeSearchTextBox();
                    }

                    composeOptions(optionElements);
                },

                attachClickFromOutsideEventListener = function() {
                    var
                        wrapper = $(CSS_CLASS_QUERY + ".select"),
                        optionsPanels = wrapper.find(".options-panel"),
                        captions = wrapper.find(".caption");

                    $(window.document).on("click", function(e) {

                        if ($(e.target).parent(CSS_CLASS_QUERY + ".select")
                            .empty()) {
                            if (optionsPanels.visible()) {
                                optionsPanels.hide();
                                captions.removeClass("expanded-arrow");
                                captions.addClass("retracted-arrow");
                            }
                        }
                    });
                },

                addOptions = function(select, optionElements) {
                    var
                        callback = function(optionElement) {
                            select.append(optionElement);
                        };

                    $(optionElements).each(callback);
                },

                replaceSelectOptions = function(select, optionElements) {
                    select.clean();
                    addOptions(select, $(optionElements));
                },

                Option = {
                    new: function(data) {
                        var
                            option,
                            abstractOption,
                            ConstructorReference = Option.new,
                            select = $(data.select),

                            build = function(li, option) {
                                li = $(li);
                                option = $(option);
                                li.text(option.text());
                                li.attribute("data-value", option
                                             .attribute("value"));
                            };

                        if (!(this instanceof ConstructorReference)) {
                            return new ConstructorReference(data);
                        }

                        if ($(data.option).tagName() == "option") {
                            option = $(data.option);
                            abstractOption = $("

");
                            build(abstractOption, option);
                        } else {
                            abstractOption = $(data.option);
                            option = select.find("option[value='" +
                                      abstractOption.data("value") + "']");
                        }

                        this.select = function() {
                            $(data.captionText).text($(abstractOption)
                                                     .textContent());
                            select.find("option:checked").unselect();
                            option.select();
                            $(data.optionsPanel).hide();
                            toggleCaptionClass(data.caption);
                        };

                        this.element = function() {
                            return abstractOption;
                        };
                    }
                };

            if (!(this instanceof ConstructorReference)) {
                return new ConstructorReference(select, options);
            }

            resolveArguments(options);
            select = $(select);
            compose();
            attachClickFromOutsideEventListener();

            this.addOptions = function(optionElements) {
                addOptions(select, optionElements);
                composeOptions(optionElements);
            };

            this.replaceOptions = function(optionElements) {
                abstractSelect.clean();
                replaceSelectOptions(select, optionElements);
                composeOptions(optionElements);
            };

            return this;
        }
    });

}(esPhinx, esPhinx.ui));
<commit_msg>fix list as argument<commit_after>var
    esPhinx;

(function($, $module) {
    "use strict";

    var
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    $module.extend({
        selectors: {Select: {}}
    });

    $.Extender.extend($module.selectors.Select, true, {
        new: function(select, options) {
            var
                ConstructorReference = $module.selectors.Select.new,
                wrapper = $("

"),
                caption = $("

"),
                optionsPanel = $("

"),
                searchTextBox = $("<input></input>"),
                abstractSelect = $("

"),
                abstractOptions = [],
                captionText = $("

"),
                selectElement = $(select),
                optionElements = selectElement.find("option"),

                resolveArguments = function(options) {
                    if(!options) {
                        options = {};
                    }

                    if(!options.developmentMode ||
                       typeof options.developmentMode != "boolean") {
                        options.developmentMode = false;
                    }
                },

                selected = function(select) {
                    return $(select).find("option:checked");
                },

                toggleCaptionClass = function(caption) {
                    caption.toggleClass("expanded-arrow", "retracted-arrow");
                },

                attachFoundListEventListener = function(abstractOptions) {
                    var
                        callback = function(abstractOption) {
                            $(abstractOption.element()).off("click");
                            $(abstractOption.element()).on("click", function() {
                                abstractOption.select();
                            });
                        };

                    abstractOptions.forEach(callback);
                },

                composeOptions = function(optionElements) {
                    var
                        callback = function(option) {
                            var
                                optionObject = Option.new({
                                    option: option,
                                    select: selectElement,
                                    caption: caption,
                                    captionText: captionText,
                                    optionsPanel: optionsPanel,
                                    abstractSelect: abstractSelect
                                });

                            abstractSelect.append(optionObject.element());
                            abstractOptions.push(optionObject);
                        };

                    // debugger
                    optionElements.each(callback);
                    attachFoundListEventListener(abstractOptions);
                    abstractOptions = [];
                },

                compose = function() {
                    if (!options.developmentMode) {
                        selectElement.hide();
                    }

                    wrapper.insertAfter(selectElement);
                    captionText.text(selected(selectElement).text());
                    caption.append(captionText);
                    wrapper.prepend(caption);
                    wrapper.append(optionsPanel);
                    optionsPanel.append(abstractSelect);

                    var

                        composeSearchTextBox = function() {
                            searchTextBox.attribute("type", "text");
                            optionsPanel.prepend(searchTextBox);
                            // debugger
                            $.ui.panels.autocomplete.new(searchTextBox,
                                // abstractSelect,
                                abstractSelect.childElements(),
                                options.autocomplete,
                                function(found) {
                                    // debugger
                                    composeOptions(found);
                                }
                            );
                        };

                    wrapper.addClass(CSS_CLASS + " select");
                    caption.addClass("caption retracted-arrow");
                    optionsPanel.addClass("options-panel");
                    captionText.addClass("text");

                    // toggle on click on caption
                    caption.on("click", function() {
                        optionsPanel.toggle();
                        toggleCaptionClass($(this));
                    });

                    composeOptions(optionElements);

                    if (typeof options.searchTextBox == "boolean" &&
                        options.searchTextBox) {
                        composeSearchTextBox();
                    }
                },

                attachClickFromOutsideEventListener = function() {
                    var
                        wrapper = $(CSS_CLASS_QUERY + ".select"),
                        optionsPanels = wrapper.find(".options-panel"),
                        captions = wrapper.find(".caption");

                    $(window.document).on("click", function(e) {

                        if ($(e.target).parent(CSS_CLASS_QUERY + ".select")
                            .empty()) {
                            if (optionsPanels.visible()) {
                                optionsPanels.hide();
                                captions.removeClass("expanded-arrow");
                                captions.addClass("retracted-arrow");
                            }
                        }
                    });
                },

                addOptions = function(select, optionElements) {
                    var
                        callback = function(optionElement) {
                            select.append(optionElement);
                        };

                    $(optionElements).each(callback);
                },

                replaceSelectOptions = function(select, optionElements) {
                    select.clean();
                    addOptions(select, $(optionElements));
                },

                Option = {
                    new: function(data) {
                        var
                            option,
                            abstractOption,
                            ConstructorReference = Option.new,
                            select = $(data.select),

                            build = function(li, option) {
                                li = $(li);
                                option = $(option);
                                li.text(option.text());
                                li.attribute("data-value", option
                                             .attribute("value"));
                            };

                        if (!(this instanceof ConstructorReference)) {
                            return new ConstructorReference(data);
                        }

                        if ($(data.option).tagName() == "option") {
                            option = $(data.option);
                            abstractOption = $("

");
                            build(abstractOption, option);
                        } else {
                            abstractOption = $(data.option);
                            option = select.find("option[value='" +
                                      abstractOption.data("value") + "']");
                        }

                        this.select = function() {
                            $(data.captionText).text($(abstractOption)
                                                     .textContent());
                            select.find("option:checked").unselect();
                            option.select();
                            $(data.optionsPanel).hide();
                            toggleCaptionClass(data.caption);
                        };

                        this.element = function() {
                            return abstractOption;
                        };
                    }
                };

            if (!(this instanceof ConstructorReference)) {
                return new ConstructorReference(select, options);
            }

            resolveArguments(options);
            select = $(select);
            compose();
            attachClickFromOutsideEventListener();

            this.addOptions = function(optionElements) {
                addOptions(select, optionElements);
                composeOptions(optionElements);
            };

            this.replaceOptions = function(optionElements) {
                abstractSelect.clean();
                replaceSelectOptions(select, optionElements);
                composeOptions(optionElements);
            };

            return this;
        }
    });

}(esPhinx, esPhinx.ui));
<|endoftext|>


<commit_before>(function ($) {
    "use strict";

    try {
        Object.defineProperties($, {

            // talves seja interessante fazer uma rotina para o carregamento de uma da lib js, de forma que seja verificado previamente, varrendo-se a tag head, se o script já não se encontra carregado.

            // Para apenas dois números o Algorítmo de Euclides é mais rápido, que pode ser usado recursivamente
            // greatest common divisor
            gcd: {
                value: function () {
                    var
                        numbers = [],
                        commonFactors = [],
                        smallerFactorsHash = {},
                        count = 0,
                        i = 0,
                        smallerCommonProduct = 1;

                    for(i in arguments) {
                        if(arguments.hasOwnProperty(i)) {
                            numbers.push(parseFloat(arguments[i]));
                        }
                    }

                    numbers = numbers.asc();
                    numbers = numbers.uniq();
                    if(numbers.length == 1) {
                        return numbers[0];
                    }

                    // dois números primos nunca serão múltiplos entre si
                    i = 0;
                    while(true) {
                        if((numbers[i]).isPrime()) {count++;}
                        if(count >= 2) {return 1;}
                        if(i == numbers.length -1) {break;}
                        i++;
                    }

                    if(numbers.areMultiples()) {return numbers.min();}

                    numbers.map(function (v) {
                        numbers.push(v.primeFactors());
                    });

                    commonFactors = numbers.intersection();

                    if(commonFactors) {
                        numbers.map(function (a) {
                            commonFactors.map(function (v) {
                                if(!smallerFactorsHash[v]) {
                                    smallerFactorsHash[v] = a.count(v);
                                } else {
                                    if(a.count(v) < smallerFactorsHash[v]) {
                                        smallerFactorsHash[v] = a.count(v);
                                    }
                                }
                            });
                        });
                    } else {
                        return [];
                    }

                    for(i in smallerFactorsHash) {
                        if (smallerFactorsHash.hasOwnProperty(i)) {
                                smallerCommonProduct *= Math.pow(i, smallerFactorsHash[i]);
                        }
                    }

                    return smallerCommonProduct;
                }
            },

            // least common multiple
            lcm: {
                value: function () {
                    var
                        numbers = [],
                        commonFactors = [],
                        nonCommonfactors = [],
                        biggerFactorsHash = {},
                        i = 0,
                        biggerCommonProduct = 1,
                        noCommonFactors = 1;

                    for(i in arguments) {
                        if(arguments.hasOwnProperty(i)) {
                            numbers.push(parseFloat(arguments[i]));
                        }
                    }

                    numbers = numbers.asc();
                    numbers = numbers.uniq();
                    if(numbers.length == 1) {
                        return numbers[0];
                    }

                    if(numbers.areMultiples()) {return numbers.max();}

                    numbers.map(function (v) {
                        numbers.push(v.primeFactors());
                    });

                    commonFactors = numbers.intersection();

                    numbers.map(function (a) {
                        commonFactors.map(function (v) {
                            if(!biggerFactorsHash[v]) {
                                biggerFactorsHash[v] = a.count(v);
                            } else {
                                if(a.count(v) > biggerFactorsHash[v]) {
                                    biggerFactorsHash[v] = a.count(v);
                                }
                            }
                        });
                    });

                    for(i in biggerFactorsHash) {
                        if (biggerFactorsHash.hasOwnProperty(i)) {
                                biggerCommonProduct *= Math.pow(i, biggerFactorsHash[i]);
                        }
                    }

                    // JSON.parse("[" + string + "]");
                    nonCommonfactors = numbers.join().split(',').map(Number).uniq()
                    .difference(commonFactors);

                    nonCommonfactors.map(function (v) {
                        noCommonFactors *= v;
                    });

                    return biggerCommonProduct * noCommonFactors;
                }
            }

        });

    } catch(e) {}

})(Math);
<commit_msg>comments<commit_after>(function ($) {
    "use strict";

    try {
        Object.defineProperties($, {

            // greatest common divisor
            GCD: {
                value: function () {
                    var
                        numbers = [],
                        commonFactors = [],
                        smallerFactorsHash = {},
                        count = 0,
                        i = 0,
                        smallerCommonProduct = 1,

                        euclidesAlgorithm = function(a, b) {
                            var
                                rest = b;

                            while(rest != 0) {
                               rest = a % b;
                               a = b;
                               b = rest;
                            }

                            return a;
                        };

                    for(i in arguments) {
                        if(arguments.hasOwnProperty(i)) {
                            numbers.push(parseFloat(arguments[i]));
                        }
                    }

                    numbers = numbers.asc();
                    numbers = numbers.uniq();
                    if(numbers.length == 1) {
                        return numbers[0];
                    }

                    // rules
                    // dois números primos nunca serão múltiplos entre si
                    i = 0;
                    while(true) {
                        if((numbers[i]).isPrime()) {count++;}
                        if(count >= 2) {return 1;}
                        if(i == numbers.length -1) {break;}
                        i++;
                    }

                    if(numbers.areMultiples()) {return numbers.min();}

                    numbers.map(function (v) {
                        numbers.push(v.primeFactors());
                    });

                    commonFactors = numbers.intersection();

                    if(commonFactors) {
                        numbers.map(function (a) {
                            commonFactors.map(function (v) {
                                if(!smallerFactorsHash[v]) {
                                    smallerFactorsHash[v] = a.count(v);
                                } else {
                                    if(a.count(v) < smallerFactorsHash[v]) {
                                        smallerFactorsHash[v] = a.count(v);
                                    }
                                }
                            });
                        });
                    } else {
                        return [];
                    }

                    for(i in smallerFactorsHash) {
                        if (smallerFactorsHash.hasOwnProperty(i)) {
                                smallerCommonProduct *= Math
                                    .pow(i, smallerFactorsHash[i]);
                        }
                    }

                    return smallerCommonProduct;
                }
            },

            // least common multiple
            LCM: {
                value: function () {
                    var
                        numbers = [],
                        commonFactors = [],
                        nonCommonfactors = [],
                        biggerFactorsHash = {},
                        i = 0,
                        biggerCommonProduct = 1,
                        noCommonFactors = 1;

                    for(i in arguments) {
                        if(arguments.hasOwnProperty(i)) {
                            numbers.push(parseFloat(arguments[i]));
                        }
                    }

                    numbers = numbers.asc();
                    numbers = numbers.uniq();
                    if(numbers.length == 1) {
                        return numbers[0];
                    }

                    if(numbers.areMultiples()) {return numbers.max();}

                    numbers.map(function (v) {
                        numbers.push(v.primeFactors());
                    });

                    commonFactors = numbers.intersection();

                    numbers.map(function (a) {
                        commonFactors.map(function (v) {
                            if(!biggerFactorsHash[v]) {
                                biggerFactorsHash[v] = a.count(v);
                            } else {
                                if(a.count(v) > biggerFactorsHash[v]) {
                                    biggerFactorsHash[v] = a.count(v);
                                }
                            }
                        });
                    });

                    for(i in biggerFactorsHash) {
                        if (biggerFactorsHash.hasOwnProperty(i)) {
                                biggerCommonProduct *= Math
                                    .pow(i, biggerFactorsHash[i]);
                        }
                    }

                    // JSON.parse("[" + string + "]");
                    // what a fuck is that?
                    nonCommonfactors = numbers.join().split(',').map(Number)
                        .uniq().difference(commonFactors);

                    nonCommonfactors.map(function (v) {
                        noCommonFactors *= v;
                    });

                    return biggerCommonProduct * noCommonFactors;
                }
            }

        });

    } catch(e) {}

})(Math);
<|endoftext|>


<commit_before>/**
 * @namespace FormComponents
 */

// External Requirements
var _             = require('lodash');
var React         = require('react/addons');
var validator     = require('validator');
var isEmpty       = require('../../../utils/isEmpty');

// Page Components
var Row           = require('../../page-structure/Row');
var Column        = require('../../page-structure/Column');
var FormActions   = require('../../../actions/FormActionCreators');
var FormValidator = require('./FormValidator');

// Stores
var FormStore     = require('../../../stores/FormStore');

/**
 * This component is responsible for rendering all form components
 * as well as updating the form field's data in the FormStore.
 *
 * @class Form
 * @memberOf FormComponents
 */
var Form = React.createClass({
	propTypes: {
		// A unique identifier for this instance of the form component
		formKey: React.PropTypes.string.isRequired,
		// The resource to bind
		bindResource: React.PropTypes.oneOfType([
			React.PropTypes.object,
			React.PropTypes.array
		]).isRequired,
		// An optional submit handler
		onSubmit: React.PropTypes.func,
		schema: React.PropTypes.object
	},

	getInitialState: function () {
		return {
			isValid: true,
			boundResource: {}
		}
	},

	/**
	 * Container for the bound resource
	 */
	boundResource: {},

	validator: null,

	/**
	 * Bubble up form's boundResource with parent state.
	 *
	 * @param resource
	 * @param isValid
	 */
	syncBoundResource: function (resource, isValid) {
		this.props.bindResourceCallback(resource, this.state.isValid);
	},

	componentDidMount: function () {
		var self = this;

		if (self.props.schema) {
			self.validator = new FormValidator(self.props.schema);
		}

		// Set the bound resource that will be passed down to child components
		self.setState({
			boundResource: self.props.bindResource
		}, function() {
			if (! isEmpty(self.state.boundResource) && self.props.schema) {
				self.validateAndRegisterFormAgainstSchema();
			} else {
				FormActions.registerForm(self.props.formKey, self.props.bindResource);
			}
		});
	},

	/**
	 * Form component receives props on every parent state change (when form fields are edited). On these events,
	 * we need to sync the form's resource with parent's state.
	 *
	 * @param nextProps
	 */
	componentWillReceiveProps: function (nextProps) {
		this.boundResource = nextProps.bindResource; // Sync form's resource with parent's state
		//FormActions.registerForm(this.props.formKey, this.props.bindResource); @todo is this needed?

		// Set the bound resource that will be passed down to child components
		this.setState({
			boundResource: nextProps.bindResource
		});
	},

	/**
	 * Master parent change handler for every child form field component.
	 *
	 * @param path
	 * @param value
	 * @param component
	 */
	handleChange: function (fieldKey, value, component) {
		var self = this;

		// If there's a schema, we validate using that
		if (self.props.schema) {
			// Clone the form's data to test against
			var form = _.cloneDeep(FormStore.getResource(self.props.formKey));

			// Set the value of the updated field locally so we can validate before saving
			_.set(form, fieldKey, value);

			// Test all the fields, including the locally-edited one
			var errors = self.validator.validate(form);

			// If there's errors returned from the validator, we set those fields to invalid
			if (errors) {
				var errorFields = self.getNestedFieldKeys(errors);

				errorFields.forEach(function(field) {
					FormActions.editField(self.props.formKey, field, _.get(form, field), false);
				});

				// If the errors don't include the field we editited, we save the value and set isValid to true
				if (! errorFields.includes(fieldKey)) {
					FormActions.editField(self.props.formKey, fieldKey, value, true);
				}

			// If there are no errors, we just save the edited field as valid
			} else {
				FormActions.editField(self.props.formKey, fieldKey, value, true)
			}

		// If there's no included schema, we proceed with saving the value using local validation
		} else {
			var isValid = self.validate(fieldKey, value);
			// Apply the change
			FormActions.editField(self.props.formKey, fieldKey, value, isValid);
		}
	},

	/**
	 * When there's a schema, handles validating the form and registering it.
	 *
	 * This is used to flag invalid fields on page-load
	 *
	 * @return {null}
	 */
	validateAndRegisterFormAgainstSchema: function() {
		var self = this,
			validations = {},
			isValid;

		// Clone the form's data to test against
		var resource = this.state.boundResource;

		// Test all the fields on the form
		var errors = self.validator.validate(resource);

		// If there's errors returned from the validator, we set those fields to invalid
		if (errors) {
			var errorFields = self.getNestedFieldKeys(errors);

			isValid = false;

			errorFields.forEach(function(field) {
				validations[field] = false;
			});
		}

		FormActions.registerForm(this.props.formKey, resource, validations, isValid);
	},

	/**
	 * Takes an object with infinitely nested values and grabs the paths to all values
	 *
	 * Example:
	 *	var obj = {a: 1, b: {c: 2}};
	 *	getNestedFieldKeys(obj); // ['a', 'b.c']
	 *
	 * @param {object} obj The object to be flattened
	 *
	 * @return {array}     An array of paths to all values on the object
	 */
	getNestedFieldKeys: function(obj) {
		var self = this;

		return Object.keys(obj).map(function(key) {
			if (typeof obj[key] === 'object') {
				return self.getNestedFieldKeys(obj[key]).map(function(deepKey) {
					return '{}.{}'.format(key, deepKey);
				});
			} else {
				return key;
			}
		}).reduce(function(array, value) {
			return array.concat(value);
		}, []);
	},

	// @todo this might be helpful to fully flesh out and use
	determineColumnSize: function () {
		var columns = React.Children.count(this.props.children);
		return Math.floor(12 / columns);
	},

	/**
	 * Handle attaching universal properties to all children
	 */
	componentWillMount: function () {
		this.traverseChildren(this.props.children);
	},

	componentWillUnmount: function () {
		this.boundResource = {}; // Clear bound resource
	},

	/**
	 * Container for all form field components. This is only for observation of child components, not for modifying them.
	 */
	formFields: {},

	/**
	 * Built upon http://christianalfoni.github.io/javascript/2014/10/22/nailing-that-validation-with-reactjs.html
	 *
	 * @param component
	 * @param value
	 */
	validate: function (fieldKey, value) {
		var formField = this.formFields[fieldKey];

		if (formField.required && (!value || value.length < 1)) {
			return false;
		}

		// If no validations, don't continue
		if (! formField.validations) {
			return true;
		}

		var isValid = true;

		if (value || (formField.required === true)) {
			// Parse the validations string
			formField.validations.split(',').forEach(function (validation) {
				var args = validation.split(':');
				var validationMethod = args.shift(); // ['isLength', 5] -> 'isLength'

				args = args.map(function (arg) {
					return JSON.parse(arg); // Coerce values to correct types
				});

				args = [value].concat(args);

				// Call validator with ['isValidationMethod', 'arg1', 'arg2']
				if (! validator[validationMethod].apply(validator, args)) {
					isValid = false;
				}
			});
		}

		// Call child component callback to set its state, and register the full form validator as a callback
		//component.setValidationState(isValid, this.validateForm); @todo set field validity state
		return isValid;
	},

	/**
	 * Validate form in full
	 */
	validateForm: function () {
		this.setState({
			isValid: FormStore.isFormValid()
		});
	},

	/**
	 * Dynamically (recursively) traverse every child component and set some universal properties for them.
	 *
	 * @param children
	 * @returns {*}
	 */
	traverseChildren: function (children) {
		return React.Children.map(children, function (child) {
			if (! child || ! child.props) {
				return child;
			}

			if (children.props && typeof children.props.changeCallback === 'function') {
				var changeCallback = children.props.changeCallback;
			} else {
				var changeCallback = this.handleChange;
			}

			if (child.props.fieldKey) {
				child = React.addons.cloneWithProps(child, {
					changeCallback: changeCallback,
					bindResource: this.props.bindResource,
					formKey: this.props.formKey
				});

				this.formFields[child.props.fieldKey] = {
					validations: child.props.validations || false,
					required: child.props.required ? true : false,
					isValid: FormStore.isFieldValid(this.props.formKey, child.props.fieldKey)
				}
			}

			if (child.props.children) {
				child = React.addons.cloneWithProps(child, {
					children: this.traverseChildren(child.props.children)
				});
			}

			return child;
		}.bind(this))
	},

	/**
	 * Determine if there's an onSubmit handler available
	 *
	 * @param event
	 */
	handleSubmit: function (event) {
		event.preventDefault();
		this.props.onSubmit ? this.props.onSubmit(event) : void(0);
	},

	render: function () {
		return (
			<form role="form" onSubmit={this.handleSubmit}>
				{this.traverseChildren(this.props.children)}
			</form>
		)
	}
});

// The currently available form components

// Layout
Form.Row             = Row;
Form.Column          = Column;
Form.Submit          = require('./Submit');

// Text Input
Form.Input           = require('./Input');
Form.FizzyWig        = require('./FizzyWig');
Form.TextArea        = require('./TextArea');
Form.TypeAheadInput  = require('./TypeAheadInput');

// Selection
Form.File            = require('./FileInput');
Form.Checkbox        = require('./Checkbox');
Form.SelectBox       = require('./SelectBox');
Form.RadioButtons    = require('./RadioButtons');
Form.DropdownSelect  = require('./DropdownSelect');

// Date && Time
Form.DatePicker      = require('./Time/DatePicker');
Form.TimePicker      = require('./Time/TimePicker');

module.exports = Form;
<commit_msg>Updating documentation<commit_after>/**
 * Form components are varied in implementation, but all focus on one thing: editing data.
 * All Form components can live outside of the '<Form>', but wrapping them in '<Form>' adds a lot of functionality.  For example, automatic updating of bound resources via the FormStore.
 *
 * In the below example, we require the Mortar Form, and create a working resource with the property "first_name".  We then bind that resource to the form, and reference the path to that key in `Br.Form.Input`.  The input is rendered with the value specified in 'workingResource'.  Now, any changes to that input field will be caught by the Form, and a change event will be fired in the 'FormStore'.
 *
 * Registering a change listener to the 'FormStore' will allow changes to be picked up in our component, and let us 'setState()' with any changes.
 *
 * @example
 * var Br = MortarJS.require('components', 'Form');
 * var FormStore = MortarJS.Stores.FormStore;
 *
 * // in the component:
 * workingResource = {first_name: 'Kyle'}
 *
 * // in component.render
 * <Br.Form key="a string" formKey="unique string" bindResource={this.workingResource}>
 *	<Br.Form.Input fieldKey="first_name" type="text" label="First Name" />
 *</Br.Form>
 *
 * @namespace FormComponents
 */

// External Requirements
var _             = require('lodash');
var React         = require('react/addons');
var validator     = require('validator');
var isEmpty       = require('../../../utils/isEmpty');

// Page Components
var Row           = require('../../page-structure/Row');
var Column        = require('../../page-structure/Column');
var FormActions   = require('../../../actions/FormActionCreators');
var FormValidator = require('./FormValidator');

// Stores
var FormStore     = require('../../../stores/FormStore');

/**
 * This component is responsible for rendering all form components
 * as well as updating the form field's data in the FormStore.
 *
 * @class Form
 * @memberOf FormComponents
 */
var Form = React.createClass({
	propTypes: {
		// A unique identifier for this instance of the form component
		formKey: React.PropTypes.string.isRequired,
		// The resource to bind
		bindResource: React.PropTypes.oneOfType([
			React.PropTypes.object,
			React.PropTypes.array
		]).isRequired,
		// An optional submit handler
		onSubmit: React.PropTypes.func,
		schema: React.PropTypes.object
	},

	getInitialState: function () {
		return {
			isValid: true,
			boundResource: {}
		}
	},

	/**
	 * Container for the bound resource
	 */
	boundResource: {},

	validator: null,

	/**
	 * Bubble up form's boundResource with parent state.
	 *
	 * @param resource
	 * @param isValid
	 */
	syncBoundResource: function (resource, isValid) {
		this.props.bindResourceCallback(resource, this.state.isValid);
	},

	componentDidMount: function () {
		var self = this;

		if (self.props.schema) {
			self.validator = new FormValidator(self.props.schema);
		}

		// Set the bound resource that will be passed down to child components
		self.setState({
			boundResource: self.props.bindResource
		}, function() {
			if (! isEmpty(self.state.boundResource) && self.props.schema) {
				self.validateAndRegisterFormAgainstSchema();
			} else {
				FormActions.registerForm(self.props.formKey, self.props.bindResource);
			}
		});
	},

	/**
	 * Form component receives props on every parent state change (when form fields are edited). On these events,
	 * we need to sync the form's resource with parent's state.
	 *
	 * @param nextProps
	 */
	componentWillReceiveProps: function (nextProps) {
		this.boundResource = nextProps.bindResource; // Sync form's resource with parent's state
		//FormActions.registerForm(this.props.formKey, this.props.bindResource); @todo is this needed?

		// Set the bound resource that will be passed down to child components
		this.setState({
			boundResource: nextProps.bindResource
		});
	},

	/**
	 * Master parent change handler for every child form field component.
	 *
	 * @param path
	 * @param value
	 * @param component
	 */
	handleChange: function (fieldKey, value, component) {
		var self = this;

		// If there's a schema, we validate using that
		if (self.props.schema) {
			// Clone the form's data to test against
			var form = _.cloneDeep(FormStore.getResource(self.props.formKey));

			// Set the value of the updated field locally so we can validate before saving
			_.set(form, fieldKey, value);

			// Test all the fields, including the locally-edited one
			var errors = self.validator.validate(form);

			// If there's errors returned from the validator, we set those fields to invalid
			if (errors) {
				var errorFields = self.getNestedFieldKeys(errors);

				errorFields.forEach(function(field) {
					FormActions.editField(self.props.formKey, field, _.get(form, field), false);
				});

				// If the errors don't include the field we editited, we save the value and set isValid to true
				if (! errorFields.includes(fieldKey)) {
					FormActions.editField(self.props.formKey, fieldKey, value, true);
				}

			// If there are no errors, we just save the edited field as valid
			} else {
				FormActions.editField(self.props.formKey, fieldKey, value, true)
			}

		// If there's no included schema, we proceed with saving the value using local validation
		} else {
			var isValid = self.validate(fieldKey, value);
			// Apply the change
			FormActions.editField(self.props.formKey, fieldKey, value, isValid);
		}
	},

	/**
	 * When there's a schema, handles validating the form and registering it.
	 *
	 * This is used to flag invalid fields on page-load
	 *
	 * @return {null}
	 */
	validateAndRegisterFormAgainstSchema: function() {
		var self = this,
			validations = {},
			isValid;

		// Clone the form's data to test against
		var resource = this.state.boundResource;

		// Test all the fields on the form
		var errors = self.validator.validate(resource);

		// If there's errors returned from the validator, we set those fields to invalid
		if (errors) {
			var errorFields = self.getNestedFieldKeys(errors);

			isValid = false;

			errorFields.forEach(function(field) {
				validations[field] = false;
			});
		}

		FormActions.registerForm(this.props.formKey, resource, validations, isValid);
	},

	/**
	 * Takes an object with infinitely nested values and grabs the paths to all values
	 *
	 * Example:
	 *	var obj = {a: 1, b: {c: 2}};
	 *	getNestedFieldKeys(obj); // ['a', 'b.c']
	 *
	 * @param {object} obj The object to be flattened
	 *
	 * @return {array}     An array of paths to all values on the object
	 */
	getNestedFieldKeys: function(obj) {
		var self = this;

		return Object.keys(obj).map(function(key) {
			if (typeof obj[key] === 'object') {
				return self.getNestedFieldKeys(obj[key]).map(function(deepKey) {
					return '{}.{}'.format(key, deepKey);
				});
			} else {
				return key;
			}
		}).reduce(function(array, value) {
			return array.concat(value);
		}, []);
	},

	// @todo this might be helpful to fully flesh out and use
	determineColumnSize: function () {
		var columns = React.Children.count(this.props.children);
		return Math.floor(12 / columns);
	},

	/**
	 * Handle attaching universal properties to all children
	 */
	componentWillMount: function () {
		this.traverseChildren(this.props.children);
	},

	componentWillUnmount: function () {
		this.boundResource = {}; // Clear bound resource
	},

	/**
	 * Container for all form field components. This is only for observation of child components, not for modifying them.
	 */
	formFields: {},

	/**
	 * Built upon http://christianalfoni.github.io/javascript/2014/10/22/nailing-that-validation-with-reactjs.html
	 *
	 * @param component
	 * @param value
	 */
	validate: function (fieldKey, value) {
		var formField = this.formFields[fieldKey];

		if (formField.required && (!value || value.length < 1)) {
			return false;
		}

		// If no validations, don't continue
		if (! formField.validations) {
			return true;
		}

		var isValid = true;

		if (value || (formField.required === true)) {
			// Parse the validations string
			formField.validations.split(',').forEach(function (validation) {
				var args = validation.split(':');
				var validationMethod = args.shift(); // ['isLength', 5] -> 'isLength'

				args = args.map(function (arg) {
					return JSON.parse(arg); // Coerce values to correct types
				});

				args = [value].concat(args);

				// Call validator with ['isValidationMethod', 'arg1', 'arg2']
				if (! validator[validationMethod].apply(validator, args)) {
					isValid = false;
				}
			});
		}

		// Call child component callback to set its state, and register the full form validator as a callback
		//component.setValidationState(isValid, this.validateForm); @todo set field validity state
		return isValid;
	},

	/**
	 * Validate form in full
	 */
	validateForm: function () {
		this.setState({
			isValid: FormStore.isFormValid()
		});
	},

	/**
	 * Dynamically (recursively) traverse every child component and set some universal properties for them.
	 *
	 * @param children
	 * @returns {*}
	 */
	traverseChildren: function (children) {
		return React.Children.map(children, function (child) {
			if (! child || ! child.props) {
				return child;
			}

			if (children.props && typeof children.props.changeCallback === 'function') {
				var changeCallback = children.props.changeCallback;
			} else {
				var changeCallback = this.handleChange;
			}

			if (child.props.fieldKey) {
				child = React.addons.cloneWithProps(child, {
					changeCallback: changeCallback,
					bindResource: this.props.bindResource,
					formKey: this.props.formKey
				});

				this.formFields[child.props.fieldKey] = {
					validations: child.props.validations || false,
					required: child.props.required ? true : false,
					isValid: FormStore.isFieldValid(this.props.formKey, child.props.fieldKey)
				}
			}

			if (child.props.children) {
				child = React.addons.cloneWithProps(child, {
					children: this.traverseChildren(child.props.children)
				});
			}

			return child;
		}.bind(this))
	},

	/**
	 * Determine if there's an onSubmit handler available
	 *
	 * @param event
	 */
	handleSubmit: function (event) {
		event.preventDefault();
		this.props.onSubmit ? this.props.onSubmit(event) : void(0);
	},

	render: function () {
		return (
			<form role="form" onSubmit={this.handleSubmit}>
				{this.traverseChildren(this.props.children)}
			</form>
		)
	}
});

// The currently available form components

// Layout
Form.Row             = Row;
Form.Column          = Column;
Form.Submit          = require('./Submit');

// Text Input
Form.Input           = require('./Input');
Form.FizzyWig        = require('./FizzyWig');
Form.TextArea        = require('./TextArea');
Form.TypeAheadInput  = require('./TypeAheadInput');

// Selection
Form.File            = require('./FileInput');
Form.Checkbox        = require('./Checkbox');
Form.SelectBox       = require('./SelectBox');
Form.RadioButtons    = require('./RadioButtons');
Form.DropdownSelect  = require('./DropdownSelect');

// Date && Time
Form.DatePicker      = require('./Time/DatePicker');
Form.TimePicker      = require('./Time/TimePicker');

module.exports = Form;
<|endoftext|>


<commit_before>"use strict";

const path = require("path");
const fs = require("fs");
const chalk = require("chalk");
const parse = require("..").parse;

function list_files(root, dir) {
  const files = fs.readdirSync(dir ? path.join(root, dir) : root);
  let result = [];
  for (let i = 0; i < files.length; i++) {
    const file = dir ? path.join(dir, files[i]) : files[i];
    const stats = fs.statSync(path.join(root, file));
    if (stats.isDirectory()) {
      result = result.concat(list_files(root, file));
    } else {
      result.push(file);
    }
  }
  return result.sort();
}

function get_tests(root_dir) {
  const files = list_files(root_dir);
  const tests = {};
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const test_name = path.dirname(file);
    const case_parts = path.basename(file).split(".");
    const case_name = case_parts[0];

    // Hack to ignore hidden files.
    if (case_name === "") {
      continue;
    }

    const cases = (tests[test_name] = tests[test_name] || {});
    const case_ = (cases[case_name] = cases[case_name] || {});

    const content = fs.readFileSync(path.join(root_dir, file), {
      encoding: "utf8",
    });
    const ext = case_parts[case_parts.length - 1];
    const kind =
      case_parts.length > 2 ? case_parts[case_parts.length - 2] : null;

    if (ext === "js") {
      case_.name = case_name;
      case_.content = content;
    } else if (ext === "json" && kind === "tree") {
      case_.expected_ast = JSON.parse(content);
    } else if (ext === "json" && kind === "options") {
      case_.options = JSON.parse(content);
    }
  }
  return tests;
}

function get_hardcoded_tests() {
  const tests = get_tests(
    path.join(__dirname, "../build/flow/src/parser/test/flow")
  );
  const result = {};
  for (const section in tests) {
    if (tests.hasOwnProperty(section)) {
      const test = tests[section];
      const cases = [];
      // TODO: use Object.values if we require new enough node
      for (const case_ in test) {
        if (test.hasOwnProperty(case_)) {
          cases.push(test[case_]);
        }
      }
      result[section] = { tests: cases };
    }
  }
  return result;
}

const options = {
  plugins: ["jsx", "flow", "asyncGenerators", "objectRestSpread"],
  sourceType: "module",
  ranges: true,
};

const flowOptionsMapping = {
  esproposal_class_instance_fields: "classProperties",
  esproposal_class_static_fields: "classProperties",
  esproposal_export_star_as: "exportExtensions",
  esproposal_decorators: "decorators",
};

let failedTests = 0;
let successTests = 0;
const hardcodedTests = get_hardcoded_tests();
Object.keys(hardcodedTests).forEach(sectionName => {
  console.log("");
  console.log(`### ${sectionName} ###`);
  hardcodedTests[sectionName].tests.forEach(test => {
    const shouldSuccess =
      test.expected_ast &&
      (!Array.isArray(test.expected_ast.errors) ||
        test.expected_ast.errors.length === 0);

    const babylonOptions = Object.assign({}, options);
    babylonOptions.plugins = babylonOptions.plugins.slice();

    if (test.options) {
      Object.keys(test.options).forEach(option => {
        if (!test.options[option]) return;
        if (!flowOptionsMapping[option])
          throw new Error("Parser options not mapped " + option);
        babylonOptions.plugins.push(flowOptionsMapping[option]);
      });
    }

    let failed = false;
    let exception = null;
    try {
      parse(test.content, babylonOptions);
    } catch (e) {
      exception = e;
      failed = true;
      // lets retry in script mode
      try {
        parse(
          test.content,
          Object.assign({}, babylonOptions, { sourceType: "script" })
        );
        exception = null;
        failed = false;
      } catch (e) {}
    }

    if ((!failed && shouldSuccess) || (failed && !shouldSuccess)) {
      successTests++;
      console.log(chalk.green(`✔ ${test.name}`));
    } else {
      failedTests++;
      printErrorMessage(
        test.name,
        exception,
        shouldSuccess,
        test.expected_ast,
        babylonOptions
      );
    }
  });
});

function printErrorMessage(
  code,
  exception,
  shouldSuccess,
  expectedAst,
  babylonOptions
) {
  console.log(chalk.red(`✘ ${code}`));
  console.log(
    chalk.yellow(
      `  Should ${shouldSuccess
        ? "parse successfully"
        : `fail parsing`}, but did not`
    )
  );
  if (exception)
    console.log(chalk.yellow(`  Failed with: \`${exception.message}\``));
  if (Array.isArray(expectedAst.errors) && expectedAst.errors.length > 0) {
    console.log(chalk.yellow("  Expected error message similar to:"));
    expectedAst.errors.forEach(error => {
      console.log(`    • ${error.message}`);
    });
  }

  console.log(
    chalk.yellow(`  Active plugins: ${JSON.stringify(babylonOptions.plugins)}`)
  );
}

console.log();
console.log(chalk.green(`✔ ${successTests} tests passed`));
console.log(chalk.red(`✘ ${failedTests} tests failed`));

process.exit(failedTests > 0 ? 1 : 0);
<commit_msg>Use a Map instead of an Obejct to store tests<commit_after>"use strict";

const path = require("path");
const fs = require("fs");
const chalk = require("chalk");
const parse = require("..").parse;

function map_get_default(map, key, defaultConstructor) {
  if (map.has(key)) {
    return map.get(key);
  }
  const value = new defaultConstructor();
  map.set(key, value);
  return value;
}

function list_files(root, dir) {
  const files = fs.readdirSync(dir ? path.join(root, dir) : root);
  let result = [];
  for (let i = 0; i < files.length; i++) {
    const file = dir ? path.join(dir, files[i]) : files[i];
    const stats = fs.statSync(path.join(root, file));
    if (stats.isDirectory()) {
      result = result.concat(list_files(root, file));
    } else {
      result.push(file);
    }
  }
  return result.sort();
}

function get_tests(root_dir) {
  const files = list_files(root_dir);
  const tests = new Map();
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const test_name = path.dirname(file);
    const case_parts = path.basename(file).split(".");
    const case_name = case_parts[0];

    // Hack to ignore hidden files.
    if (case_name === "") {
      continue;
    }

    const cases = map_get_default(tests, test_name, Map);
    const case_ = map_get_default(cases, case_name, Object);

    const content = fs.readFileSync(path.join(root_dir, file), {
      encoding: "utf8",
    });
    const ext = case_parts[case_parts.length - 1];
    const kind =
      case_parts.length > 2 ? case_parts[case_parts.length - 2] : null;

    if (ext === "js") {
      case_.name = case_name;
      case_.content = content;
    } else if (ext === "json" && kind === "tree") {
      case_.expected_ast = JSON.parse(content);
    } else if (ext === "json" && kind === "options") {
      case_.options = JSON.parse(content);
    }
  }
  return tests;
}

function get_hardcoded_tests() {
  const tests = get_tests(
    path.join(__dirname, "../build/flow/src/parser/test/flow")
  );
  const result = new Map();
  tests.forEach((section, sectionName) => {
    const cases = Array.from(section.values());
    result.set(sectionName, { tests: cases });
  });
  return result;
}

const options = {
  plugins: ["jsx", "flow", "asyncGenerators", "objectRestSpread"],
  sourceType: "module",
  ranges: true,
};

const flowOptionsMapping = {
  esproposal_class_instance_fields: "classProperties",
  esproposal_class_static_fields: "classProperties",
  esproposal_export_star_as: "exportExtensions",
  esproposal_decorators: "decorators",
};

let failedTests = 0;
let successTests = 0;
const tests = get_hardcoded_tests();
tests.forEach((section, sectionName) => {
  console.log("");
  console.log(`### ${sectionName} ###`);
  section.tests.forEach(test => {
    const shouldSuccess =
      test.expected_ast &&
      (!Array.isArray(test.expected_ast.errors) ||
        test.expected_ast.errors.length === 0);

    const babylonOptions = Object.assign({}, options);
    babylonOptions.plugins = babylonOptions.plugins.slice();

    if (test.options) {
      Object.keys(test.options).forEach(option => {
        if (!test.options[option]) return;
        if (!flowOptionsMapping[option])
          throw new Error("Parser options not mapped " + option);
        babylonOptions.plugins.push(flowOptionsMapping[option]);
      });
    }

    let failed = false;
    let exception = null;
    try {
      parse(test.content, babylonOptions);
    } catch (e) {
      exception = e;
      failed = true;
      // lets retry in script mode
      try {
        parse(
          test.content,
          Object.assign({}, babylonOptions, { sourceType: "script" })
        );
        exception = null;
        failed = false;
      } catch (e) {}
    }

    if ((!failed && shouldSuccess) || (failed && !shouldSuccess)) {
      successTests++;
      console.log(chalk.green(`✔ ${test.name}`));
    } else {
      failedTests++;
      printErrorMessage(
        test.name,
        exception,
        shouldSuccess,
        test.expected_ast,
        babylonOptions
      );
    }
  });
});

function printErrorMessage(
  code,
  exception,
  shouldSuccess,
  expectedAst,
  babylonOptions
) {
  console.log(chalk.red(`✘ ${code}`));
  console.log(
    chalk.yellow(
      `  Should ${shouldSuccess
        ? "parse successfully"
        : `fail parsing`}, but did not`
    )
  );
  if (exception)
    console.log(chalk.yellow(`  Failed with: \`${exception.message}\``));
  if (Array.isArray(expectedAst.errors) && expectedAst.errors.length > 0) {
    console.log(chalk.yellow("  Expected error message similar to:"));
    expectedAst.errors.forEach(error => {
      console.log(`    • ${error.message}`);
    });
  }

  console.log(
    chalk.yellow(`  Active plugins: ${JSON.stringify(babylonOptions.plugins)}`)
  );
}

console.log();
console.log(chalk.green(`✔ ${successTests} tests passed`));
console.log(chalk.red(`✘ ${failedTests} tests failed`));

process.exit(failedTests > 0 ? 1 : 0);
<|endoftext|>