Underscorejs vs Python
In this post, I show parallels between Javascript/Underscorejs and Python.
The examples below are available on github.
To start using underscore in your app, add the underscore package:
meteor add underscore
Let see instructions to execute similar operations in javascript/underscorejs and python. For each operation, the first example is javascript and the other example is python.
.toUpperCase() and ‘‘.upper()
var s = 'This tutorial focuses on using';
console.log(s.toUpperCase());
s = 'This tutorial focuses on using'
print s.upper()
.toLowerCase() and ‘‘.lower()
var s = 'This tutorial focuses on using';
console.log(s.toLowerCase());
s = 'This tutorial focuses on using'
print s.lower()
.replace(//g,’’) and ‘‘.replace()
var s = 'This tutorial focuses on using';
console.log(s.replace(/i/g,'I'));
s = 'This tutorial focuses on using'
print s.replace('i','I')
parseInt and int
var fl = 5.5;
console.log(parseInt(fl));
fl = 5.5
print int(fl)
.trim() and ‘‘.strip()
var s = ' This tutorial focuses on using ';
console.log(s.trim());
s = ' This tutorial focuses on using '
print s.strip()
.split() and ‘‘.split()
var s = 'This tutorial focuses on using';
console.log(s.split(' '));
s = 'This tutorial focuses on using'
print s.split(' ')
.join() and ‘‘.join()
var a = ['1','2'];
console.log(a.join(' '));
a = ['1','2']
print ' '.join(a)
_.each and enumerate
_.each(a,function (element,index,list) {
console.log('element: '+element);
console.log('index: '+index);
});
for i,element in enumerate(a):
print 'element: %s' % element
print 'index: %d' % i
_.map and map()
var c = [2,1,3];
d = _.map(c, function (value, index,list) {
return value*2;
});
c = [2,1,3]
def f(p):
return p*2
print map(f, c)
Delete element from array: delete and del
delete a[index]
a = _.compact(a);
del a[index]
_.reject, _.without
var b = ['a','b','c'];
r = _.reject(b, function (num) {
return num == 'c';
});
b = ['a','b','c']
print [i for i in b if i!= 'a']
_.contains and e in a
r = _.contains(c,1);
print 1 in c
contains in javascript
r = c.indexOf(1) != -1
_.indexOf and .index()
r = _.indexOf(c,'2');
print a.index('2')
.push() and .append()
a.push('a');
a.append('a')
Append array to array, push.apply and +
a.push.apply(a, [1,2]);
a += [1,2]
_.uniq and list(set())
r = _.uniq(a);
print list(set(b))
_.size and len()
r = _.size(a);
// or
a.length
print len(a)
_.first, _.slice and [n:m]
r = _.first(a,2);
r = a.slice(0,2);
print a[2:]
print a[0:2]
Lists/Dictionaries: _.zip and zip()
r = _.zip(b,a);
r = zip(b,a)
Array to list and array to dictionary _.object and dict()
r = _.object(r);
r = dict(r)
_.keys and .keys()
k = _.keys(r);
// or
k = Object.keys(r);
print r.keys()
_.values and .values()
v = _.values(r);
print r.values()
.has, .hasOwnProperty and .haskey()
console.log(_.has(r,'c'));
console.log(r.hasOwnProperty('c'));
print r.has_key('c')
_.pairs and zip list
p = _.pairs(r);
print [list(i) for i in zip(r.keys(),r.values())]
_.range
r = _.range(5);
print range(5)