Giter VIP home page Giter VIP logo

locutus's Introduction

Locutus

All your standard libraries will be assimilated into our JavaScript collective. Resistance is futile.

Welcome to Locutus, where the boundaries of coding languages blur. We're a dedicated collective developers on a mission to explore the possibilities of porting standard libraries from various programming language (Go, Ruby, PHP, C) to JavaScript. Our journey is one of discovery, innovation, and sometimes, delightful chaos.

From the complex to the quirky, we assimilate libraries with a spirit of curiosity and a penchant for experimentation. Our creations typically start as rainy Sunday afternoon puzzles, and end up ranging from groundbreaking functions that enhance the JavaScript ecosystem, to unique oddities that challenge the norms of coding.

As we navigate through this uncharted territory, we invite you to join us. Whether to contribute, learn, or simply marvel at the wonders of cross-language integration and portability, your presence on GitHub is valued.

Embark on this journey with us at locutus.io.

Use our creations at your own risk, and may they inspire you to push the boundaries of what's possible with JavaScript.

Table of contents

Install

yarn add locutus

Use

$ vim php.js
const sprintf = require('locutus/php/strings/sprintf')
const echo = require('locutus/php/strings/echo')
const effectiveness = 'futile'
echo(sprintf('Resistance is %s', effectiveness))
$ node php.js
Resistance is futile
$ vim go.js
const strings = require('locutus/golang/strings')
console.log(strings.Contains('Locutus', 'cut'))
$ node go.js
true

Development

Some guidelines and instructions can be found in CONTRIBUTING.md

locutus's People

Contributors

argosback avatar brettz9 avatar codemasher avatar codestar avatar divinity76 avatar duzun avatar evgenius avatar glenara avatar greenkeeperio-bot avatar infusion avatar ironmagma avatar jamieslome avatar joni2back avatar josephthies avatar kukawski avatar kvz avatar louisstow avatar mackshot avatar marcuswestin avatar mfaber avatar mio-koduki avatar onnomarsman avatar oskarlh avatar plepe avatar reggino avatar simivar avatar tersmitten avatar theriault avatar tholum avatar yadimon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

locutus's Issues

Remove Site's Ohloh.net dependency

Ohloh.net problems. Could you offer me access again to the web code, or fix this at some point? It literally takes about 20+ seconds to load a page on phpjs.org for me due to ohloh.net apparently being blocked here in China. Could you adjust it to load asynchronously or something?

file_get_contents - XMLHttpRequest Exception 101

I just include Jquery and file_getcontents.js. When i use

$(document).ready(function(){ file_get_contents('http://www.anydomain.com/'); }); this code I take this error on Console Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101

How can i fix it ?
Thanks

Unserialize is having issues

Consider the following string:

a:5:%7Bs:7:%22nome_pt%22;s:27:%22Participa%C3%A7%C3%A3o%20no%20Congresso%22;s:4:%22tipo%22;s:5:%22texto%22;s:6:%22opcoes%22;a:0:%7B%7Ds:5:%22preco%22;s:5:%2210.00%22;s:11:%22obrigatorio%22;s:3:%22nao%22;%7D

Applying the following:

var t = decodeURI(valor);

t gets the following:

a:5:{s:7:"nome_pt";s:27:"Participação no Congresso";s:4:"tipo";s:5:"texto";s:6:"opcoes";a:0:{}s:5:"preco";s:5:"10.00";s:11:"obrigatorio";s:3:"nao";}

Next I apply unserialize function to t

at the 'nome_pt' field I'm getting a "Participa磯 no Congresso" ( Japanese character replacing the 'ç' and 'ão' )

The first value comes from php which puts that into a hidden input field.
The decodeURI works as expected.

Can anyone point out if this is a bug or I am missing something?
Regards

array_map doesn't support array callbacks

In PHP, one can supply array('Class', 'method') for static invocations, and array($instance, 'method') for non-static invocation of any callable type. PHPJS' array_map() function doesn't support this.

Pseudo-code, no error handling

  if (callback is array && callback.length == 2) {
    if (callback[0] is string) {
      func= global[callback[0]][callback[1]];
    } else {
      func= callback[0][callback[1]];
    }
  } else if (callback is string) {
     if (callback.contains('::')) {
       target= callback.split('::', 2);
       func= global[target[0]][target[1]];
     } else {
       func= global[callback];
     }
  } else {
     func= callback;
  }

I suppose most probably other functions handling callbacks are also affected by this, so a change should probably be done in a single, utility-style place. I'm new to this project, can you give me a pointer where to start?

bcscale not preserved

I'm seeing an issue where the bcscale is not preserved when using the bcmath functions. The following JS code should alert "0.33333", but it alerts "0" instead:

bcscale(5);
alert(bcdiv(1, 3));

It looks like it's occurring because each call to bcdiv calls this._phpjs_shared_bc() which returns a new libbcmath object each time.

This issue does not exist in the project https://sourceforge.net/projects/bcmath-js because libbcmath is a global object there.

Is there a way to preserve the bcscale() call with the way that php.js is including the libbcmath library?

"Notporting" Functions

With the advent of Node, it seems that many of the "Notporting" functions should now begin implementation. Thoughts?

preg_match, preg_replace, preg_split ?

Okay, I failed to find these 3 functions on your website and in the trunk. So, I wanted to give you these 3 functions because I made them few months ago...

preg_match works perfectly except for a known limitation as I didn't find any way to grab the index of every matching parenthesis so, if you set the flag 'PREG_OFFSET_CAPTURE', you will get '-1' as matching parenthesis' index. It uses 'is_array'.

