Skip to content

Instantly share code, notes, and snippets.

@zz85
Last active February 22, 2020 17:49
Show Gist options
  • Save zz85/e929503387cdc597b4f7 to your computer and use it in GitHub Desktop.
Save zz85/e929503387cdc597b4f7 to your computer and use it in GitHub Desktop.
mrdoob style guide with jscs config
{
"requireCurlyBraces": ["while", "do", "try", "catch"],
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"],
"requireSpacesInFunctionExpression": {
"beforeOpeningCurlyBrace": true
},
"requirePaddingNewlinesInBlocks": true,
"requireSpacesInsideObjectBrackets": "all",
"requireSpacesInsideArrayBrackets": "allButNested",
"requireSpaceBeforeBlockStatements": true,
"disallowLeftStickedOperators": ["?", "+", "-", "/", "*", "=", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "++", "--"],
"disallowRightStickedOperators": [ ";", "?", "/", "*", ":", "=", "==", "===", "!=", "!==", ">", ">=", "<", "<=" ],
"requireLeftStickedOperators": [ "," ],
"disallowKeywords": [ "with" ],
"requireLineFeedAtFileEnd": true,
"validateLineBreaks": "LF",
"validateIndentation": "\t",
"requireSpacesInConditionalExpression": {
"afterTest": true,
"beforeConsequent": true,
"afterConsequent": true,
"beforeAlternate": true
},
"requireSpaceAfterPrefixUnaryOperators": ["++", "--"],
"requireSpaceBeforePostfixUnaryOperators": ["++", "--"],
"requireSpaceBeforeBinaryOperators": [ "+", "-", "/", "*", "=", "==", "===", "!=", "!==", ">", ">=", "<", "<=" ]
}

#Mr.doob's Code Style™

Known for its generous use of whitespace as seen in three.js and elsewhere mrdoob.com

##Warning This is an unoffical style guide by @blurspline and still a WIP. Test at your own risk. Might be imported to three.js later.

##Examples

Valid

for ( a = 0; a < 23; a ++ ) {

	hello = 'world';

}

Invalid

for ( a = 0; a < 23; a ++ ) {
	hello = 'world';
}

for ( a=0; a<23; a ++ ) {

	hello = 'world';
	
}

for (a = 0; a < 23; a ++) {

	hello = 'world';
	
}

for ( a = 0;a < 23; a ++ ) {

	hello = 'world';
}

#JSCS

to install,

npm install -g jscs

to validate,

jscs *.js -c mrdoob.json

More about JSCS and its plugins here.

Some scripts for code transformation.

See mrdoob/three.js#4806

git reset --hard # clean state
cd src/
# run code painter
codepainter xform -j ../utils/codestyle/mrdoob_codepainter.json  "*/*.js"
# execute some custom regex
find ./ -type f -exec sed -i -e 's/( )/()/g;s/\[ \]/[]/g;s#{[ ]}#\{\}#g' {} \;
# remove backup files by sed. To undo, use find . -name "*-e" -exec sh -c 'mv -f $0 ${0%-e}' {} \;
find . -name "*.js-e*" -print0 | xargs -0 rm
jscs src -c mrdoob.json -r spaces # execute custom jscs for spaces
git add -p # inspect changes

mrdoob_codepainter.json

{
	"indent_style": "tab",
	"indent_size": "tab",
	"insert_final_newline": true,
	"quote_type": "auto",
	"space_after_anonymous_functions": true,
	"space_after_control_statements": true,
	"spaces_around_operators": true,
	"trim_trailing_whitespace": true,
	"spaces_in_brackets": true,
	"end_of_line": "lf"
}

unary_jscs.json

{
    "requireSpaceAfterPrefixUnaryOperators": [ "+", "-", "++", "--" ],
    "requireSpaceBeforePostfixUnaryOperators": ["++", "--"]
}

spaces.js

var util = require('util');
var fs = require('fs');

/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function(errorsCollection) {
    var errorCount = 0;
    /**
     * Fixes spacing errors.
     */

    var json = {};

    errorsCollection.forEach(function(errors) {
        var file = errors.getFilename();
        var file_contents = fs.readFileSync(file, 'utf-8');
        var lines = file_contents.split('\n');

        if (!errors.isEmpty()) {
           var list = [];

            errors.getErrorList().forEach(function(error) {
                list.push({
                    line: error.line,
                    column: error.column,
                    message: error.message
                })
                errorCount++;
            });

            json[file] = list;

            list = list.reverse();
            list.forEach(function(error) {
                var line = error.line - 1;
                var str = lines[line];
                var col = error.column;
                while (str.charAt(col) != '+' && str.charAt(col) != '-') col++;
                lines[line] = str.substring(0, col) + ' ' + str.substring(col);
                console.log(str +  ' --> ' + lines[line]);
            });

            file_contents = lines.join('\n');

            // console.log('--preview formatted: ' + file + ' --')
            // console.log(file_contents) // print formatted source
            fs.writeFile(file, file_contents);  // write formatted source
        }       

    });

    console.log('end', json, errorCount)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment