Git Product home page Git Product logo

underscore.php's Introduction

Underscore.php

Underscore.php is a PHP port of Underscore.js.

In addition to porting Underscore's functionality, Underscore.php includes matching unit tests. Thanks to Jeremy Ashkenas and all contributors to Underscore.js.

For docs, license, tests, change log, and downloads, see: https://brianhaveri.github.io/Underscore.php/

underscore.php's People

Contributors

brianhaveri 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

underscore.php's Issues

Work with object methods too.

Hey !

We need some code to work with collections of objects. Sometimes we have gets and sets methods to work like ->name(), or get_name(), set_name(), getName()., getAge() , ..........

The underscore php need to be prepered to work with this methods. like: _::pluck($collection, $nameOfMethod, $arrayParams.)

__filter for associative arrays

I would love to see filter() be able to operate on associative arrays. There are so many cases you have a list of name-value pairs and you want to reduce this to a subset which is defined by a list of either values to exclude (black-list approach) or a list of to include only a list (white-list approach). I had hoped to have something like:

$start = array ( "one" => "monkey" , "two" => "donkey" , "three" => "beetle" );
$filter = array ( "two", "three" );

$list = ___::filter( $start, function ($value,$key) {
return in_array( $key , $filter );
});

I'd be interested to know if this is better achieved a different way (as I'm still relatively new to underscore) or whether this would be seen as a worthwhile extension to the functionality if I were to fork it off.

list() function causing problems

It seems the list() function is being used incorrectly:

list($one, $two) = array('one')

While this produces what is usually the desired result in the code ($one is set to 'one' and $two is set to NULL), this isn't technically a correct use of list() and produces an undefined offset notice.

__::chain($array) is not same with __($array)

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$result = __::chain($numbers)->select(function($n) { return $n < 5; })
                             ->reject(function($n) { return $n === 3; });


$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$result = __($numbers)->select(function($n) { return $n < 5; })
                             ->reject(function($n) { return $n === 3; });

__($array) doesn't support chaining

Context of anonymous function is lost

The context of where the function is being called is lost. This is very unfortunate when I want to do some nested 'each' functions. Is there a way to overcome this?

I write a function "object" Converts arrays into objects

I write this and share with you. Thanks a lot for your work
Converts arrays into objects
/**

  • Converts arrays into objects. Pass either a single list of [key, value] pairs,

  • or a list of keys, and a list of values. If duplicate keys exist, the last value wins.
    */
    public function object($list=null, $values=null) {
    if(is_null($list)) return self::_wrap(array());
    $return = array();
    foreach($list as $k=>$v) {
    if($values){
    $return[$v] = $values[$k] ;
    }
    else{
    $return[[$k][0]] = $values[$k][1];
    }
    }

    return self::_wrap($return);
    }

__::bind() and __::bindAll()

By implementing a references couldn't these two functions be implemented?

I can see a situation where they may be useful as a type of observer similar to backbone, although limited.

// My Model definitions
$person = new PersonModel();

$persons = new PersonsCollection();
$persons->add($person);

//... somewhere in the controller
public function broadcast() {
  $args = func_get_args();
  $persons = $args[0];
  $v1 = $args[1];
  $v2 = $args[2];
  $v3 = $args[3];
}

// add some controller events
__::bind($this->addRole, array(&$person), 1, 2, 3);
__::bind($this->broadcast, array(&$persons), 1, 2, 3);

Thinking about this more it may just be outside the scope of this project for bindAll, too many systems needed to manage events and triggering events.

Composer fails to download dev-master

I have problems downloading the dev-master of Underscore.php. I've created a new project with nothing else then composer as a requirement and composer fails:

pr@em-webdev-php53:~/projects/test$ ./composer.phar require underscore/Underscore.php
Please provide a version constraint for the underscore/Underscore.php requirement: dev-master
composer.json has been updated
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package underscore/underscore.php dev-master could not be found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

This is my composer.json:

{
    "name": "pr/foobar",
    "authors": [
        {
            "name": "pr",
            "email": "[email protected]"
        }
    ],
    "require": {
        "underscore/Underscore.php": "dev-master"

    }
}

When I change the version to 1.3.1 ist works:

pr@em-webdev-php53:~/projects/test$ ./composer.phar u
Loading composer repositories with package information
Updating dependencies
  - Installing underscore/underscore.php (1.3.1)
    Downloading: 100%

Writing lock file
Generating autoload files

I'm using the latest version of composer.

Memoize example doesn't work

The example for __::memoize doesn't work:

$fibonacci = function($n) use (&$fibonacci) {
  return $n < 2 ? $n : $fibonacci($n - 1) + $fibonacci($n - 2);
};
$fastFibonacci = __::memoize($fibonacci);

Computing $fastFibonacci(40) is no faster than $fibonacci(40), since $fibonacci calls into itself. Instead, the example should set $fibonacci = __::memoize($fibonacci) so that it calls into the memoized version.

Array by Reference

in javascript arrays are pass by reference and not by value like php does.

