Created
January 2, 2017 20:36
-
-
Save deniskyashif/46ab2f5dca0cd3fb932036e545e3e299 to your computer and use it in GitHub Desktop.
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
/* | |
The problem: define functions range, map, reverse and foreach, obeying the restrictions below, such that the following program works properly. | |
It prints the squares of numbers from 1 to 10, in reverse order. | |
You must not use arrays. The square bracket characters, [ and ], are forbidden, as well as new Array. | |
You must not use objects. The curly braces, { and }, and the dot character (.) are forbidden. You may use curly braces for code blocks, but not for creating JavaScript objects. | |
Should go without saying, these functions must be generic and do what their name implies. They must not be hard-coded for the particular 1..10 example. | |
*/ | |
function convertArgsToArray(...args) { | |
return args; | |
} | |
function getArrayLength(arr) { | |
let count = 0; | |
for(let num of arr) { | |
count++; | |
} | |
return count; | |
} | |
function prepend(str, item) { | |
return item + str; | |
} | |
function append(str, item) { | |
return str + item; | |
} | |
function range(from, to) { | |
let argsAsString = ''; | |
for(let i = from; i <= to; i++) { | |
argsAsString = append(argsAsString, i + (i < to ? ',': '')); | |
} | |
return eval(`convertArgsToArray(${argsAsString});`); | |
} | |
function foreach(arr, action) { | |
for(let num of arr) { | |
action(num); | |
} | |
} | |
function map(arr, func) { | |
let argsAsString = ''; | |
let count = getArrayLength(arr); | |
let i = 0; | |
for(let item of arr) { | |
argsAsString = append(argsAsString, `${func(item)}${(i++ < (count - 1) ? ',' : '')}`); | |
} | |
return eval(`convertArgsToArray(${argsAsString});`); | |
} | |
function reverse(arr) { | |
let argsAsString = ''; | |
let i = 0; | |
for(let item of arr) { | |
if (i > 0) { | |
argsAsString = prepend(argsAsString, ','); | |
} else { | |
i++; | |
} | |
argsAsString = prepend(argsAsString, item); | |
} | |
return eval(`convertArgsToArray(${argsAsString});`); | |
} | |
let numbers = range(1, 10); | |
numbers = map(numbers, x => x*x); | |
numbers = reverse(numbers); | |
foreach(numbers, console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment