For a loop has different meanings inside vs outside the loop

I am trying to make a complex calculation of interest with a recession in an arbitrary year. The following promise function calculates the development of a portfolio of variables.

EDITING FOR BRIGHTNESS:

  • const recessionsis an array that repeats cyclically from 1 to 20 ( recseverityis static)
  • Triple ( thisyear == recyear) starts every year every time, which leads to a 50% decrease portfolioin different years

const chunk = ( horizon, principal, roi, recyear, recseverity ) => { 
	return new Promise( resolve => {
		// Decimalise and create portfolio holder
		let portfolio = principal
		let crash = 1 - ( recseverity / 100 )
		let grow = 1 + ( roi / 100 )

		// Loop over the years and crash or grow
		for (let thisyear = 1; thisyear < horizon +1; thisyear++) {
			thisyear == recyear ? ( portfolio *= crash ) : ( portfolio *= grow )
			console.log( portfolio )
		}
		console.log( 'last', portfolio )

		// Resolve with the outcome
		resolve( { year: recyear, result: portfolio } )
	} )
}

const horizon = 20
const principal = 100
const roi = 7
const recseverity = 50
const yearlyadd = principal/horizon

const recessions = []
for (let year = 1; year < horizon +1; year++) {
	recessions.push( { year: year, severity: recseverity } )
}

Promise.all( recessions.map( recession => chunk( horizon, principal, roi, recession.year, recession.severity ) ) )
.then( console.log.bind( console ) )
Run codeHide result

The kicker is that everything goes perfectly, except that the end result of the portfolio variable is a value that makes no sense to me. ALL FROM THEM are returned 180.82637675169082.

console.log, for , 180.82637675169082. .

:

[ { year: 1, result: 180.82637675169082 },
  { year: 2, result: 180.82637675169082 },
  { year: 3, result: 180.82637675169082 },
  { year: 4, result: 180.82637675169082 },
  { year: 5, result: 180.82637675169082 },
  { year: 6, result: 180.82637675169082 },
  { year: 7, result: 180.82637675169082 },
  { year: 8, result: 180.82637675169082 },
  { year: 9, result: 180.82637675169082 },
  { year: 10, result: 180.82637675169082 },
  { year: 11, result: 180.82637675169082 },
  { year: 12, result: 180.82637675169082 },
  { year: 13, result: 180.82637675169082 },
  { year: 14, result: 180.82637675169082 },
  { year: 15, result: 180.82637675169082 },
  { year: 16, result: 180.82637675169082 },
  { year: 17, result: 180.82637675169082 },
  { year: 18, result: 180.82637675169082 },
  { year: 19, result: 180.82637675169082 },
  { year: 20, result: 180.82637675169082 } ]
Hide result

console.log, , - , . , 180.82637675169082.

+4
2

.

, , .

: , X , , 10 .

, .

PBKAC.

, .

+1

, , , ,

            thisyear == recyear ? ( portfolio *= crash ) : ( portfolio *= grow )

var thisyear recyear , , < < →

, recyear ,

, , ,

0

Source: https://habr.com/ru/post/1691361/


All Articles