Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let testCases = [
- [[1,2,3,4,4,5,1,4,2], 3],
- [[3,4,4,2], 2],
- [[,2,3,4,1], 1],
- [[9,1,2], 2],
- [[], 0],
- [[undefined, undefined], 0],
- [null, 0],
- ];
- //
- testCases.forEach(testRunner(build));
- //
- function build(terrain) {
- terrain = terrain || [];
- let castleCount = terrain.reduce(([castleCount, sidecar], current) => {
- switch (sidecar.length) {
- case 0: {
- return [castleCount, [current]];
- };
- case 1: {
- let [lastEntry] = sidecar;
- return lastEntry == current
- ? [castleCount, sidecar]
- : [castleCount, [...sidecar, current]];
- };
- case 2: {
- /**
- * [1 , 9]
- * [9, 1]
- */
- let [start, middle] = sidecar;
- let isValley = (middle < start) && (middle < current);
- let isPeak = (middle > start) && (middle > current);
- return (isPeak || isValley)
- ? [castleCount+1, [current]]
- : [castleCount, sidecar];
- }
- }
- }, [0, []])[0];
- return Boolean(terrain[0])
- ? castleCount+1
- : castleCount;
- }
- function testRunner(testFunc) {
- return ([input, expectedOutput]) => {
- let actualOutput = build(input);
- if(actualOutput === expectedOutput) {
- console.log("Test passed.");
- } else {
- console.log("Test failed.")
- }
- console.log("input: ", input);
- console.log("expectedOutput: ", expectedOutput);
- console.log("actualOutput: ", actualOutput);
- console.log("===========");
- }
- }
Add Comment
Please, Sign In to add comment