'use strict';

const metasync = require('..');
const metatests = require('metatests');

metatests.test('succesfull map', test => {
  test.plan(2);

  const arr = [1, 2, 3];
  const expectedArr = [2, 4, 6];

  metasync.asyncMap(arr, item => item * 2, (err, newArr) => {
    test.error(err);
    test.strictSame(newArr, expectedArr);
  });
});

const doSmth = time => {
  const begin = Date.now();
  while (Date.now() - begin < time);
};

metatests.test('Non-blocking', test => {
  const ARRAY_SIZE = 1000;
  const MIN_IO_CALLS = 90;
  const MAX_IO_CALLS = 110;

  let ioCallsCount = 0;
  const arr = new Array(ARRAY_SIZE).fill(1);

  const timer = setInterval(() => {
    doSmth(9);
    ioCallsCount++;
  }, 1);

  metasync.asyncMap(arr, () => doSmth(1),
    { percent: 0.5 }, () => {
      clearInterval(timer);
      test.assert(ioCallsCount >= MIN_IO_CALLS);
      test.assert(ioCallsCount <= MAX_IO_CALLS);
      test.end();
    });
});


@@ -483,25 +483,21 @@
 nst 
-ARRAY_SIZ
+ITEM_TIM
 E = 1
-000
 ;%0A  
@@ -506,25 +506,22 @@
 nst 
-MIN_IO_CALLS
+TIMER_TIME
  = 9
-0
 ;%0A  
@@ -530,52 +530,93 @@
 nst 
-MAX_IO_CALLS
+ARRAY_SIZE
  = 1
-1
+00
 0;%0A
-%0A
   
-let ioCallsCount = 0;
+const EXPECTED_PERCENT = 0.5;%0A  const EXPECTED_DEVIATION = 0.2;%0A
 %0A  c
@@ -695,22 +695,16 @@
 ) =%3E
- %7B%0A   
  doSmth(
 9);%0A
@@ -703,42 +703,54 @@
 mth(
-9);%0A    ioCallsCount++;%0A  %7D, 1
+TIMER_TIME), 1);%0A%0A  const begin = Date.now(
 );%0A
-%0A
   me
@@ -783,17 +783,25 @@
  doSmth(
-1
+ITEM_TIME
 ),%0A    %7B
@@ -810,19 +810,32 @@
 ercent: 
-0.5
+EXPECTED_PERCENT
  %7D, () =
@@ -870,103 +870,273 @@
 r);%0A
+%0A
       
-test.assert(ioCallsCount %3E= MIN_IO_CALLS);%0A      test.assert(ioCallsCount %3C= MAX_IO_CALLS
+const mapTime = ITEM_TIME * ARRAY_SIZE;%0A      const allTime = Date.now() - begin;%0A      const actualPercent = mapTime / allTime;%0A      const actualDeviation = Math.abs(actualPercent - EXPECTED_PERCENT);%0A      test.assert(actualDeviation %3C= EXPECTED_DEVIATION
 );%0A 

Fix asyncMap function test