build_scripts/generate_achievement_functions.js   A
last analyzed

Complexity

Total Complexity 8
Complexity/F 4

Size

Lines of Code 66
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
wmc 8
nc 2
mnd 2
bc 8
fnc 2
dl 0
loc 66
rs 10
bpm 4
cpm 4
noi 0
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A generate_achievement_functions.js ➔ createFunctions 0 12 3
A generate_achievement_functions.js ➔ conditionToProgress 0 14 4
1
/* eslint-env node */
2
/*jslint node: true */
3
'use strict';
4
5
const jsonfile = require('jsonfile');
6
const template = require('lodash.template');
7
const crypto = require('crypto');
8
const fs = require('fs');
9
10
let achievements = jsonfile.readFileSync('build/data/achievements.json');
11
let unlocks = jsonfile.readFileSync('build/data/unlocks.json');
12
let achievementService = fs.readFileSync('build/scripts/component/achievements.js').toString();
13
14
const FUNCTION_TEMPLATE = `this.<%= name %> = function (player){
15
  return <%= progress %>;
16
};`;
17
18
let functionTemplate = template(FUNCTION_TEMPLATE);
19
20
// convert conditions to progress, to normalise the implementation
21
function conditionToProgress(source){
22
  for(let i in source){
23
  let achievement = source[i];
24
    if(typeof achievement.condition === 'undefined') {
25
      continue;
26
    }
27
    if(achievement.condition.constructor === Array){
28
      achievement.condition = achievement.condition.join('\n');
29
    }
30
    achievement.progress = '('+achievement.condition+') ? 1 : 0';
31
    achievement.goals = [1];
32
    delete achievement.condition;
33
  }
34
}
35
function createFunctions(source){
36
  for(let i in source){
37
    let achievement = source[i];
38
    if(achievement.progress.constructor === Array){
39
      achievement.progress = achievement.progress.join('\n');
40
    }
41
    let name = '_'+crypto.createHash('md5').update(achievement.progress).digest('hex');
42
    functions[name] = functionTemplate({ 'name': name, 'progress': achievement.progress });
43
    // we overwrite progress with the name
44
    source[i].progress = name;
45
  }
46
}
47
48
let functions = {};
49
conditionToProgress(achievements);
50
conditionToProgress(unlocks);
51
createFunctions(achievements);
52
createFunctions(unlocks);
53
54
let concatFunctions = '';
55
for(let i in functions){
56
  concatFunctions += functions[i]+'\n';
57
}
58
59
let serviceTemplate = template(achievementService);
60
61
fs.writeFileSync('build/scripts/component/achievements.js', serviceTemplate({'functions': concatFunctions}));
62
63
jsonfile.writeFileSync('build/data/achievements.json', achievements, {
64
  spaces: 2
65
});
66
jsonfile.writeFileSync('build/data/unlocks.json', unlocks, {
67
  spaces: 2
68
});
69