Skip to content

Instantly share code, notes, and snippets.

@yonatanmn
Last active June 29, 2016 13:01
Show Gist options
  • Save yonatanmn/aa2db585f0c7379b7126259eb04f1eee to your computer and use it in GitHub Desktop.
Save yonatanmn/aa2db585f0c7379b7126259eb04f1eee to your computer and use it in GitHub Desktop.
create square of numbers - look at result file
function addBeforeAfter(arr, item){
return [item].concat(arr).concat([item])
}
function createLine(counter, min){
const minNum = Math.max(counter, min);
return counter > 1 ? addBeforeAfter(createLine(counter - 1, min), minNum) : [minNum]
}
function createSquare(counter, max){
const line = createLine(max, counter);
return counter > 1 ? addBeforeAfter(createSquare(counter - 1, max), line) : [line]
}
function run(n){
return createSquare(n, n)
.map(line => line.join(''))
.join('\n')
}
console.log(run(3));
console.log(run(7));
function recursionFactory(baseObjFunc){
return function recursive(counter, limit){
const base = baseObjFunc(limit, counter);
return counter > 1 ? [base].concat(recursive(counter - 1, limit)).concat([base]) : [base];
}
}
const createLine = recursionFactory(Math.max);
const createSquare = recursionFactory(createLine);
function run(n){
return createSquare(n, n)
.map(line => line.join(''))
.join('\n')
}
console.log(run(3));
console.log(run(7));
run(3) :
33333
32223
32123
32223
33333
run(7):
7777777777777
7666666666667
7655555555567
7654444444567
7654333334567
7654322234567
7654321234567
7654322234567
7654333334567
7654444444567
7655555555567
7666666666667
7777777777777
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment