Codementor Events

Implementing Common Python Built-ins in JavaScript

Published Sep 28, 2020

In this post we'll try to implement common Python builtins such as min mas etc in JavaScript. Here's what we'll have:

print(1, 2, 3, 4)
print(max([1, 2, 100]));
print(min([1, 2, 100]));
print(sum([1, 2, 100]));
print(round(9.12));
print(int('90') + 2);
print(reverse([1, 2, 3, 4, 5]))
print(len([1, 2, 3]))
print(all([true, true]))
print(any([false, false, false]))
print(abs(-1))

Please feel free to submit improvements here

Let's begin:

print

function print() {
    var sep = ' ';
    var toprint = '';
    for (var i = arguments.length - 1; i >= 0; i--) {
        arg = arguments[arguments.length - i - 1];
        if (typeof arg === 'string' || arg instanceof String) {

        } else {
            arg = arg.toString();
        }
        toprint += arg + sep;
    }
    console.log(toprint);
}

Since Js lacks keyword args, you won't be able to use print(1, 2, 3, sep='-') but nevertheless you can use print(1, '1', [1,2,3])

max

function max(array1){
  return Math.max(...array1)
}

min

function min(array1){
  return Math.min(...array1)
}

sum

function sum(array1){
  var sumArray = array1.reduce(function(a, b){
      return a + b;
  }, 0);
  return sumArray;
}

round

function round(number){
  return Math.round(number);
}

int

function int(number_string){
  return parseInt(number_string);
}

reverse

function reverse(array1){
  return array1.reverse();
}

len

function len(object1){
  return object1.length;
}

This one is great. for(i=0; i<len(array1; ...

all

function checkTrue(element){
  return element === true;
}
function all(array1){
  return array1.every(checkTrue);
}

any

function any(array1){
  return array1.some(function(e) {
      return e === true;
  });
}

abs

function abs(number1){
  return Math.abs(number1);
}

Result:

>>> print(1, 2, 3, 4);
1 2 3 4 
>>> print(max([1, 2, 100]));
100 
>>> print(min([1, 2, 100]));
1
>>> print(sum([1, 2, 100]));
103
>>> print(round(9.12));
9
>>> print(int('90') + 2);
92
>>> print(reverse([1, 2, 3, 4, 5]));
5,4,3,2,1 
>>> print(len([1, 2, 3]));
3
>>> print(all([true, true]));
true
>>> print(any([false, false, false]));
false
>>> print(abs(-1));
1

disclaimer

This is not Python. Look out for Js quirks. This is a fun experiment. Feel free to improve here

Discover and read more posts from Abdur-Rahmaan Janhangeer
get started