must of the time i need to pass the array by reference and not by value.
i think it's can be better that the library will work with array by reference?
what do you say?

Memoize default hashFunction can't recognize different Closures

Simple example first:

<?php
$foo = function($no) {
  return "Foo: {$no}\n";
};

$bar = function($no) {
  return "Bar: {$no}\n";
};

$foo_mem = __::memoize($foo);
$bar_mem = __::memoize($bar);

echo $foo_mem(5);
echo $bar_mem(5);

The output of this script is:

$ php test.php
Foo: 5
Foo: 5

It's because var_export can't properly export Closure's. It's better to use spl_object_hash() in hash function.
I have simple (and yet stupid) example of hash function:

<?php
$hash = function($function, $args) {
  return md5(join('_', array(
    spl_object_hash($function),
    var_export($args, true),
  )));
};

$foo = function($no) {
  return "Foo: {$no}\n";
};

$bar = function($no) {
  return "Bar: {$no}\n";
};

$foo_mem = __::memoize($foo, $hash);
$bar_mem = __::memoize($bar, $hash);

echo $foo_mem(5);
echo $bar_mem(5);

Maybe it's time to implement better default hash function? What do You think about it?
In free time, I'll try to propose my implementation of it.

Static invocations such as __::each raise E_STRICT warnings

Using the static method invocations, like __::each and __::map will raise E_STRICT warnings. For example, calling __::filter will raise this chain of warnings:

Array
(
    [number] => 2048
    [string] => Non-static method __::filter() should not be called statically
    [line] => 55
)
Array
(
    [number] => 2048
    [string] => Non-static method __::select() should not be called statically
    [file] => ../lib/underscore.php
    [line] => 182
)
Array
(
    [number] => 2048
    [string] => Non-static method __::_wrapArgs() should not be called statically
    [file] => ../lib/underscore.php
    [line] => 184
)
Array
(
    [number] => 2048
    [string] => Non-static method __::_collection() should not be called statically
    [file] => ../lib/underscore.php
    [line] => 186
)

As of PHP 5.4, E_STRICT is or'd into the E_ALL constant, so scripts that report all errors will show these.

documentation for iterator argument to uniq is confusing

I expected iterator to be called with each combination of elements, thus it would have a signature like:

$artist_files = __($artist_files)->uniq(false, function($a, $b){
    return $a->id == $b->id;
  });

Instead, I needed to change this to:

$artist_files = __($artist_files)->uniq(false, function($a){
    return $a->id;
  });

Clearly, the implementation provided by underscore.php is better than the one I expected. I just needed to read the source to understand what was up.

I think the reason I misunderstood this was because I did not realize that there is an assumed 1 to 1 mapping of uniquely identifying values for all possible inputs.

Anyway, a more thorough explanation of the iterator function would probably be a good idea.

Thanks!

isRegExp to use php last error?

I saw that isRegExp is not implemented yet. I have once before needed to know during run time whether or not a string is a regular expression string or not, and after a lot of research, I failed quite epicly. So I turned to stackoverflow where user ThiefMaster gave me some code that works:

ini_set('track_errors', 'on');
$php_errormsg = '';
@preg_match('/[blah/', '');
if($php_errormsg) echo 'regex is invalid';

Which works. Maybe this can be implemented as isRegExp? I'm not sure if it's a good idea though, hence why I'm asking.

Alternatively, maybe interoperability with a library like Flux?

groupBy will stop the chaining.

groupBy will stop the chaining.

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$result = __::chain($numbers)->select(function($n) { return $n < 5; })
                                                ->reject(function($n) { return $n === 3; })
                                                ->groupBy(function($n) { return $n % 2; })
                                                ->sortBy(function($n) { return -$n; })
                                                ->value();

no result

_::keys & _::values return private properties.

class test { public $var1 = 'My accessible variable'; private $var2 = 'My non-accessible variable'; } $obj = new test(); var_dump( __::keys ( $obj ) ); var_dump( __::values( $obj ) );

// array('var1','testvar2');
// array('My accessible variable','My non-accessible variable');

__ Naming conflict with Wordpress

I'm trying to use underscore.php with a Wordpress installation and unfortunately Wordpress uses the __() function call as part of it's translation/localisation functions. Is there a simple and tested way to move underscore into a non-conflicting namespace?

pluck does not pluck values if elements are of type ArrayAccess

In PHP it's possible to implement a custom array class, by implementing the ArrayAccess interface. That way you can use any instance of your class as be it an array. We had our own implementation of pluck which could handle elements that did this. But underscore's pluck doesn't seem to be able to handle these custom array types.

The line from our own implementation that checked for keys existence in elements, was:

if (isset($element[$key])) { // Must use isset instead of array_key_exists, because the latter does not work correctly on self implementing ArrayAccess classes.

Note the comment.

It would be great if underscore would support this too. We'd rather use your pluck version than our own.

IGNORE

โ— Sorry, wrong repository. Please delete this issue!

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.