Created
December 15, 2016 21:10
-
-
Save RomanMinkin/8f23594c93b51dc07380a290627fa973 to your computer and use it in GitHub Desktop.
Simple Node.js program which accepts a string of JSON array, make it flat and returns as a string in stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
'use strict'; | |
// Program accepts only json array string on stdin | |
// You need node.js with version >= v6.2.2 | |
// Examples of usage: | |
// | |
// $ echo "[1,2,[3,4],[5,[6],7],8]" | node flatten.js | |
// [1,2,3,4,5,6,7,8] | |
// | |
// $ echo "[1, [2,3], [4,[5,[6]]]]" | node flatten.js | |
// [1,2,3,4,5,6] | |
// | |
// $ echo "{data: "wrong input" }" | node flatten.js | |
// Not a valid JSON array format! | |
// Example: 'echo "[1,2,[3],4]" | node flatten.js' | |
// | |
var stdin = process.stdin, | |
stdout = process.stdout, | |
stderr = process.stderr, | |
data = []; | |
var flatten = function flatten(arr) { | |
return arr.reduce(function (a, b) { | |
return a.concat(Array.isArray(b) ? flatten(b) : b); | |
}, []); | |
}; | |
stdin.resume(); | |
stdin.setEncoding('utf8'); | |
stdin.on('data', function (chunk) { | |
data.push(chunk); | |
}); | |
stdin.on('end', function () { | |
var inputJSON = data.join(), | |
parsedData, | |
output; | |
try { | |
parsedData = JSON.parse(inputJSON); | |
if (!Array.isArray(parsedData)) { | |
throw 'not an array' | |
} | |
} catch(e) { | |
stderr.write('Not a valid JSON array format!\n'); | |
stderr.write('Example: \'echo "[1,2,[3],4]" | node flatten.js\'\n'); | |
process.exit(1) | |
} | |
output = JSON.stringify(flatten(parsedData), null, '') | |
stdout.write(output) | |
stderr.write('\n'); | |
process.exit() | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment