Skip to content

Commit eee837f

Browse files
committed
Add ensure array lib function to allocate/resize
1 parent b32c21d commit eee837f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/lib/ensure_array.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Copyright 2012-2017, Plotly, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
'use strict';
10+
11+
/*
12+
* Ensures an array has the right amount of storage space. If it doesn't
13+
* exist, it creates an array. If it does exist, it returns it if too
14+
* short or truncates it in-place.
15+
*
16+
* The goal is to just reuse memory to avoid a bit of excessive garbage
17+
* collection.
18+
*/
19+
module.exports = function ensureArray(out, n) {
20+
if(!Array.isArray(out)) out = [];
21+
22+
// If too long, truncate. (If too short, it will grow
23+
// automatically so we don't care about that case)
24+
out.length = n;
25+
26+
return out;
27+
};

src/lib/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ lib.isArray = require('./is_array');
1919
lib.mod = require('./mod');
2020
lib.toLogRange = require('./to_log_range');
2121
lib.relinkPrivateKeys = require('./relink_private');
22+
lib.ensureArray = require('./ensure_array');
2223

2324
var coerceModule = require('./coerce');
2425
lib.valObjects = coerceModule.valObjects;

0 commit comments

Comments
 (0)