Skip to content

Commit

Permalink
adding files
Browse files Browse the repository at this point in the history
  • Loading branch information
mikolalysenko committed Apr 10, 2013
0 parents commit 66f747c
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .gitignore
@@ -0,0 +1,15 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz

pids
logs
results

npm-debug.log
node_modules/*
43 changes: 43 additions & 0 deletions README.md
@@ -0,0 +1,43 @@
# dup
Initializes an n-dimensional array to a constant value.

## Install

npm install dup

## Example

```javascript
var dup = require("dup")

console.log(dup(5))

//Prints:
//
// [0, 0, 0, 0, 0]
//


console.log(dup([3,2], 1))

//Prints:
//
// [[1, 1],
// [1, 1],
// [1, 1]]
//
```

## `require("dup")(shape[, value])`
Initializes an array to a constant value

* `shape` Either an array of dimensions or a scalar, representing the shape of the array to create.
* `value` The value to initialize the array with. Default is 0

**Returns** An n-dimensional array with the given shape and value

## Rationale
I often find myself using [numeric.js'](http://www.numericjs.com/) `rep` method in my projects. However, for many things pulling in all of numeric.js is total overkill, especially for code that ultimately needs to run on the browser. So I decided to make this library which just implements the `rep` and nothing else in the spirit of promoting modularity by smaller and more numerous packages.

# Credits
(c) 2013 Mikola Lysenko. MIT License
49 changes: 49 additions & 0 deletions dup.js
@@ -0,0 +1,49 @@
"use strict"

function dupe_array(count, value, i) {
var c = count[i]|0
if(c <= 0) {
return []
}
var result = new Array(c), j
if(i === count.length-1) {
for(j=0; j<c; ++j) {
result[j] = value
}
} else {
for(j=0; j<c; ++j) {
result[j] = dupe_array(count, value, i+1)
}
}
return result
}

function dupe_number(count, value) {
var result, i
result = new Array(count)
for(i=0; i<count; ++i) {
result[i] = value
}
return result
}

function dupe(count, value) {
if(typeof value === "undefined") {
value = 0
}
switch(typeof count) {
case "number":
if(count > 0) {
return dupe_number(count|0, value)
}
break
case "object":
if(typeof (count.length) === "number") {
return dupe_array(count, value, 0)
}
break
}
return []
}

module.exports = dupe
29 changes: 29 additions & 0 deletions test/test.js
@@ -0,0 +1,29 @@
var dup = require("../dup.js")

require("tap").test("dup", function(t) {

t.equals(dup().length, 0)

var a = dup(5)
t.equals(a.length, 5)
for(var i=0; i<5; ++i) {
t.equals(a[i], 0)
}

var b = dup([3,2], 1)
t.equals(b.length, 3)
for(var i=0; i<3; ++i) {
var c = b[i]
t.equals(c.length, 2)
t.equals(c[0], 1)
t.equals(c[1], 1)
if(i > 0) {
t.assert(b[i] !== b[i-1])
}
}

var c = dup([], 100)
t.equals(c.length, 0)

t.end()
})

0 comments on commit 66f747c

Please sign in to comment.