Skip to content

Instantly share code, notes, and snippets.

@BucleSinFin
Created April 2, 2016 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BucleSinFin/ad7bab88baa44b082d5a4537e3cdee03 to your computer and use it in GitHub Desktop.
Save BucleSinFin/ad7bab88baa44b082d5a4537e3cdee03 to your computer and use it in GitHub Desktop.
/* Poiščite node.js modul na npmjs.com, ga namestite v okolju runnable.com in ga
uporabite. Naredite funkcijo, ki iz datoteke prebere števila in jih sešteje med seboj.*/
var fs = require('fs');
var numbers = '0, 1, 3.9, -5, 100 \n200, 300 \n-50';
fs.writeFileSync('file', numbers);
function sum(file_name) {
var x = fs.readFileSync(file_name, 'utf-8').split(/[\n,]+/);
return x.reduce(function(a, b){return parseFloat(a) + parseFloat(b)});
}
console.log('Vsota števil v datoteki: ' + sum('file'));
@offlinehacker
Copy link

Zelo dobra rešitev. Ker vidim da že uporabljaš reduce funkcijo nad arrayem in split stringa, tale modul je precej uporaben in naredi pisanje kode v javascriptu, precej bolj uporabno https://lodash.com/, tu najdeš dokumentacijo https://lodash.com/docs. Lodash je kot swiss army knife za javascript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment