HardPro challengeJavaScriptTypeScript
Observable (map / filter / take)
BackendDesign
Implement a minimal synchronous Observable class:
Observable.of(...values)— static factory from a list of values.obs.map(fn)— returns a new Observable applyingfnto each value.obs.filter(fn)— returns a new Observable keeping values wherefnis truthy.obs.take(n)— returns a new Observable with at mostnvalues.obs.subscribe({ next })— executes the chain synchronously, callingnextfor each value.
solve applies a declarative operator chain to a values array.
Operators: ['map', expr], ['filter', expr], ['take', n] whereexpr is an arrow function string compiled with new Function.
Sample tests
Test #1map doubles values
Input: [[["map","x => x * 2"]],[1,2,3,4]]
Output: [2,4,6,8]
Test #2filter keeps even numbers
Input: [[["filter","x => x % 2 === 0"]],[1,2,3,4,5,6]]
Output: [2,4,6]
Test #3take limits output
Input: [[["take",3]],[10,20,30,40,50]]
Output: [10,20,30]
Test #4Chained map+filter+take
Input: [[["map","x => x * 2"],["filter","x => x > 4"],["take",2]],[1,2,3,4,5]]
Output: [6,8]
Test #5No operators passes through
Input: [[],[1,2,3]]
Output: [1,2,3]