{"size": 1119, "ext": "js", "max_stars_repo_path": "test/test_critical_section.js", "max_stars_repo_name": "e-neko/OpenBalkans", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_critical_section.js", "max_issues_repo_name": "e-neko/OpenBalkans", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_critical_section.js", "max_forks_repo_name": "e-neko/OpenBalkans", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.8085106383, "max_line_length": 87, "alphanum_fraction": 0.527256479}
'use strict'

const assert = require('assert')

const sleep = pause => new Promise(resolve => setTimeout(resolve, pause))

exports.testNoCriticalSection = async function testNoCriticalSection() {
    const stack = []

    function a() {
        return Promise.resolve()
            .then(() => sleep(200))
            .then(() => stack.push(1))
    }

    function b() {
        return Promise.resolve()
            .then(() => sleep(100))
            .then(() => stack.push(2))
    }

    await Promise.all([a(), b()])
    assert.deepStrictEqual(stack, [2, 1])
}

exports.testCriticalSection = async function testCriticalSection({ CriticalSection }) {
    const pcs = new CriticalSection
    const stack = []

    function a() {
        return pcs.enter()
            .then(() => sleep(200))
            .then(() => stack.push(1))
            .then(() => pcs.leave())
    }

    function b() {
        return pcs.enter()
            .then(() => sleep(100))
            .then(() => stack.push(2))
            .then(() => pcs.leave())
    }

    await Promise.all([a(), b()])
    assert.deepStrictEqual(stack, [1, 2])
}