preg_replace works perfectly except that I failed to return the value for the 'count' parameter: I accept the parameter, I set it in my function but outside of the function, the old value is still in place. (I don't know how the pass-by-reference thing is working in JS... for the 'matches' array parameter of preg_match, it seems to work ...). It uses 'is_array', 'is_null' and 'isset'.

preg_split: It uses 'is_null'. It behaves like the original PHP function. I just didn't know how to do the logic to be able to pass multiple flags at once. All flags are handled by the function but, currently, you can only use them independently. Like preg_match, if you have a complex pattern with more than one capturing group, the split will always work but, if you specify the flag PREG_SPLIT_OFFSET_CAPTURE, you will get -1 as index for all capturing groups.
So, if you can enhance them, feel free to do so.

Tristan

function preg_match(pattern, subject)
{
    var offset = ( arguments.length >= 5 ) ? arguments[4] : 0;
    var flags = ( arguments.length >= 4 ) ? arguments[3] : 0;
    var matches = ( arguments.length >= 3 ) ? arguments[2] : null;

    var result = null;
    var regexp = new RegExp(pattern);
    regexp.lastIndex = offset;

    if( (result = regexp.exec(subject)) )
    {
        if( is_array(matches) )
        {
            matches.splice(0, matches.length);

            for( i = 0; i < result.length; i ++ )
            {
                matches.push(( flags == 'PREG_OFFSET_CAPTURE' ) ? new Array(result[i].toString(), (( i == 0 ) ? result.index : -1)) : result[i].toString());
            }
        }

        return( 1 );
    }
    else
    {
        return( 0 );
    }
}

function preg_replace(pattern, replacement, subject)
{
    var count = ( arguments.length >= 5 ) ? arguments[4] : 0;
    var limit = ( arguments.length >= 4 ) ? arguments[3] : -1;

    new_subject = ( !is_array(subject) ) ? new Array(subject) : subject;
    new_pattern = ( !is_array(pattern) ) ? new Array(pattern) : pattern;

    var key_1;
    var key_2;
    var i = 0;

    for( key_1 in new_subject )
    {
        for( key_2 in new_pattern )
        {
            if( !is_array(replacement) )
            {
                var new_replacement = replacement;
            }
            else
            {
                var new_replacement = ( isset(replacement[key_2]) ) ? replacement[key_2] : '';
            }

            for( i = 0; is_null(limit) || limit == -1 || i < limit; )
            {
                var newest_subject = new_subject[key_1].replace(new_pattern[key_2], new_replacement);

                if( newest_subject != new_subject[key_1] )
                {
                    new_subject[key_1] = newest_subject;

                    i ++;
                }
                else
                {
                    break;
                }
            }

            count += i;
        }
    }

    return( ( !is_array(subject) ) ? new_subject[0] : new_subject );
}

function preg_split(pattern, subject)
{
    var flags = ( arguments.length >= 4 ) ? arguments[3] : 0;
    var limit = ( arguments.length >= 3 ) ? arguments[2] : -1;

    var splitted_subject = subject.split(pattern);

    var regexp = new RegExp(pattern.source, (( pattern.ignoreCase ) ? 'i' : '')+(( pattern.multiline ) ? 'm' : '')+'g');
    var match = null;

    var return_array = new Array();
    var position = 0;
    var i = 0;
    var j = 0;

    while( (match = regexp.exec(subject)) )
    {
        if( is_null(limit) || limit == -1 || i < limit )
        {
            if( flags == 'PREG_SPLIT_NO_EMPTY' && match.index == position )
            {
                continue;
            }
            else
            {
                i ++;
            }

            var string = subject.substr(position, match.index - position);

            return_array.push(( flags == 'PREG_SPLIT_OFFSET_CAPTURE' ) ? new Array(string, position) : string);

            position = match.index + match[0].length;

            if( flags == 'PREG_SPLIT_DELIM_CAPTURE' )
            {
                if( match.length == 2 && match[0] == match[1] )
                {
                    return_array.push(( flags == 'PREG_SPLIT_OFFSET_CAPTURE' ) ? new Array(match[0], match.index) : match[0]);
                }
                else
                {
                    for( j = 1; j < match.length; j ++ )
                    {
                        return_array.push(( flags == 'PREG_SPLIT_OFFSET_CAPTURE' ) ? new Array(match[j], -1) : match[j]);
                    }
                }
            }
        }
        else
        {
            break;
        }
    }

    if( position < subject.length )
    {
        var string = subject.substr(position);

        return_array.push(( flags == 'PREG_SPLIT_OFFSET_CAPTURE' ) ? new Array(string, position) : string);
    }

    return( return_array );
}

array_filter - wrong return type

array_filter should always return array (on success) and never an object !

something like this won't work cause of this issue

var A = [1,false,3];
A.length 
// result: 3

var B = array_filter( A );
B.length 
// undefined, but expected: 2

usage of utf-8 string not documented for base64 functions

Please document the usage of utf-8 characters in the base64 decode and encode functions

this code will yield incorrect result.

str = '✓ à la mode';
eStr = base64_encode(str);
console.log(str, '|', eStr);
console.log(base64_decode(eStr), '|', eStr, '|', str);

there should be necessary documentation that it could be easily fixed by escaping the string

like,

str = '✓ à la mode';
eStr = base64_encode(unescape(encodeURIComponent(str)));
console.log(str, '|', eStr);
console.log(decodeURIComponent(escape(base64_decode(eStr))), '|', eStr, '|', str);

Add a component.json file for Bower

Bower is a web package manager. It only handles dependencies and such.
Exemple file :

{
  "name": "phpjs",
  "version": "1.0.0",
  "main": "./build/phpjs.js",
  "dependencies": { }
}

AVG Virus Error in IE 9.0

After today's AVG update (Anti Virus Free Edition 2013) phpjs.min throws a "Virus found Script/Generic" error in IE 9.0 (but not in FF).

Compiled version + namespace

Hi! I'd just like to know how to get a compiled version of PHPJS and how to use the namespace. I looked for a "getting started" everywhere but I can't find any. Or maybe I missed a place.

Empty.js

Hi,

I've a question about "Empty.js".

If i do :

empty(val);

Where "val" is not set with "var val = something;"

the function works or an ReferenceError is send?

jslint

Go over all php.js functions and make them compliant with our jslinst standard.

Maybe we need to split this task up in several chunks since this obviously is a Lot of work?

Also, maybe we could automate some of the tedious parts.

strtotime fails on "monday"

When performing strtotime("next monday"), the result is equivalent to strtotime("next month");

In file: https://github.com/kvz/phpjs/blob/master/functions/datetime/strtotime.js
Line 97 should read: if (ranges.hasOwnProperty(range) && split[1].indexOf("day")<0)

And the regex should match whole words before abbreviations. eg lines 110-116 should read:
var regex = '([+-]?\d+\s' +
'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' +
'|sunday|sun.?|monday||mon.?|tuesday|tue.?|wednesday|wed.?' +
'|thursday|thu.?|friday|fri.?|saturday|sat.?)|(last|next)\s' +
'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' +
'|sunday|sun.?|monday|mon.?|tuesday|tue.?|wednesday|wed.?' +
'|thursday|thu.?|friday|fri.?|saturday|sat.?))(\sago)?';

Unit tests

I think this project would benefit from unit tests. There are some functions that work different from PHP for some argument variations and there are some functions that are implemented partially. If there were unit tests prepared, we could easily track progress and fix many issues.
Should we maybe agree on one JS unit testing framework that is easy to set up and run and place all tests in the /tests directory?

This project is pissing me off

It's cleanup time, boys.

The alien scum are on the way and I don't want them seeing embarrassing projects like this one. There's already enough things for them to make fun of like fat chicks and Walmart.

I've got balls of steel. I just don't have time for self::play().

implement token_get_all()

If we implement token_get_all(), we'd also, in the process, be
able to convert PHP to JavaScript. There are some very complex-seeming
and large tools like Antlr (also in JavaScript) which might do the job
but I didn't get too good of a feel for how it worked. I started
writing my own individualized parser, based on an EBNF grammar someone
prepared for PHP 5.2: http://www.icosaedro.it/articoli/php-syntax-ebnf.txt
and it seems it should be doable (I actually started writing an EBNF
parser based on EBNF of EBNF which could create a PHP or other parser
though haven't gotten around to debugging it yet). - Brett Zamir

echo() - TypeError: stringToDOM(...).cloneNode is not a function

Happens when trying to echo("<br>"); or any html code.
It also pops when you attempt to use var_dump("<pre>"); or anything else that uses echo function for printing out the results on a screen, and the printed value contains DOM element.

From Firebug:

TypeError: stringToDOM(...).cloneNode is not a function
..._xhtml, 'div').cloneNode(true); // We will not actually append the div tag (just...

Upper limit for array_multisort?

Is there an upper limit as far as what array_multisort can handle effectively? Or maybe a limit as to how many arrays it can take in? I ask because I may have hit it, that or I found a bug. I have an idea of what the results should look like in my case but when I get much above 50 items being sorted on 6 criteria I seem to have data being associated with the wrong values. I can try and debug further, but it is difficult since I can't use associative arrays due to the differences between IE, Chrome, and FF.

repo omits license files

website indicates phpjs is dual-licensed under MIT & GPL, but the license files appear to be omitted from the repo.

Implement Travis CI

  • Do it as a nodejs / php project
  • Write a little nodejs script that parses the function headers, executes the example code in php & a separate node process, compares the results.
  • Have a way to simply disable tests. This way we can first get this system live, then start working on fixing either testcases / functions

Profit because:

  • travis is free to open source
  • we can lose a lot of ugly 2007 legacy code
  • most contributors don't setup full dev environments, so testing is not done
  • github integration. e.g. github will say if a new branch can be merged based on travis tests that are automatically ran & integrated.

This will be a big boost for php.js quality in the long-run.

Anybody who feels up to this task and make name in php.js history?

bcsub produces erroneous result.

In PHP, the following code results in 0.018, which is correct:

$bcResult = bcsub(0.03, bcmul(0.03, 0.40, 3), 3);
var_dump($bcResult);

However, in PHPJS, that same code returns 0.001, which is incorrect:
var bcResult = bcsub(0.03, bcmul(0.03, 0.40, 3), 3);
console.debug(bcResult);

I have tested and bcmul for PHPJS works fine (i.e. the above bcmul(0.03, 0.40, 3) is correct). The problem is when doing the bcsub.

date_default_timezone_set overflows the stack

If I type this into the JavaScript console:

try { phpjs.date_default_timezone_set('Europe/London') } catch(e) { console.log([e.name, e.message, navigator.userAgent]); }

then the following is printed to the console:

["RangeError", "Maximum call stack size exceeded", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.57 Safari/537.1"]

Move the functions in a own namespace

Would be nice to scope the functions to a specific namespace.

an example:

    if (typeof php === 'undefined') var php = {};
    +function() {
        php.ltrim = function(str, charlist) {
            // http://kevin.vanzonneveld.net
            // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // + input by: Erkekjetter
            // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // + bugfixed by: Onno Marsman
            // * example 1: ltrim(' Kevin van Zonneveld ');
            // * returns 1: 'Kevin van Zonneveld '
             var whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
            charlist = !charlist ? whitespace : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
            var re = new RegExp('^[' + charlist + ']+', 'g');
            return (str + '').replace(re, '');
        };      
    }();

Usage:

console.log( php.ltrim(myString) );

Download fails

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 524288 bytes) in /var/git/cakephp1.2/cake/libs/model/datasources/dbo_source.php on line 932 Call Stack: 0.0000 645344 1. {main}() /var/git/phpjsweb/webroot/index.php:0 0.0060 2184904 2. Dispatcher->dispatch() /var/git/phpjsweb/webroot/index.php:52 0.0083 2416200 3. Dispatcher->_invoke() /var/git/cakephp1.2/cake/dispatcher.php:193 0.1007 5714632 4. Object->dispatchMethod() /var/git/cakephp1.2/cake/dispatcher.php:226 0.1007 5714712 5. PackagesController->download() /var/git/cakephp1.2/cake/libs/object.php:117 0.1007 5714712 6. Package->getByAny() /var/git/phpjsweb/controllers/packages_controller.php:535 0.1007 5717752 7. Model->find() /var/git/phpjsweb/models/package.php:180 0.1008 5722168 8. DboSource->read() /var/git/cakephp1.2/cake/libs/model/model.php:2040 0.1227 6033904 9. DboSource->queryAssociation() /var/git/cakephp1.2/cake/libs/model/datasources/dbo_source.php:680 1.6188 123958288 10. DboSource->__mergeHasMany() /var/git/cakephp1.2/cake/libs/model/datasources/dbo_source.php:788

[email protected] 05/08/2012

base64_decode appends invisible character

base64_decode("YQ===") returns the string "a" but its length is 4.
In fact, String.fromCharCode(0) returns an empty character of length 1.
atob in JS and base64_decode in PHP don't have this bug.

Escaped characters in php style date (date.js)

I was looking at datetime/date.js and I'm not sure the escaping behaves quite as it should.
The relevant RegExp is: /\\?([a-z])/gi

It works fine for detecting if a letter is immediately preceded by a slash, but doesn't take into account slashes that are themselves escaped. For example a format string of "H\\\\i\\\\s", should produce a result like "17\57\31", but would in fact see both i and s as escaped even though they're not.

I've been working from the same basic code from jsfromhell.com, and reinventing the wheel a bit since somehow I missed this version of the PHP style date function. Anyway, the regexp I've been using is: /(\\\\)*(\\?([a-Z]))/gi

This will match any paired backslashes first, and only catch any remnant ones as escape sequences for a format letter. So then all you need to do is throw it into:

formatChrCb = function(m, e, t, c) { return e + (f[t] ? f[t]() : c); };

Hopefully I've not completely misunderstood!

Utf-8 bug in php-unserialize.js

Hi, Kevin!
You have bug in https://github.com/kvz/phpjs/blob/master/functions/var/unserialize.js
That line is unnecessary:
76 length -= utf8Overhead(chr);
Serialized object, that reproduce the bug is:
a:12:{i:0;s:17:"Жесткость ботинка";i:1;s:7:"Кантинг";i:2;s:6:"Клипсы";i:3;s:13:"Производитель";i:4;s:6:"Размер";i:5;s:6:"Состав";i:6;s:13:"Срок гарантии";i:7;s:18:"Товарная подгруппа";i:8;s:41:"Уровень подготовки (по уровню подготовки)";i:9;s:14:"Ширина колодки";i:10;s:3:"Пол";i:11;s:9:"Возраст 1";}
here is output:
error:
WARNING: Error at offset 33 of 441 bytes

P.S. You can test it here: http://www.functions-online.com/unserialize.html

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.