Skip to content

Instantly share code, notes, and snippets.

@neosavvy
Created March 2, 2018 20:41
Show Gist options
  • Save neosavvy/b01788cf7d95086aed415c0d9b06386a to your computer and use it in GitHub Desktop.
Save neosavvy/b01788cf7d95086aed415c0d9b06386a to your computer and use it in GitHub Desktop.
Example Interview Question
// ==================
// Utility code start
// ==================
var Readable = require('stream').Readable;
var util = require('util');
/**
* Stream which returns numbers in ascending sorted order.
*
* @param {Number} initialNum The first number
* @param {Number} numbersInStream The total number of sorted numbers
* in the stream.
* @constructor
*/
function SortedNumberStream(initialNum, numbersInStream) {
this._count = 0;
this._previousNum = initialNum;
this._numbersInStream = numbersInStream;
Readable.call(this, {objectMode: true});
};
util.inherits(SortedNumberStream, Readable);
/**
* Generate the next number in the sorted sequence.
*
* @returns {null}
* @private
*/
SortedNumberStream.prototype._read = function () {
if (this._count === this._numbersInStream) {
this.push(null);
} else {
this.push(this._previousNum);
this._previousNum += randomIntFromInterval(0, 20);
this._count++;
}
};
SortedNumberStream.prototype.getStreamSize = function() {
return this._numbersInStream;
}
/**
* Utility function to generate a random number within a range.
*
* @param {Number} min The minimum number in the range, inclusive.
* @param {Number} max The maximum number in the range, inclusive.
* @returns {number}
*/
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// ====================
// Candidate code start
// ====================
var streams = [
new SortedNumberStream(5, 10),
new SortedNumberStream(19, 15),
new SortedNumberStream(0, 7)
];
// A SortedNumberStream contains numbers in ascending order.
// Write an algoritm to sort the numbers in all of the streams
// and output them to a file, stdout, or another stream.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment