time-to-botec/js/node_modules/@stdlib/ndarray/base/buffer/lib/main.js

103 lines
2.2 KiB
JavaScript
Raw Normal View History

/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bufferCtors = require( './../../../base/buffer-ctors' );
var allocUnsafe = require( '@stdlib/buffer/alloc-unsafe' );
var zeros = require( './zeros.js' );
// FUNCTIONS //
/**
* Returns a zero-filled generic array.
*
* @private
* @param {NonNegativeInteger} size - buffer size
* @returns {Array} zero-filled generic array
*/
function generic( size ) {
var buf;
var i;
buf = [];
for ( i = 0; i < size; i++ ) {
buf.push( 0 );
}
return buf;
}
/**
* Returns a zero-filled binary buffer.
*
* @private
* @param {NonNegativeInteger} size - buffer size
* @returns {Buffer} zero-filled binary buffer
*/
function binary( size ) {
return zeros( allocUnsafe( size ) );
}
/**
* Returns a zero-filled typed array.
*
* @private
* @param {string} dtype - data type
* @param {NonNegativeInteger} size - buffer size
* @returns {(TypedArray|null)} zero-filled typed array
*/
function typedarray( dtype, size ) {
var ctor = bufferCtors( dtype );
if ( ctor ) {
return new ctor( size );
}
return null;
}
// MAIN //
/**
* Returns a zero-filled contiguous linear ndarray data buffer.
*
* @param {string} dtype - data type
* @param {NonNegativeInteger} size - buffer size
* @returns {(Array|TypedArray|Buffer|null)} data buffer
*
* @example
* var buf = buffer( 'float64', 3 );
* // returns <Float64Array>[ 0.0, 0.0, 0.0 ]
*/
function buffer( dtype, size ) {
if ( dtype === 'generic' ) {
return generic( size );
}
if ( dtype === 'binary' ) {
return binary( size );
}
return typedarray( dtype, size );
}
// EXPORTS //
module.exports = buffer;