-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcalculator.js
1315 lines (1077 loc) · 54.2 KB
/
calculator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** ************* CALCULATOR JS FUNCTIONS *************************/
//= ==========================================================
// see also: https://github.com/jfoclpf/autocosts/wiki/Calculate-Costs-core-function
// CALCULATOR MODULE
// see our module template: https://github.com/jfoclpf/autocosts/blob/master/contributing.md#modules
// This file is used both by the browser and by node/commonsJS, the latter being called by getAvgFromDB.js
/* eslint prefer-const: "off" */
/* eslint no-var: "off" */
// Check if current script is being run by NodeJS
if (typeof process === 'object' && String(process) === '[object process]') {
// In node initialize main object to avoid error. Object is set to {},
// but no problem because in Node, different modules don't share the same global scope
var autocosts = {}
}
autocosts.calculatorModule = (function (thisModule) {
var conversionsModule
var inputData // input data object, obtained from user HTML form or from database entry
var calculatedData // output object
var consoleError
var consts = {
numberOfDaysInAYear: 365.25,
numberOfDaysInAWeek: 7,
numberOfMonthsInAYear: 12,
numberOfWeeksInAYear: 365.25 / 7,
numberOfWeeksInAMonth: 365.25 / 12 / 7
}
// says if some calculated results are likely to be valid
var isLikelyToBeValidConst = {
financialEffortPercentage: {
min: 2,
max: 110
}
}
var errMsgDataCountry = 'inputData or calculatedData not defined. Initializtion functions not run'
function initialize () {
loadModuleDependencies()
if (typeof window === 'undefined') { // nodeJS
consoleError = require('debug')('calculator')
} else { // browser
consoleError = console.error
}
}
function loadModuleDependencies () {
if (typeof window === 'undefined') { // node
conversionsModule = require('./conversions')
} else { // browser
conversionsModule = autocosts.calculatorModule.conversionsModule
}
}
// private method, to be called by calculateCosts()
function initializeCalculatedData () {
if (!isObjectDefined(inputData)) {
throw Error(errMsgDataCountry)
}
// object to be returned by the function calculateCosts
// for the object full structure see: https://github.com/jfoclpf/autocosts/wiki/Calculate-Costs-core-function#output
calculatedData = CreateCalculatedDataObj() // calculatedData is global to this module
initializeCalculatedDataObj()
}
// Object Constructor for the Results, where the calculated averages are stored
// see: https://github.com/jfoclpf/autocosts/blob/master/contributing.md#calculateddata-class
// because it is a constructor, first letter is capital
function CreateCalculatedDataObj () {
var u; u = undefined
return {
countryCode: u,
currency: u,
costs: {
totalPerYear: u,
totalEver: u,
perMonth: {
items: {
depreciation: u,
insurance: u,
credit: u,
inspection: u,
roadTaxes: u,
fuel: u,
maintenance: u,
repairsImprovements: u,
parking: u,
tolls: u,
fines: u,
washing: u
},
standingCosts: u,
runningCosts: u,
total: u
},
perUnitDistance: { // "km", "mile", etc.
runningCosts: u,
totalCosts: u
}
},
speeds: {
averageKineticSpeed: u,
averageConsumerSpeed: u // see for more details
// https://github.com/jfoclpf/autocosts/wiki/Kinetic-speed-vs.-Consumer-speed
},
publicTransports: {
calculated: false, // boolean whether the public transports info was calculated
toBeDisplayed: u, // boolean whether makes sense to display public transports
totalCostsOfStandardPublicTransports: u, // total costs of public transports in the city with monthly pass
furtherPublicTransports: { // further alternative public transports (train, outside residence city, etc.),
display: false, // boolean for further alternative public transports
totalCosts: u // costs set to these further public transports
},
taxi: {
totalCosts: u, // usage of taxi as an alternative to car
costPerUnitDistance: u, // average price of taxi per unit distance
possibleDistanceDoneByTaxi: u // km/miles/etc. that could be done by taxi with amount of this.taxiCosts
},
totalAlternativeCostsWhenUserHasNoCar: u, // total alternative costs by not having a car
ratios: {
ptCostsOverCarCosts: u, // public transports over car costs ratio
// ratio (costs of public transports)/(car costs) under which it shows public transports as alternative
showPt: u,
// ratio (costs of public transports)/(car costs) under which shows other alternatives,
// with further public transports (intercity trains for example)
showFurtherPt: u
}
},
financialEffort: {
calculated: false, // boolean whether the public transports info was calculated
isLikelyToBeValid: false, // says if this result is likely to be valid
income: {
calculated: false,
averagePerHour: u,
averagePerWeek: u,
averagePerMonth: u,
perYear: u
},
workingTime: {
calculated: false,
hoursPerWeek: u, // hours of work per week
weeksPerYear: u, // weeks of work per year
monthsPerYear: u, // months of work per year
hoursPerMonth: u, // average total working hours per month
hoursPerYear: u // average total working hours per year
},
totalCarCostsPerYear: u, // total costs per year
workingHoursPerYearToAffordCar: u, // hours per year to afford the car
workingMonthsPerYearToAffordCar: u, // months per year to afford the car
daysForCarToBePaid: u, // number of days till the car is paid
financialEffortPercentage: u // percentage of income that car costs represent
},
drivingDistance: {
calculated: false, // boolean
perWeek: u, // average distance driven per month
perMonth: u, // total distance driven per month
perYear: u, // total distance driven per year
betweenHomeAndJob: u, // distance between home and job (one-way)
duringEachWeekend: u // distance the user drives during weekend
},
timeSpentInDriving: {
calculated: false, // boolean
minutesBetweenHomeAndJob: u, // time (in minutes) driven between home and job
minutesInEachWeekend: u, // time (in minutes) driven during weekends
minutesPerWeek: u, // time (in minutes) driven per week
minutesPerDay: u, // time (in minutes) driven per day
daysPerMonth: u, // number of days driven per month
hoursPerMonth: u, // number of hours driven per month
hoursPerYear: u // number of hours driven per year
},
externalCosts: {
calculated: false, // boolean
handbookOfeExternalCostsURL: u,
pollution: u,
greenhouseGases: u,
noise: u,
fatalities: u,
congestion: u,
infrastructure: u,
total: u
},
details: {
numberOfDaysPerWeekUserDrivesToJob: u, // number of days per week, the user drives to job
ageOfCarInMonths: u,
credit: {
numberOfMonthlyInstalments: u,
totalPaidInInterests: u
}
},
// see https://github.com/jfoclpf/autocosts/blob/master/contributing.md#standards
// standard units applicable to the whole object
standardUnits: {
speed: u, // type string: km/h, mi/h, mil(10km)/h
distance: u, // type string: km, mi, mil(10km)
fuelEfficiency: u, // type string: L/100km, km/L, etc.
fuelPriceVolume: u // type string: L, gal(imp) or gal(US)
}
}
}
// calculatedData and inputData are global to this module
function initializeCalculatedDataObj () {
if (!isObjectDefined(calculatedData) || !isObjectDefined(inputData)) {
throw Error(errMsgDataCountry)
}
calculatedData.countryCode = inputData.countryCode
calculatedData.currency = inputData.currency
// decide what Standard Distance Unit to use according to user input
if (inputData.fuel.typeOfCalculation === 'distance') {
checkBoolean(inputData.fuel.distanceBased.considerCarToJob)
if (inputData.fuel.distanceBased.considerCarToJob) {
calculatedData.standardUnits.distance = inputData.fuel.distanceBased.carToJob.distanceStandardUnit
} else {
calculatedData.standardUnits.distance = inputData.fuel.distanceBased.noCarToJob.distanceStandardUnit
}
} else if (inputData.fuel.typeOfCalculation === 'money') {
/* gets distance from section distance when available */
if (typeof inputData.distance.considerCarToJob === 'boolean') {
if (inputData.distance.considerCarToJob) {
calculatedData.standardUnits.distance = inputData.distance.carToJob.distanceStandardUnit
} else {
calculatedData.standardUnits.distance = inputData.distance.noCarToJob.distanceStandardUnit
}
} else {
calculatedData.standardUnits.distance = null
}
} else {
throw Error('invalid fuel.typeOfCalculation: ' + inputData.fuel.typeOfCalculation)
}
if (calculatedData.standardUnits.distance) {
calculatedData.standardUnits.distance = conversionsModule.mapUnit('distance', calculatedData.standardUnits.distance)
// standard speed
calculatedData.standardUnits.speed = calculatedData.standardUnits.distance + '/h'
}
// standard fuelEfficiency: type string: L/100km, km/L, etc
calculatedData.standardUnits.fuelEfficiency = conversionsModule.mapUnit('fuelEfficiency',
inputData.fuel.distanceBased.fuelEfficiencyStandard)
// standard fuelPriceVolume: type string: L, gal(imp) or gal(US)
calculatedData.standardUnits.fuelPriceVolume = conversionsModule.mapUnit('fuelPriceVolume',
inputData.fuel.distanceBased.fuelPriceVolumeStandard)
}
// return the difference in months between two dates dateTo-dateFrom
// if dateFrom is after dateTo returns null
function differenceBetweenDates (dateFrom, dateTo) {
var numberOfMonths = dateTo.getMonth() - dateFrom.getMonth() + (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
if (numberOfMonths > 0) {
return numberOfMonths
} else if (numberOfMonths === 0) {
/* to avoid divisions by zero in the depreciation,
allowing user to use the calculator on the month he bought the car */
return 1
} else {
return null
}
}
function calculateMonthlyDepreciation (depreciation, ageInMonths) {
return (depreciation.dateOfAcquisition.valueOfTheVehicle - depreciation.dateOfUserInput.valueOfTheVehicle) / ageInMonths
}
function calculateInsuranceMonthlyValue (insurance) {
return getMonthlyAmount(insurance.amountPerPeriod, insurance.period)
}
function calculateInterestsMonthlyValue (credit, ageInMonths) {
var monthlyCost
var totalInterests
var numberOfMonthlyInstalments
if (typeof credit.creditBool !== 'boolean') {
throw (Error('Error calculating credit'))
}
if (credit.creditBool) { // if there was credit
numberOfMonthlyInstalments = parseInt(credit.yesCredit.numberInstallments, 10)
var amountInstallment = credit.yesCredit.amountInstallment
var residualValue = credit.yesCredit.residualValue
var borrowedAmount = credit.yesCredit.borrowedAmount
totalInterests = (numberOfMonthlyInstalments * amountInstallment + residualValue) - borrowedAmount
if (totalInterests < 0) {
totalInterests = 0
}
if (ageInMonths >= numberOfMonthlyInstalments) {
monthlyCost = totalInterests / ageInMonths
} else {
monthlyCost = totalInterests / numberOfMonthlyInstalments
}
} else {
monthlyCost = 0
}
return {
monthlyCost: monthlyCost,
numberOfMonthlyInstalments: numberOfMonthlyInstalments,
totalInterests: totalInterests
}
}
function calculateMonthlyInspection (inspection, ageInMonths) {
if (parseInt(inspection.numberOfInspections, 10) > 0) {
return (parseInt(inspection.numberOfInspections, 10) * inspection.averageInspectionCost) / ageInMonths
} else {
return 0
}
}
function calculateMonthlyTaxes (roadTaxes) {
return roadTaxes.amountPerYear / 12
}
function calculateMonthlyFuel (fuel) {
var monthlyCost, // monthly fuel costs in standard currency
distancePerMonth // distance per month in standard unit
var errMsg = 'Error calculating fuel'
// the result shall be: "money", "distanceNoCarToJob" or "distanceCarToJob"
var typeOfCalculation = function () {
switch (fuel.typeOfCalculation) {
case 'distance':
if (typeof fuel.distanceBased.considerCarToJob !== 'boolean') {
throw Error(errMsg + 'fuel.distanceBased.considerCarToJob is not a boolean')
}
checkBoolean(fuel.distanceBased.considerCarToJob)
if (fuel.distanceBased.considerCarToJob) {
return 'distanceCarToJob'
} else {
return 'distanceNoCarToJob'
}
break // eslint-disable-line no-unreachable
case 'money':
return 'money'
default:
throw Error(errMsg + ' - Invalid fuel.typeOfCalculation: ' + fuel.typeOfCalculation)
}
}
var getMonthlyCost = function () {
var fuelEffL100km,
fuelPriceOnCurrPerLitre,
distancePerMonthInKms,
selectedDistancePerMonth,
distanceBetweenHomeAndJob,
distanceDuringWeekends,
daysPerWeekUserDrivesToJob
// the result shall be: "money", "distanceNoCarToJob" or "distanceCarToJob"
switch (typeOfCalculation()) {
case 'distanceNoCarToJob':
fuelEffL100km = conversionsModule
.convertFuelEfficiencyToL100km(fuel.distanceBased.fuelEfficiency, fuel.distanceBased.fuelEfficiencyStandard)
fuelPriceOnCurrPerLitre = conversionsModule
.convertFuelPriceToLitre(fuel.distanceBased.fuelPrice, fuel.distanceBased.fuelPriceVolumeStandard)
selectedDistancePerMonth = getMonthlyAmount(fuel.distanceBased.noCarToJob.distancePerPeriod, fuel.distanceBased.noCarToJob.period)
// converts distance unit to kilometres
distancePerMonthInKms = conversionsModule
.convertDistanceToKm(selectedDistancePerMonth, fuel.distanceBased.noCarToJob.distanceStandardUnit)
monthlyCost = fuelEffL100km * distancePerMonthInKms * fuelPriceOnCurrPerLitre / 100
// always set the "distance per month" in the standard default unit defined for the country standard
distancePerMonth = conversionsModule
.convertDistanceFromKm(distancePerMonthInKms, calculatedData.standardUnits.distance)
break
case 'distanceCarToJob':
distanceBetweenHomeAndJob = fuel.distanceBased.carToJob.distanceBetweenHomeAndJob
distanceDuringWeekends = fuel.distanceBased.carToJob.distanceDuringWeekends
daysPerWeekUserDrivesToJob = parseInt(fuel.distanceBased.carToJob.daysPerWeek, 10)
fuelEffL100km = conversionsModule
.convertFuelEfficiencyToL100km(fuel.distanceBased.fuelEfficiency, fuel.distanceBased.fuelEfficiencyStandard)
fuelPriceOnCurrPerLitre = conversionsModule
.convertFuelPriceToLitre(fuel.distanceBased.fuelPrice, fuel.distanceBased.fuelPriceVolumeStandard)
// if for example miles were the default must convert input to kilometres
var distanceHomeToJobInKms = conversionsModule.convertDistanceToKm(distanceBetweenHomeAndJob,
fuel.distanceBased.carToJob.distanceStandardUnit)
var distanceOnWeekendsInKms = conversionsModule.convertDistanceToKm(distanceDuringWeekends,
fuel.distanceBased.carToJob.distanceStandardUnit)
distancePerMonthInKms = (2 * distanceHomeToJobInKms * daysPerWeekUserDrivesToJob + distanceOnWeekendsInKms) *
consts.numberOfWeeksInAMonth
monthlyCost = fuelEffL100km * distancePerMonthInKms * fuelPriceOnCurrPerLitre / 100
// always set the distance per month in the standard default unit defined for the country
distancePerMonth = conversionsModule
.convertDistanceFromKm(distancePerMonthInKms, calculatedData.standardUnits.distance)
calculatedData.details.numberOfDaysPerWeekUserDrivesToJob = daysPerWeekUserDrivesToJob
break
case 'money':
monthlyCost = getMonthlyAmount(fuel.currencyBased.amountPerPeriod, fuel.currencyBased.period)
distancePerMonth = null
break
default:
throw Error(errMsg + ' - Invalid result from typeOfCalculation(): ' + typeOfCalculation())
}
return monthlyCost
}
// always return the distance per month in the standard default unit defined for the country
var getDistancePerMonth = function () {
getMonthlyCost()
return distancePerMonth
}
return {
typeOfCalculation: typeOfCalculation,
getMonthlyCost: getMonthlyCost,
getDistancePerMonth: getDistancePerMonth
}
}
function calculateMonthlyMaintenance (maintenance) {
return maintenance.amountPerYear / 12
}
function calculateMonthlyRepairsAndImprovements (repairsImprovements) {
return repairsImprovements.amountPerYear / 12
}
function calculateMonthlyParking (parking) {
return parking.amountPerMonth
}
function calculateMonthlyTolls (tolls) {
var errMsg = 'Error calculating tolls'
if (typeof tolls.calculationBasedOnDay !== 'boolean') {
throw (Error(errMsg))
}
checkBoolean(tolls.calculationBasedOnDay)
if (!tolls.calculationBasedOnDay) { // calculation not done by day
return getMonthlyAmount(tolls.noBasedOnDay.amountPerPeriod, tolls.noBasedOnDay.period)
} else {
return tolls.yesBasedOnDay.amountPerDay * tolls.yesBasedOnDay.daysPerMonth
}
}
function calculateMonthlyFines (fines) {
return getMonthlyAmount(fines.amountPerPeriod, fines.period)
}
function calculateMonthlyWashing (washing) {
return getMonthlyAmount(washing.amountPerPeriod, washing.period)
}
function calculateMonthlyCosts (costs, details) {
// 'costs' and 'details' are assigned by reference and makes reference to calculatedData.costs and calculatedData.details
// no other methods and properties of calculatedData are touched
var dateOfAcquisition = new Date(inputData.depreciation.dateOfAcquisition.year, inputData.depreciation.dateOfAcquisition.month - 1)
var dateOfUserInput = new Date(inputData.depreciation.dateOfUserInput.year, inputData.depreciation.dateOfUserInput.month - 1)
var ageInMonths = differenceBetweenDates(dateOfAcquisition, dateOfUserInput)
if (ageInMonths === null || ageInMonths <= 0) {
console.log(inputData.depreciation)
throw Error('Age of vehicle invalid: ' + ageInMonths)
}
var monthlyCosts = costs.perMonth.items
monthlyCosts.depreciation = calculateMonthlyDepreciation(inputData.depreciation, ageInMonths)
monthlyCosts.insurance = calculateInsuranceMonthlyValue(inputData.insurance)
monthlyCosts.credit = calculateInterestsMonthlyValue(inputData.credit, ageInMonths).monthlyCost
monthlyCosts.inspection = calculateMonthlyInspection(inputData.inspection, ageInMonths)
monthlyCosts.roadTaxes = calculateMonthlyTaxes(inputData.roadTaxes)
monthlyCosts.fuel = calculateMonthlyFuel(inputData.fuel).getMonthlyCost()
monthlyCosts.maintenance = calculateMonthlyMaintenance(inputData.maintenance)
monthlyCosts.repairsImprovements = calculateMonthlyRepairsAndImprovements(inputData.repairsImprovements)
monthlyCosts.parking = calculateMonthlyParking(inputData.parking)
monthlyCosts.tolls = calculateMonthlyTolls(inputData.tolls)
monthlyCosts.fines = calculateMonthlyFines(inputData.fines)
monthlyCosts.washing = calculateMonthlyWashing(inputData.washing)
// total standing costs
var totalStandingCostsPerMonth = monthlyCosts.insurance + monthlyCosts.depreciation + monthlyCosts.credit +
monthlyCosts.inspection + 0.5 * monthlyCosts.maintenance + monthlyCosts.roadTaxes
// total running costs
var totalRunningCostsPerMonth = monthlyCosts.fuel + 0.5 * monthlyCosts.maintenance +
monthlyCosts.repairsImprovements + monthlyCosts.parking +
monthlyCosts.tolls + monthlyCosts.fines + monthlyCosts.washing
// totals
var totalCostsPerMonth = monthlyCosts.insurance + monthlyCosts.fuel + monthlyCosts.depreciation +
monthlyCosts.credit + monthlyCosts.inspection + monthlyCosts.maintenance +
monthlyCosts.repairsImprovements + monthlyCosts.roadTaxes + monthlyCosts.parking +
monthlyCosts.tolls + monthlyCosts.fines + monthlyCosts.washing
var totalCostsPerYear = totalCostsPerMonth * 12
var totalCostsEver = totalCostsPerMonth * ageInMonths
// details and costs are references
details.ageOfCarInMonths = ageInMonths
var creditObj = calculateInterestsMonthlyValue(inputData.credit, ageInMonths)
details.credit.numberOfMonthlyInstalments = creditObj.numberOfMonthlyInstalments
details.credit.totalPaidInInterests = creditObj.totalInterests
costs.perMonth.items = monthlyCosts
costs.perMonth.standingCosts = totalStandingCostsPerMonth
costs.perMonth.runningCosts = totalRunningCostsPerMonth
costs.perMonth.total = totalCostsPerMonth
costs.totalPerYear = totalCostsPerYear
costs.totalEver = totalCostsEver
// because NaN+1+2+3=NaN this also checks if any cost itme is a valid number
if (areAllNumbers(totalStandingCostsPerMonth, totalRunningCostsPerMonth, totalCostsPerMonth, totalCostsPerYear, totalCostsEver)) {
return true
} else {
return false
}
}
function calculatePublicTransports (publicTransports, inputPublicTransports, totalCarCostsPerMonth) {
// 'publicTransports' is assigned by reference and refers to calculatedData.publicTransports
// 'inputPublicTransports' is assigned by reference and makes reference to inputData.publicTransports
// This function calculates the public transports costs as an alternative to car usage
// that is, how much of public transports could be used with the same amount
// of money that the user spends totally with automobile
var errMsg = 'Error calculating Public Transports'
if (!publicTransports || !inputPublicTransports || !isNumber(totalCarCostsPerMonth)) {
consoleErrorPairs('publicTransports', publicTransports,
'inputPublicTransports', inputPublicTransports,
'totalCarCostsPerMonth', totalCarCostsPerMonth)
throw Error(errMsg)
}
/* ratios */
// ratio (costs of public transports)/(car costs), under which it shows public transports as an alternative
publicTransports.ratios.showPt = 0.9
// ratio of (costs of public transports)/(car costs), under which shows further public transports (intercity trains for example)
publicTransports.ratios.showFurtherPt = 0.6
var costOfEachMonthlyPass = inputPublicTransports.monthlyPassCost
var numberOfPeopleInFamily = inputPublicTransports.numberOfPeopleInFamily
if (!areAllNumbersGreaterThanZero(costOfEachMonthlyPass, inputPublicTransports.taxi.costPerUnitDistance) ||
!isInteger(numberOfPeopleInFamily)) {
/* if */
publicTransports.calculated = false
return
}
var totalCostsOfStandardPt = costOfEachMonthlyPass * numberOfPeopleInFamily
publicTransports.totalCostsOfStandardPublicTransports = totalCostsOfStandardPt
var taxiDistancePerUnitCurrency = 1 / inputPublicTransports.taxi.costPerUnitDistance
taxiDistancePerUnitCurrency = conversionsModule.convertDistanceFromTo(taxiDistancePerUnitCurrency,
inputPublicTransports.taxi.distanceStandardUnit, calculatedData.standardUnits.distance)
publicTransports.taxi.costPerUnitDistance = 1 / taxiDistancePerUnitCurrency
// boolean function that says if public transports alternatives are calculated
publicTransports.toBeDisplayed =
(totalCostsOfStandardPt < publicTransports.ratios.showPt * totalCarCostsPerMonth) && (costOfEachMonthlyPass > 0)
if (publicTransports.toBeDisplayed) {
var taxiTotalCostsPerMonth
publicTransports.totalAlternativeCostsWhenUserHasNoCar = totalCostsOfStandardPt
publicTransports.ratios.ptCostsOverCarCosts = totalCostsOfStandardPt / totalCarCostsPerMonth
// in case further public transports are not shown, further shows just taxi
if (publicTransports.ratios.ptCostsOverCarCosts > publicTransports.ratios.showFurtherPt) {
publicTransports.furtherPublicTransports.display = false
taxiTotalCostsPerMonth = totalCarCostsPerMonth - totalCostsOfStandardPt
publicTransports.totalAlternativeCostsWhenUserHasNoCar += taxiTotalCostsPerMonth
} else {
// in case further public transports are shown,
// half of the remainder goes to taxi and other half goes to further public transports
publicTransports.furtherPublicTransports.display = true
taxiTotalCostsPerMonth = totalCarCostsPerMonth * (1 - publicTransports.ratios.ptCostsOverCarCosts) / 2
// amount allocated to further Public Transports, besides monthly pass and taxi
publicTransports.furtherPublicTransports.totalCosts =
totalCarCostsPerMonth * (1 - publicTransports.ratios.ptCostsOverCarCosts) / 2
publicTransports.totalAlternativeCostsWhenUserHasNoCar +=
taxiTotalCostsPerMonth + publicTransports.furtherPublicTransports.totalCosts
}
publicTransports.taxi.totalCosts = taxiTotalCostsPerMonth
publicTransports.taxi.possibleDistanceDoneByTaxi = taxiTotalCostsPerMonth / publicTransports.taxi.costPerUnitDistance
publicTransports.calculated = true
} else {
publicTransports.calculated = false
}
}
function calculateFinancialEffort (financialEffort, inputIncome, inputWorkingTime, totalCostsPerYear) {
// 'financialEffort' is assigned by reference and makes reference to calculatedData.financialEffort
// 'inputIncome' and 'inputWorkingTime' are assigned by reference and make reference to inputData.income and inputData.inputData
// no other methods and properties of calculatedData or inputData are touched
var errMsg = 'Error calculating Financial Effort'
if (!financialEffort || !inputIncome || !inputWorkingTime || !isNumber(totalCostsPerYear)) {
consoleErrorPairs('financialEffort', financialEffort,
'inputIncome', inputIncome,
'inputWorkingTime', inputWorkingTime,
'totalCostsPerYear', totalCostsPerYear)
throw Error(errMsg)
}
financialEffort.totalCarCostsPerYear = totalCostsPerYear
// Income and financial effort
var incomePeriod = inputIncome.incomePeriod
switch (incomePeriod) {
case 'year':
financialEffort.income.perYear = inputIncome.year.amount * 1
break
case 'month':
financialEffort.income.perYear = inputIncome.month.amountPerMonth * inputIncome.month.monthsPerYear
break
case 'week':
financialEffort.income.perYear = inputIncome.week.amountPerWeek * inputIncome.week.weeksPerYear
break
case 'hour':
financialEffort.workingTime.hoursPerWeek = inputIncome.hour.hoursPerWeek
financialEffort.workingTime.weeksPerYear = inputIncome.hour.weeksPerYear
financialEffort.income.perYear =
inputIncome.hour.amountPerHour * financialEffort.workingTime.hoursPerWeek * financialEffort.workingTime.weeksPerYear
break
default:
// if income period is not valid, return the function immediately
financialEffort.calculated = financialEffort.income.calculated = false
return
}
// this function also works with one parameter, must be a valid number > 0
if (areAllNumbersGreaterThanZero(financialEffort.income.perYear)) {
financialEffort.income.averagePerMonth = financialEffort.income.perYear / 12
financialEffort.income.averagePerWeek = financialEffort.income.perYear / consts.numberOfWeeksInAYear
financialEffort.workingMonthsPerYearToAffordCar = totalCostsPerYear / financialEffort.income.perYear * 12
financialEffort.daysForCarToBePaid =
totalCostsPerYear / financialEffort.income.perYear * consts.numberOfDaysInAYear
financialEffort.financialEffortPercentage = totalCostsPerYear / financialEffort.income.perYear * 100
financialEffort.income.calculated = true
} else {
financialEffort.income.calculated = false
}
// Working Time
// uses input Data section "income", as the income was selected per hour
if (incomePeriod === 'hour') {
if (areAllNumbersGreaterThanZero(financialEffort.workingTime.hoursPerWeek, financialEffort.workingTime.weeksPerYear)) {
financialEffort.workingTime.hoursPerYear = financialEffort.workingTime.hoursPerWeek * financialEffort.workingTime.weeksPerYear
financialEffort.workingTime.hoursPerMonth = financialEffort.workingTime.hoursPerYear / 12
financialEffort.workingTime.calculated = true
} else {
financialEffort.workingTime.calculated = false
}
} else if (incomePeriod === 'week' || incomePeriod === 'month' || incomePeriod === 'year') {
// uses input data section "working time"
if (typeof inputWorkingTime.isActivated !== 'boolean') {
consoleError(Error(errMsg))
return
}
if (inputWorkingTime.isActivated) {
financialEffort.workingTime.hoursPerWeek = inputWorkingTime.hoursPerWeek
financialEffort.workingTime.monthsPerYear = inputWorkingTime.monthsPerYear
} else {
// if user doesn't input, use standard values
financialEffort.workingTime.hoursPerWeek = 36
financialEffort.workingTime.monthsPerYear = 11
}
if (areAllNumbersGreaterThanZero(financialEffort.workingTime.hoursPerWeek, financialEffort.workingTime.monthsPerYear)) {
financialEffort.workingTime.hoursPerYear =
consts.numberOfWeeksInAMonth * financialEffort.workingTime.monthsPerYear * financialEffort.workingTime.hoursPerWeek
financialEffort.workingTime.hoursPerMonth = financialEffort.workingTime.hoursPerYear / 12
financialEffort.workingTime.calculated = true
} else {
financialEffort.workingTime.calculated = false
}
} else {
financialEffort.calculated = financialEffort.workingTime.calculated = false
return
}
// find average income per hour
financialEffort.calculated = financialEffort.income.calculated && financialEffort.workingTime.calculated
if (financialEffort.calculated) {
financialEffort.income.averagePerHour = financialEffort.income.perYear / financialEffort.workingTime.hoursPerYear
financialEffort.workingHoursPerYearToAffordCar = totalCostsPerYear / financialEffort.income.averagePerHour
}
if (financialEffort.income.calculated &&
financialEffort.financialEffortPercentage >= isLikelyToBeValidConst.financialEffortPercentage.min &&
financialEffort.financialEffortPercentage <= isLikelyToBeValidConst.financialEffortPercentage.max) {
/* if */
financialEffort.isLikelyToBeValid = true
} else {
financialEffort.isLikelyToBeValid = false
}
// doesn't need to return because financialEffort is a referece to calculatedData.financialEffort
// and calculatedData is global in this module
}
function calculateDrivingDistance (drivingDistance, details, inputFuel, inputDistance) {
// 'drivingDistance' and 'details' are assigned by reference and refer to calculatedData.drivingDistance and calculatedData.inputFuel
// 'inputDistance' and 'inputFuel' are assigned by reference and refer to inputData.inputDistance and inputData.details
var errMsg = 'Error calculating Driving Distance'
if (!drivingDistance || !details || !inputFuel || !inputDistance) {
consoleErrorPairs('drivingDistance', drivingDistance,
'details', details,
'inputFuel', inputFuel,
'inputDistance', inputDistance)
throw Error(errMsg)
}
// always set the distances in the standard default unit defined for the country
var distancePerWeek, // distance driven per week
distancePerMonth, // distance driven per month
distancePerYear, // distance driven per year
distanceBetweenHomeAndJob, // distance between home and job (one-way)
distanceDuringEachWeekend, // distance the user drives during weekend
daysPerWeekUserDrivesToJob
// the result shall be: "money", "distanceNoCarToJob" or "distanceCarToJob"
var fuelTypeOfCalculation = calculateMonthlyFuel(inputFuel).typeOfCalculation()
// if fuel calculation with distance was NOT chosen in form part 2, gets distance from form part 3
if (fuelTypeOfCalculation === 'money') {
if (typeof inputDistance.considerCarToJob !== 'boolean') {
drivingDistance.calculated = false
return
}
if (inputDistance.considerCarToJob) {
daysPerWeekUserDrivesToJob = inputDistance.carToJob.daysPerWeek
distanceBetweenHomeAndJob = inputDistance.carToJob.distanceBetweenHomeAndJob
distanceDuringEachWeekend = inputDistance.carToJob.distanceDuringWeekends
if (isInteger(daysPerWeekUserDrivesToJob) && areAllNumbers(distanceBetweenHomeAndJob, distanceDuringEachWeekend)) {
/* if */
distanceBetweenHomeAndJob = conversionsModule.convertDistanceFromTo(distanceBetweenHomeAndJob,
inputDistance.carToJob.distanceStandardUnit, calculatedData.standardUnits.distance)
distanceDuringEachWeekend = conversionsModule.convertDistanceFromTo(distanceDuringEachWeekend,
inputDistance.carToJob.distanceStandardUnit, calculatedData.standardUnits.distance)
distancePerWeek = 2 * distanceBetweenHomeAndJob * daysPerWeekUserDrivesToJob + distanceDuringEachWeekend
distancePerMonth = consts.numberOfWeeksInAMonth * distancePerWeek
distancePerYear = distancePerMonth * 12
details.numberOfDaysPerWeekUserDrivesToJob = daysPerWeekUserDrivesToJob
} else {
drivingDistance.calculated = false
return
}
} else { // considerCarToJob is false
if (isNumber(inputDistance.noCarToJob.distancePerPeriod)) {
distancePerMonth = getMonthlyAmount(inputDistance.noCarToJob.distancePerPeriod, inputDistance.noCarToJob.period)
distancePerMonth = conversionsModule.convertDistanceFromTo(distancePerMonth,
inputDistance.noCarToJob.distanceStandardUnit, calculatedData.standardUnits.distance)
distancePerYear = distancePerMonth * 12
distancePerWeek = distancePerMonth / consts.numberOfWeeksInAMonth
} else {
drivingDistance.calculated = false
return
}
}
} else if (fuelTypeOfCalculation === 'distanceCarToJob' || fuelTypeOfCalculation === 'distanceNoCarToJob') {
// gets distance information from form part 2, in fuel section
// distancePerMonth comes already in calculatedData.standardUnits.distance
distancePerMonth = calculateMonthlyFuel(inputFuel).getDistancePerMonth()
if (isNumber(distancePerMonth)) {
distancePerWeek = distancePerMonth / consts.numberOfWeeksInAMonth
distancePerYear = distancePerMonth * 12
} else {
drivingDistance.calculated = false
return
}
} else {
throw Error(errMsg)
}
drivingDistance.calculated = true
// always in the standard default unit defined for the country standards
drivingDistance.perWeek = distancePerWeek
drivingDistance.perMonth = distancePerMonth
drivingDistance.perYear = distancePerYear
drivingDistance.betweenHomeAndJob = distanceBetweenHomeAndJob
drivingDistance.duringEachWeekend = distanceDuringEachWeekend
// doesn't need to return because drivingDistance is a referece to calculatedData.drivingDistance
// and calculatedData is global in this module
}
function calculateTimeSpentInDriving (timeSpentInDriving, details, inputFuel, inputDistance, inputTimeSpentInDriving) {
// 'timeSpentInDriving' is assigned by reference and makes reference to calculatedData.timeSpentInDriving
// 'details' is assigned by reference and makes reference to calculatedData.details
// inputFuel, inputDistance and inputTimeSpentInDriving make reference to
// inputData.inputFuel inputData.inputDistance and inputData.inputTimeSpentInDriving
var errMsg = 'Error calculating Time Spent In Driving'
if (!timeSpentInDriving || !details || !inputFuel || !inputDistance || !inputTimeSpentInDriving) {
consoleErrorPairs('timeSpentInDriving', timeSpentInDriving,
'details', details,
'inputFuel', inputFuel,
'inputDistance', inputDistance,
'inputTimeSpentInDriving', inputTimeSpentInDriving)
throw Error(errMsg)
}
var minutesBetweenHomeAndJob, // time (in minutes) driven between home and job
minutesInEachWeekend, // time (in minutes) driven during weekends
minutesPerWeek, // time (in minutes) driven per week
minutesPerDay, // time (in minutes) driven per day
daysPerMonth, // number of days driven per month
hoursPerMonth, // number of hours driven per month
hoursPerYear, // number of hours driven per year
daysPerWeekUserDrivesToJob,
fuelTypeOfCalculation
// the result shall be: "money", "distanceNoCarToJob" or "distanceCarToJob"
fuelTypeOfCalculation = calculateMonthlyFuel(inputFuel).typeOfCalculation()
// When user refers that "takes car to job", either in Fuel section (form part 2) or in Distance section (part 3).
// In this situation, the form displays "option 1" in "Time Spent in Driving" section
if (fuelTypeOfCalculation === 'distanceCarToJob' || inputDistance.considerCarToJob) {
minutesBetweenHomeAndJob = inputTimeSpentInDriving.carToJob.minutesBetweenHomeAndJob
minutesInEachWeekend = inputTimeSpentInDriving.carToJob.minutesDuringWeekend
daysPerWeekUserDrivesToJob = parseInt(details.numberOfDaysPerWeekUserDrivesToJob, 10)
if (areAllNumbersGreaterThanZero(minutesBetweenHomeAndJob, minutesInEachWeekend) &&
isNumber(daysPerWeekUserDrivesToJob)) {
/* if */
minutesPerWeek = 2 * minutesBetweenHomeAndJob * daysPerWeekUserDrivesToJob + minutesInEachWeekend
hoursPerMonth = consts.numberOfWeeksInAMonth * minutesPerWeek / 60
minutesPerDay = minutesPerWeek / 7
daysPerMonth = consts.numberOfWeeksInAMonth * ((minutesInEachWeekend > 0 ? 2 : 0) + daysPerWeekUserDrivesToJob)
hoursPerYear = hoursPerMonth * 12
} else {
timeSpentInDriving.calculated = false
return
}
} else {
minutesPerDay = inputTimeSpentInDriving.noCarToJob.minutesPerDay
daysPerMonth = inputTimeSpentInDriving.noCarToJob.daysPerMonth
if (areAllNumbersGreaterThanZero(minutesPerDay, daysPerMonth)) {
hoursPerMonth = minutesPerDay * daysPerMonth / 60
minutesPerWeek = hoursPerMonth / consts.numberOfWeeksInAMonth * 60
hoursPerYear = hoursPerMonth * 12
} else {
timeSpentInDriving.calculated = false
return
}
}
// sets object
timeSpentInDriving.calculated = true
timeSpentInDriving.minutesBetweenHomeAndJob = minutesBetweenHomeAndJob
timeSpentInDriving.minutesInEachWeekend = minutesInEachWeekend
timeSpentInDriving.minutesPerWeek = minutesPerWeek
timeSpentInDriving.minutesPerDay = minutesPerDay
timeSpentInDriving.daysPerMonth = daysPerMonth
timeSpentInDriving.hoursPerMonth = hoursPerMonth
timeSpentInDriving.hoursPerYear = hoursPerYear
// doesn't need to return because timeSpentInDriving is a referece to calculatedData.timeSpentInDriving
// and calculatedData is global in this module
}
function calculateSpeeds (speeds, financialEffort, drivingDistance, timeSpentInDriving) {
// speeds, financialEffort, drivingDistance and timeSpentInDriving are assigned by reference and make reference to
// calculatedData.speeds, calculatedData.financialEffort, calculatedData.drivingDistance and calculatedData.timeSpentInDriving
var errMsg = 'Error calculating Speeds'
if (!speeds || !financialEffort || !drivingDistance || !timeSpentInDriving) {
consoleErrorPairs('speeds', speeds,
'financialEffort', financialEffort,
'drivingDistance', drivingDistance,
'timeSpentInDriving', timeSpentInDriving)
throw Error(errMsg)
}
/* For more details on the Consumer Speed concept, check:
https://github.com/jfoclpf/autocosts/wiki/Kinetic-speed-vs.-Consumer-speed */
var averageKineticSpeed,
averageConsumerSpeed
if (drivingDistance.calculated && timeSpentInDriving.calculated) {
averageKineticSpeed = drivingDistance.perYear / timeSpentInDriving.hoursPerYear
// Virtual/Consumer Speed calculated if info of Financial Effort is available
if (financialEffort.calculated) {
averageConsumerSpeed =
drivingDistance.perYear / (timeSpentInDriving.hoursPerYear + financialEffort.workingHoursPerYearToAffordCar)
}
}
// set object
speeds.averageKineticSpeed = averageKineticSpeed
speeds.averageConsumerSpeed = averageConsumerSpeed
// doesn't need to return because speeds is a referece to calculatedData.speeds
// and calculatedData is global in this module
}
function calculateExternalCosts (externalCosts, drivingDistance) {
var errMsg = 'Error calculating External Costs'
if (!externalCosts) {
throw Error(errMsg)
}
if (!isNumber(drivingDistance.perMonth)) {
externalCosts.calculated = false
return
}
// by month, source: https://ec.europa.eu/transport/themes/sustainable/doc/2008_costs_handbook.pdf
externalCosts.handbookOfeExternalCostsURL = 'http://ec.europa.eu/transport/themes/sustainable/doc/2008_costs_handbook.pdf'
externalCosts.pollution = 0.005 // pollutants in €/km
externalCosts.greenhouseGases = 0.007 // greenhouse gases in €/km