aboutsummaryrefslogtreecommitdiff
path: root/challenge-131/iangoodnight/javascript/ch-1.js
blob: 69192e05fe2ff745bdc9bff6663d79f823c49e75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env node
// ch-1.js

/**
 * https://theweeklychallenge.org/blog/perl-weekly-challenge-131/
 *
 * Task 1 > Consecutive Arrays
 * ===========================
 *
 * You are given a sorted list of unique positive integers.
 *
 * Write a script to return lists of arrays where the arrays are consecutive
 * integers.
 *
 * Example 1:
 *
 * const input = [1, 2, 3, 6, 7, 8, 9];
 *
 * const output =[[1, 2, 3], [6, 7, 8, 9]];
 *
 * Example 2:
 *
 * const input = [11, 12, 14, 17, 18, 19];
 *
 * const output = [[2], [4], [6], [8]];
 *
 * Example 3:
 *
 * const input = [2, 4, 6, 8];
 *
 * const output = [[2], [4], [6], [8]];
 *
 * Example 4:
 *
 * const input = [1, 2, 3, 4, 5];
 *
 * const output = [[1, 2, 3, 4, 5]];
 **/

'use strict';

/**
 * Node built-in dependencies (required for test runner)
 **/

const fs = require('fs');

const path = require('path');

/**
 * Here, our Consecutive Array Reducer (PWC Solution)
 **/

function reduceToConsecutive(input = []) {
  return input.reduce((reduced, element) => {
    // If no arrays in `reduced`, initialize our first set and return.
    if (reduced.length === 0) return [[element]];
    // Otherwise, pop off the last set for inspection.
    const lastSet = reduced.pop();
    // Take a copy of the last value.
    const [ last ] = lastSet.slice(-1);
    // if the last value is equal to one less than our current value, push it
    // to the last set and push our last set back into our `reduced` array.
    if (last === element - 1) {
      lastSet.push(element);
      reduced.push(lastSet);
    } else {
      // Else, push our unaltered last set, and our new set back to the array.
      reduced.push(lastSet, [element]);
    }
    return reduced;
  }, []);
}

/**
 * Followed by some utilities to test our solution
 **/

function evalInput(input = '') {
  if (input.indexOf('[') === -1) {
    // No inner sets, input string, split and return
    return input
      .replace(/\(|\)/g, '')
      .split(/\s*,\s*/)
      .map((element) => parseInt(element)
    );
  }
  // Else, answer string, parse and return
  return [...input.matchAll(/\[([^\]]*)\]/g)].map(match =>
    match[1].split(/\s*,\s*/).map(el => parseInt(el))
  );
}

function parseTestCase(filePath = '') {
  try {
    const data = fs.readFileSync(filePath, 'utf8');

    const [ inputsArray, answersArray ] = data.split('\n').reduce(
      ([inputs, tests], line) => {
        const trimmed = line.trim();
        // Discard comments and blank lines
        if (trimmed.charAt(0) === '#' || trimmed.length === 0) {
          return [inputs, tests];
        }
        // Parse line
        const parsed = evalInput(trimmed);
        // if inputs greater than tests, assume line is a test
        if (inputs.length > tests.length) return [inputs, [...tests, parsed]];
        // else, push parsed to inputs
        return [[...inputs, parsed], tests];
      },
      [[], []]
    );
    // Grab lengths for comparison conveniences
    const { length: inputLength } = inputsArray;

    const { length: answerLength } = answersArray;
    // Sanity check
    if (
      inputLength === 0 ||
      answerLength === 0 ||
      inputLength !== answerLength
    ) {
      // Something went wrong parsing the test cases
      throw new Error (
        `Found ${inputLength} inputs and ${answerLength} answers.`
      );
    }
    return [inputsArray, answersArray];
  } catch (error) {
    console.log(`Problems parsing test case(s) at: ${filePath}`);
    console.log(error);
  }
}

function assertMatch(set1 = [], set2 = []) {
  return set1.reduce((match, element, idx) => {
    // Already failed, return
    if (!match) return false;
    // just for conveniance
    const array = Array.isArray(element);

    const compare = set2[idx];
    // Fails
    if (!array && element !== compare) return false;
    // Recurse
    if (array) return assertMatch(element, set2[idx]);
    // Passes
    return match;
  }, true);
}

function printResults(testPath = '', inputs = [], expected = []) {
  console.log(testPath);
  console.log('='.repeat(testPath.length), '\n');
  // Iterates through and print relevant test data.
  inputs.forEach((input, idx) => {
    console.log(`Input: ${JSON.stringify(input)}`);
    console.log(`Expected: ${JSON.stringify(expected[idx])}`);
    const result = reduceToConsecutive(input);
    // Check for match
    console.log(`Result: ${JSON.stringify(result)}`);
    if (assertMatch(expected[idx], result)) {
      console.log('\x1b[32m%s\x1b[0m', 'Passed \u2690');
    } else {
      console.log('\x1b[31m%s\x1b[0m', 'Failed \u2715');
    }
    console.log('\n');
  });
}

const isFile = (filePath) => fs.lstatSync(filePath).isFile();

const isDirectory = (filePath) => fs.lstatSync(filePath).isDirectory();

/**
 * And our test runner
 **/

(function main() {
  const testPath = process.argv[2] || '../test_cases/ch-1';
  // Handle single file inputs
  try {
    if (isFile(testPath)) {
      const [ inputs, tests ] = parseTestCase(testPath);

      return printResults(testPath, inputs, tests);
      // Else, handle directory inputs
    } else if (isDirectory(testPath)) {
      fs.readdirSync(testPath).forEach(fileName => {
        const filePath = path.join(testPath, fileName);

        const [ inputs, tests ] = parseTestCase(filePath);

        printResults(filePath, inputs, tests);
        // Else, no tests found
      });
      return;
    } else {
      console.log('No tests found');
    }
  } catch (error) {
    console.log('Something went wrong: ', error);
  }
})();