{"size": 1987, "ext": "js", "max_stars_repo_path": "constructs/Slice.js", "max_stars_repo_name": "lo-language/velo", "max_stars_repo_stars_event_min_datetime": "2018-02-24T20:09:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T18:32:33.000Z", "max_issues_repo_path": "constructs/Slice.js", "max_issues_repo_name": "lo-language/velo", "max_issues_repo_issues_event_min_datetime": "2017-04-09T16:51:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-04T23:05:36.000Z", "max_forks_repo_path": "constructs/Slice.js", "max_forks_repo_name": "lo-language/velo", "max_forks_repo_forks_event_min_datetime": "2017-01-17T22:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-12T16:05:48.000Z"}
{"max_stars_count": 6, "max_issues_count": 14, "max_forks_count": 2, "avg_line_length": 22.3258426966, "max_line_length": 88, "alphanum_fraction": 0.4816305989}
/**=============================================================================
 *
 * Copyright (c) 2013 - 2018 Seth Purcell
 * Licensed under Apache License v2.0 with Runtime Library Exception
 *
 * See LICENSE.txt in the project root for license information.
 *
 =============================================================================*/

"use strict";

const JS = require('../codegen/JsPrimitives');
const LoConstruct = require('./LoConstruct');


class Slice extends LoConstruct {

    /**
     * A subscript expression
     *
     * @param array
     * @param start
     * @param end
     */
    constructor(array, start, end) {

        super();

        this.array = array;
        this.start = start;
        this.end = end;
    }

    /**
     * Returns the Lo AST for this node.
     */
    getAst() {

        var res = {
            type: 'slice',
            list: this.array.getAst()
        };

        if (this.start) {
            res.start = this.start.getAst();
        }

        if (this.end) {
            res.end = this.end.getAst();
        }

        return res;
    }

    /**
     * Returns the Lo AST for this node.
     */
    getTree() {

        return [
            'slice',
            this.array.getTree(),
            this.start ? this.start.getTree() : null,
            this.end ? this.end.getTree() : null
        ];
    }

    /**
     * Compiles this node to JS in the given context.
     *
     * @param sourceCtx
     * @param targetCtx
     */
    compile(sourceCtx, targetCtx) {

        // lean on JS slice since it has the same semantics

        var list = this.array.compile(sourceCtx, targetCtx);
        var start = this.start ? this.start.compile(sourceCtx, targetCtx) : JS.num('0');
        var end = this.end ? this.end.compile(sourceCtx, targetCtx) : null;

        return JS.fnCall(
            JS.select(list, 'slice'),
            end ? [start, JS.add(end, JS.num('1'))] : [start]
        );
    }
}

module.exports = Slice;